在学knn最邻近分类时,原始数据根据参数Q1、Q2分为type=T1、type=T2两种;
执行
knn
= neighbors
.KNeighborsClassifier()
knn
.fit(df
[['Q1','Q2']],df
['type'])
knn
.predict([35,26])
报错
ValueError: Expected 2D array, got 1D array instead: array=[35 26]. 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.
在尝试了
np
.array([35,26]).reshape(1,-1)
结果为 之后,了解到把一维数组改为二维数组只要外层加一个[]就可以了,可以省去reshape。
最终代码
knn
= neighbors
.KNeighborsClassifier()
knn
.fit(df
[['Q1','Q2']],df
['type'])
knn
.predict([[35,26]])
运行结果