在對模型進行預測時,如使用sklearn中的KNN模型,
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier()
knn.fit(x,y)
x_new = [50000,8,1.2]
y_pred = knn.predict(x_new)
會報錯
ValueError: Expected 2D array, got 1D array instead:
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
這是由于在新版的sklearn中,所有的數據都應該是二維矩陣,哪怕它只是單獨一行或一列(比如前面做預測時,僅僅只用了一個樣本數據),所以需要使用.reshape(1,-1)進行轉換,具體操作如下。
需改為
x_new = np.array(x_new).reshape(1, -1)
y_pred = knn.predict(x_new)
測試有效。