2017-08-07 15 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