机器学习-KNN算法示例

python 复制代码
# 导入鸢尾花数据集
from sklearn.datasets import load_iris
# 导入K近邻分类器
from sklearn.neighbors import KNeighborsClassifier
# 导入标准化预处理器
from sklearn.preprocessing import StandardScaler
# 导入数据集划分工具
from sklearn.model_selection import train_test_split

# 加载鸢尾花数据集
data1 = load_iris()
# 将数据集划分为训练集和测试集,random_state=22 保证每次划分结果一致
x_train, x_test, y_train, y_test = train_test_split(data1.data, data1.target, random_state=22)

# 创建标准化对象
trans = StandardScaler()
# 对训练集进行标准化拟合与转换
x_train = trans.fit_transform(x_train)
# 对测试集进行标准化转换(使用训练集的统计信息)##这样才能保证准确性
x_test = trans.transform(x_test)

# 创建K近邻分类器对象,设置邻居数为5
em = KNeighborsClassifier(n_neighbors=5)
# 使用训练集数据训练模型
em.fit(x_train, y_train)
# 使用测试集特征数据进行预测
y_predict = em.predict(x_test)
# 输出模型在测试集上的准确率
print(em.score(x_test, y_test))

使用交叉验证与网格搜索优化

python 复制代码
# 导入鸢尾花数据集
from sklearn.datasets import load_iris
# 导入K近邻分类器
from sklearn.neighbors import KNeighborsClassifier
# 导入标准化预处理器
from sklearn.preprocessing import StandardScaler
# 导入数据集划分工具
from sklearn.model_selection import train_test_split,GridSearchCV

# 加载鸢尾花数据集
data1 = load_iris()
# 将数据集划分为训练集和测试集,random_state=22 保证每次划分结果一致
x_train, x_test, y_train, y_test = train_test_split(data1.data, data1.target, random_state=22)

# 创建标准化对象
trans = StandardScaler()
# 对训练集进行标准化拟合与转换
x_train = trans.fit_transform(x_train)
# 对测试集进行标准化转换(使用训练集的统计信息)##这样才能保证准确性
x_test = trans.transform(x_test)

# 创建K近邻分类器对象
em = KNeighborsClassifier()
##使用网格搜索与交叉验证实现最优K值的搜索param_grid要用字典的形式给出,cv=10表示是10折
em=GridSearchCV(em,param_grid={'n_neighbors':[1,2,3,4,5,6,7,8,9,10]},cv=10)

# 使用训练集数据训练模型,模型进行训练和预测的时候是把param_grid中的每一个值都测试了一遍
em.fit(x_train, y_train)
# 使用测试集特征数据进行预测,选用测试结果最好的哪个进行预测
y_predict = em.predict(x_test)
# 输出模型在测试集上的准确率
print(em.score(x_test, y_test))##整体最好的准确率
print(em.best_params_)##最好的K值
print(em.best_score_)##10折里最优的准确率

score与best_score的不同:

相关推荐
程序员cxuan3 分钟前
Anthropic:session 之间可以相互通信了
人工智能·后端·程序员
GEOshijie12312 分钟前
GEO服务商算法适配承诺怎么验收?48小时响应的合同化考核方案
人工智能·python
wordbaby21 分钟前
大模型 API 核心概念笔记
人工智能
疯狂打码的少年27 分钟前
【数据结构】树的基本概念与二叉树定义
java·数据结构·笔记·算法
webmote3327 分钟前
用 NVIDIA Nemotron 3 Super + .NET 构建有记忆的多轮对话
后端·算法
hrrrrxeeeee31 分钟前
业务岗简历 AI 加分指南:CAIE、国考证书搭配量化案例写法
人工智能
Keven_1133 分钟前
算法札记:区分稀疏图与稠密图在经验上的数学计算差异
算法·稠密图·稀疏图
yingyuecom36 分钟前
Hi,导演:AI视频创作正在从“模型调用”走向“生产工作流”
大数据·人工智能
雨晨源码(同名B站)38 分钟前
基于深度学习YoloV11农业病害虫害检测系统 智慧农业信息化综合管理平台 (附源码+lw文档+ppt)
数据库·人工智能·深度学习·yolo·信息可视化
weixin_446260851 小时前
列表式交叉编码器微调 vs 智能体指令优化大模型重排器:医保医疗流程重排序系统性研究
人工智能