• KNN-水仙花的分类


    题目:

    思路:

    1、处理数据集,这里用的是题目已知的数据集,所以说需要提前将写好的数据放到excel表格里,再进行读取。

    2、将数据集划分为训练集和测试集

    3、定义K-NN模型。

    4、训练模型

    5、预测模型

    6、计算分类精度

    7、使用网格搜索法

    8、训练模型

    9、可视化

    结果:

    大致就是这样,代码如下:

    1. #加载数据集
    2. import numpy as np
    3. import pandas as pd
    4. from matplotlib import pyplot as plt
    5. from matplotlib.colors import ListedColormap
    6. from sklearn.metrics import accuracy_score
    7. from sklearn.model_selection import train_test_split, GridSearchCV
    8. from sklearn.neighbors import KNeighborsClassifier
    9. import warnings
    10. warnings.filterwarnings('ignore')
    11. import matplotlib
    12. print(matplotlib.matplotlib_fname())
    13. # 加载数据集
    14. def read():
    15. filename = r"水仙花.xlsx"
    16. data = pd.read_excel(filename, header=None)
    17. x1 = data.iloc[1:, [0, 1]].values
    18. x2 = data.iloc[1:, [3, 4]].values
    19. # print(x2)
    20. y1 = data.iloc[1:, 2].values
    21. y2 = data.iloc[1:, 5].values
    22. X = np.vstack((x1, x2)) # 竖向合并
    23. y = np.hstack((y1, y2)) # 横向合并
    24. y = y.astype(int)
    25. return X, y
    26. # 划分训练集和测试集
    27. X,y=read()
    28. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
    29. # 定义K-NN模型
    30. knn = KNeighborsClassifier(n_neighbors=3) # 设置k=3
    31. #训练模型
    32. knn.fit(X_train, y_train)
    33. #预测测试集
    34. y_pred = knn.predict(X_test)
    35. #计算分类精度
    36. accuracy = accuracy_score(y_test, y_pred)
    37. print('分类精度:', accuracy)
    38. # 使用网格搜索找到最佳参数
    39. param_grid = {'n_neighbors': [1,3, 5, 7, 9]} # 尝试不同的k值
    40. grid_search = GridSearchCV(knn, param_grid, cv=5)
    41. #训练模型
    42. grid_search.fit(X_train, y_train)
    43. print('最佳参数:', grid_search.best_params_)
    44. print('最佳分类精度:', grid_search.best_score_)
    45. #可视化
    46. #绘制散点图
    47. cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])
    48. cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])
    49. x_min, x_max = X[:, 0].min() - 0.1, X[:, 0].max() + 0.1
    50. y_min, y_max = X[:, 1].min() - 0.1, X[:, 1].max() + 0.1
    51. xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02))
    52. Z = knn.predict(np.c_[xx.ravel(), yy.ravel()])
    53. Z = Z.reshape(xx.shape)
    54. plt.figure()
    55. plt.pcolormesh(xx, yy, Z, cmap=cmap_light)
    56. # 绘制训练样本和测试样本
    57. plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cmap_bold, edgecolor='k')
    58. plt.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap=cmap_bold, marker='x', edgecolor='k')
    59. plt.xlim(xx.min(), xx.max())
    60. plt.ylim(yy.min(), yy.max())
    61. plt.title('K-NN分类(k=3)')
    62. plt.show()

     可能出现的问题:

    图片中中文无法显现,原因是配置文件中没有配置中文库,解决办法:

    首先打印出配置文件所在的目录:

    代码如下:

    1. import matplotlib
    2. print(matplotlib.matplotlib_fname())

     然后根据地址找到相应文件,ctr+f搜索font.family,找到下面图片中的两行

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

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

  • 相关阅读:
    BAT大厂Java面试,如何抓住面试重点知识?收割大厂offer
    SSM17:注解开发管理第三方bean
    Java @PreDestroy 注解的使用
    Java并发基石—CAS原理实战
    7、GC日志详解
    初识springmvc
    第二证券:知名私募美股持仓曝光 科技与消费板块成“心头好”
    基于混合策略改进的鲸鱼优化算法
    unity 全景视频播放全景图片转换(学习)
    【Ubuntu笔记】录屏安装
  • 原文地址:https://blog.csdn.net/qq_62649563/article/details/134012928