1 import numpy as np 2 from sklearn import datasets #数据集 3 from sklearn.model_selection import train_test_split #train_test_split用来把数据分为训练集和测试集 4 from sklearn.neighbors import KNeighborsClassifier #引人KNN算法 5 iris = datasets.load_iris() #从datasets里载入iris的数据 6 iris_X = iris.data 7 iris_y = iris.target 8 X_train,X_test,y_train,y_test = train_test_split(iris_X,iris_y,test_size=0.3) #分割训练集和测试集 9 knn = KNeighborsClassifier() 10 knn.fit(X_train,y_train) #训练
用训练好的knn做预测
1 print(knn.predict(X_test)) #打印预测结果 2 print(y_test) #打印真实结果 3 [1 1 0 0 2 0 2 1 0 1 0 2 2 0 2 2 1 2 1 0 1 1 1 0 2 1 1 0 0 1 1 0 1 1 1 0 2 1 2 0 2 0 1 1 1] 4 [1 1 0 0 2 0 2 1 0 1 0 2 2 0 2 2 2 2 1 0 1 1 1 0 2 1 1 0 0 1 1 0 1 1 1 0 2 1 2 0 1 0 1 1 1]