
1、处理数据集,这里用的是题目已知的数据集,所以说需要提前将写好的数据放到excel表格里,再进行读取。
2、将数据集划分为训练集和测试集
3、定义K-NN模型。
4、训练模型
5、预测模型
6、计算分类精度
7、使用网格搜索法
8、训练模型
9、可视化
结果:


- #加载数据集
- import numpy as np
- import pandas as pd
- from matplotlib import pyplot as plt
- from matplotlib.colors import ListedColormap
- from sklearn.metrics import accuracy_score
- from sklearn.model_selection import train_test_split, GridSearchCV
- from sklearn.neighbors import KNeighborsClassifier
- import warnings
- warnings.filterwarnings('ignore')
-
- import matplotlib
- print(matplotlib.matplotlib_fname())
-
- # 加载数据集
- def read():
- filename = r"水仙花.xlsx"
- data = pd.read_excel(filename, header=None)
- x1 = data.iloc[1:, [0, 1]].values
- x2 = data.iloc[1:, [3, 4]].values
- # print(x2)
- y1 = data.iloc[1:, 2].values
- y2 = data.iloc[1:, 5].values
- X = np.vstack((x1, x2)) # 竖向合并
- y = np.hstack((y1, y2)) # 横向合并
- y = y.astype(int)
- return X, y
- # 划分训练集和测试集
- X,y=read()
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
- # 定义K-NN模型
- knn = KNeighborsClassifier(n_neighbors=3) # 设置k=3
- #训练模型
- knn.fit(X_train, y_train)
- #预测测试集
- y_pred = knn.predict(X_test)
- #计算分类精度
- accuracy = accuracy_score(y_test, y_pred)
- print('分类精度:', accuracy)
-
- # 使用网格搜索找到最佳参数
- param_grid = {'n_neighbors': [1,3, 5, 7, 9]} # 尝试不同的k值
- grid_search = GridSearchCV(knn, param_grid, cv=5)
- #训练模型
- grid_search.fit(X_train, y_train)
- print('最佳参数:', grid_search.best_params_)
- print('最佳分类精度:', grid_search.best_score_)
- #可视化
- #绘制散点图
- cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])
- cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])
-
- x_min, x_max = X[:, 0].min() - 0.1, X[:, 0].max() + 0.1
- y_min, y_max = X[:, 1].min() - 0.1, X[:, 1].max() + 0.1
- xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02))
- Z = knn.predict(np.c_[xx.ravel(), yy.ravel()])
- Z = Z.reshape(xx.shape)
-
- plt.figure()
- plt.pcolormesh(xx, yy, Z, cmap=cmap_light)
- # 绘制训练样本和测试样本
- plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cmap_bold, edgecolor='k')
- plt.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cmap_bold, marker='x', edgecolor='k')
-
- plt.xlim(xx.min(), xx.max())
- plt.ylim(yy.min(), yy.max())
- plt.title('K-NN分类(k=3)')
- plt.show()

图片中中文无法显现,原因是配置文件中没有配置中文库,解决办法:
首先打印出配置文件所在的目录:

代码如下:
- import matplotlib
- print(matplotlib.matplotlib_fname())
然后根据地址找到相应文件,ctr+f搜索font.family,找到下面图片中的两行

然后,将其注释符号全部删掉,并在font.sans-serif中添加中文字体名称

这样再重新运行程序代码即可。