当前位置: 首页 > news >正文

KNN-水仙花的分类

题目:

思路:

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]].valuesx2 = data.iloc[1:, [3, 4]].values# print(x2)y1 = data.iloc[1:, 2].valuesy2 = data.iloc[1:, 5].valuesX = 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中添加中文字体名称

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

http://www.lryc.cn/news/204969.html

相关文章:

  • Kotlin 如何确定协程是否启动
  • 【Spring Boot】Spring Boot集成RabbitMQ
  • Hadoop部署过程中问题总结
  • 低成本IC上岸攻略—IC设计网课白嫖篇
  • BootLoader为什么要分阶段?
  • Centos8: 安装python2, 并设置默认版本
  • 【逆向】导入表注入
  • Unity游戏开发中打造游戏攻击技能架构与设计
  • 【微信小程序开发】小程序微信用户授权登录(用户信息手机号)
  • VSCode 自动格式化
  • 数据库、数据仓库相关
  • 【STM32】RCC时钟模块(使用HAL库)
  • WPF中的绑定知识详解(含案例源码分享)
  • 【JVM】类的生命周期
  • asp.net网上商城系统VS开发sqlserver数据库web结构c#编程Microsoft Visual Studio协同过滤设计
  • APUS入驻百度灵境矩阵,普惠AI大模型插件能力
  • 通过C++调用Com接口
  • 完全背包问题
  • J2EE的N层体系结构
  • Quirks(怪癖)模式是什么?它和 Standards(标准)模式有什么区别?
  • 自然语言处理---Transformer模型
  • 动画系统的前世今生(一)
  • 11 结构型模式- 代理模式
  • Unity--用户界面
  • BUUCTF 乌镇峰会种图 1
  • Runner GoUI自动化测试发布
  • 【Gensim概念】03/3 NLP玩转 word2vec
  • 【网络协议】聊聊网络路由相关算法
  • Python 深度学习入门之CNN
  • 国产开发板上打造开源ThingsBoard工业网关--基于米尔芯驰MYD-JD9X开发板