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

相关推荐
搞科研的小刘选手1 小时前
【厦门大学主办】第六届计算机科学与管理科技国际学术会议(ICCSMT 2025)
人工智能·科技·计算机网络·计算机·云计算·学术会议
fanstuck1 小时前
深入解析 PyPTO Operator:以 DeepSeek‑V3.2‑Exp 模型为例的实战指南
人工智能·语言模型·aigc·gpu算力
萤丰信息1 小时前
智慧园区能源革命:从“耗电黑洞”到零碳样本的蜕变
java·大数据·人工智能·科技·安全·能源·智慧园区
世洋Blog1 小时前
更好的利用ChatGPT进行项目的开发
人工智能·unity·chatgpt
serve the people5 小时前
机器学习(ML)和人工智能(AI)技术在WAF安防中的应用
人工智能·机器学习
gfdhy5 小时前
【c++】哈希算法深度解析:实现、核心作用与工业级应用
c语言·开发语言·c++·算法·密码学·哈希算法·哈希
百***06015 小时前
SpringMVC 请求参数接收
前端·javascript·算法
0***K8925 小时前
前端机器学习
人工智能·机器学习
陈天伟教授5 小时前
基于学习的人工智能(5)机器学习基本框架
人工智能·学习·机器学习
m0_650108245 小时前
PaLM-E:具身智能的多模态语言模型新范式
论文阅读·人工智能·机器人·具身智能·多模态大语言模型·palm-e·大模型驱动