代码

from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
import numpy as np

iris=datasets.load_iris() #加载本地iris数据
iris_x=iris.data
iris_y=iris.target
print(type(iris_x),iris_x.shape)

for key,value in iris.items():
print(key)

#将数据 随机 拆分成训练数据和测试数据,为7:3,拆分后的顺序是乱的
x_train,x_test,y_train,y_test=train_test_split(iris_x,iris_y,test_size=0.33)
print(y_test)

knn=KNeighborsClassifier(n_neighbors=7) # 使用KNN分类
print(knn)
knn.fit(x_train,y_train) # 训练

y_predict=knn.predict(x_test) # 预测

p_true=np.sum(y_predict==y_test)
print( "正确率:{0:.01%} {1}/{2}".format(p_true/len(y_test),p_true,len(y_test)))

运行结果

python sklearn中的KNN_测试数据

​关于更多​

jupyter学习过程

​github链接​