from sklearn import datasets #导入数据模块
from sklearn.model_selection import train_test_split #导入切分训练集、测试集模块
from sklearn.neighbors import KNeighborsClassifier as KNN
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
#加载数据
iris=datasets.load_iris()
iris_x=iris['data']
iris_y=iris['target']
#切分数据集为训练集和测试集,其中test_size为0.3
x_train,x_test,y_train,y_test=train_test_split(iris_x,iris_y,test_size=0.3)
#训练+预测
knn=KNN(n_neighbors=3) #实例化knn模型,这里可以选择k的值
knn.fit(x_train,y_train) #放入训练集进行训练
print(knn.predict(x_test)) #预测标签
print(y_test) #实际标签
|