机器学习-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的不同:

相关推荐
不正经学生4 小时前
C语言预处理详解:编译器真正动手之前的那些事
c语言·开发语言·算法·面试·bug
漂流瓶jz5 小时前
【AI】大模型本地部署与量化:Ollama、transformers、llama.cpp实践
人工智能·llm·ai编程
毕竟是shy哥6 小时前
计算YOLO数据集中每个类的目标数
算法·yolo·机器学习
M78佐菲6 小时前
Linux学习笔记:TCP协议
linux·笔记·学习·tcp/ip·算法
飞哥数智坊6 小时前
AI时代,我们到底该学什么、用什么,为什么还没提效?
人工智能
飞哥数智坊6 小时前
GPT 做架构,国内模型写代码:这条 AI 开发路线能跑通吗?
人工智能·ai编程
AI_AGENT_DEV_AI7 小时前
AI 智能体的开发与上线
人工智能
VL——MOESR7 小时前
【具身智能】VLA论文阅读随笔
论文阅读·人工智能·机器学习·具身智能·vla
OCR_133716212757 小时前
从模板匹配到AI泛化识别:文本抽取如何重构护照阅读器落地生态
人工智能·重构
大唐荣华7 小时前
从OpenAI关停Sora看世界模型、AI视频与国内具身智能赛道路线分化
人工智能·openai·sora·内容生成