在对模型进行预测时,如使用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)
测试有效。
作者:Python_Franklin
链接:https://www.jianshu.com/p/60596270e94e
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。