在對(duì)模型進(jìn)行預(yù)測(cè)時(shí)缤弦,如使用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)
會(huì)報(bào)錯(cuò)
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中算吩,所有的數(shù)據(jù)都應(yīng)該是二維矩陣,哪怕它只是單獨(dú)一行或一列(比如前面做預(yù)測(cè)時(shí)佃扼,僅僅只用了一個(gè)樣本數(shù)據(jù))偎巢,所以需要使用.reshape(1,-1)進(jìn)行轉(zhuǎn)換,具體操作如下兼耀。
需改為
x_new = np.array(x_new).reshape(1, -1)
y_pred = knn.predict(x_new)
測(cè)試有效压昼。