2017-08-07 18 views
8

我下面这个教程,使这个ML预测:使用Python 3.6Python脚本错误“预期的二维数组,而不是1D数组:”?

Link Tutorial

import numpy as np 
import matplotlib.pyplot as plt 
from matplotlib import style 

style.use("ggplot") 
from sklearn import svm 

x = [1, 5, 1.5, 8, 1, 9] 
y = [2, 8, 1.8, 8, 0.6, 11] 

plt.scatter(x,y) 
plt.show() 

X = np.array([[1,2], 
      [5,8], 
      [1.5,1.8], 
      [8,8], 
      [1,0.6], 
      [9,11]]) 

y = [0,1,0,1,0,1] 
X.reshape(1, -1) 

clf = svm.SVC(kernel='linear', C = 1.0) 
clf.fit(X,y) 

print(clf.predict([0.58,0.76])) 

Im和我得到错误“预期二维数组,得到了一维数组,而不是:”我 觉得剧本是为旧版本,但我不知道如何将其转换为3.6版本。

已经与尝试:

X.reshape(1, -1) 
+3

哪一行产生错误? – stackoverflowuser2010

+1

'X = X.reshape(1,-1)'。重塑不在原位。 –

+2

@ stackoverflowuser2010:我猜猜最后一行'clf.predict()',因为'X'已经是二维的了(无用的''重塑'尽管如此)。 –

回答

14

你只是应该提供predict方法用相同的二维数组,但要处理(或更多)的一个值。总之,只需更换

[0.58,0.76] 

随着

[[0.58,0.76]] 

,它应该工作

+1

工程就像一个魅力! – JonTargaryen

+2

但为什么这样工作?我不明白这个问题是什么。 –

5

问题发生时,你的阵列[0.58,0.76]上运行的预测。在调用之前通过重塑它来解决问题predict()

import numpy as np 
import matplotlib.pyplot as plt 
from matplotlib import style 

style.use("ggplot") 
from sklearn import svm 

x = [1, 5, 1.5, 8, 1, 9] 
y = [2, 8, 1.8, 8, 0.6, 11] 

plt.scatter(x,y) 
plt.show() 

X = np.array([[1,2], 
      [5,8], 
      [1.5,1.8], 
      [8,8], 
      [1,0.6], 
      [9,11]]) 

y = [0,1,0,1,0,1] 

clf = svm.SVC(kernel='linear', C = 1.0) 
clf.fit(X,y) 

test = np.array([0.58, 0.76]) 
print test  # Produces: [ 0.58 0.76] 
print test.shape # Produces: (2,) meaning 2 rows, 1 col 

test = test.reshape(1, -1) 
print test  # Produces: [[ 0.58 0.76]] 
print test.shape # Produces (1, 2) meaning 1 row, 2 cols 

print(clf.predict(test)) # Produces [0], as expected