KNN算法对鸢尾花进行分类:添加网格搜索和交叉验证

优化------添加网格搜索和交叉验证

python 复制代码
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV
#KNN算法对鸢尾花进行分类:添加网格搜索和交叉验证

#1、获取数据
iris = load_iris()
#2、数据集划分
x_train,x_test,y_train,y_test = train_test_split(iris.data,iris.target,random_state = 22)
#3、特征工程------标准化
transfer = StandardScaler()
x_train = transfer.fit_transform(x_train)
x_test = transfer.transform(x_test)
#4、KNN算法预估器
estimator = KNeighborsClassifier()

#加入网格搜索和交叉验证
#参数准备
param_dict = {"n_neighbors":[1,3,5,7,9,11]}
estimator = GridSearchCV(estimator,param_grid = param_dict,cv=10)

estimator.fit(x_train,y_train)
#5、模型评估
#方法一:直接比对真实值和预测值
y_predict = estimator.predict(x_test)
print("y_predict:\n",y_predict)
print("对真实值和预测值:\n",y_test == y_predict)
#方法二:计算准确率
score = estimator.score(x_test,y_test)
print("准确值为:\n",score)

#最佳参数best_params_
print("最佳参数:\n",estimator.best_params_)
#最佳结果best_score_
print("最佳结果:\n",estimator.best_score_)
#最佳估计量best_estimator_
print("最佳估计量:\n",estimator.best_estimator_)
#交叉验证结果
print("交叉验证结果:\n",estimator.cv_results_)
相关推荐
Zzj_tju7 分钟前
32 分钟不是完成科研:多智能体读脑图谱,突破在哪里?
人工智能·机器学习·语言模型·自然语言处理
数聚天成DeepSData4 小时前
外部标注需求里该写清哪几项,样例包才验收得动
人工智能·深度学习·机器学习·数据集·deepsdata
Rocky Ding*4 小时前
【三年面试五年模拟】2026-10-21_零一万物知识图谱算法实习生一面面经全解析
论文阅读·人工智能·深度学习·机器学习·aigc·知识图谱·ai-native
人工智能培训4 小时前
具身智能:让人工智能拥有物理世界感知能力
大数据·人工智能·学习·算法·机器学习
Rocky Ding*5 小时前
【三年面试五年模拟】2026-10-20_淘天AI应用研发一面面经全解析
论文阅读·人工智能·深度学习·机器学习·面试·aigc·ai-native
数聚天成DeepSData6 小时前
Landsat 影像去哪里下载:选景、批量与脚本检索怎么选
人工智能·深度学习·机器学习·数据集·deepsdata
小蒋观天下6 小时前
【无标题】红外补光近距过曝、远距欠曝:导致车牌AI识别失效调试
人工智能·深度学习·数码相机·算法·机器学习·ai大模型
段一凡-华北理工大学7 小时前
高炉炼铁机器视觉与智能识别十八讲~系列文章17:实战案例:一个风口监控系统的完整搭建
人工智能·pytorch·深度学习·机器学习·计算机视觉·高炉风口监测系统
WenGyyyL8 小时前
从零理解强化学习:为什么 AI 需要 Advantage,而不只是 Reward?
人工智能·python·深度学习·机器学习·nlp
鬼手点金9 小时前
带工具调用的多轮交互:Agent 的核心循环
服务器·人工智能·windows·深度学习·microsoft·机器学习·交互