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_)
相关推荐
AI科技星7 小时前
质量定义方程常数k = 4π m_p的来源、推导与意义
服务器·数据结构·人工智能·科技·算法·机器学习·生活
smile_Iris7 小时前
Day 40 复习日
人工智能·深度学习·机器学习
火山kim8 小时前
经典论文研读报告:DAGGER (Dataset Aggregation)
人工智能·深度学习·机器学习
Coding茶水间8 小时前
基于深度学习的水果检测系统演示与介绍(YOLOv12/v11/v8/v5模型+Pyqt5界面+训练代码+数据集)
图像处理·人工智能·深度学习·yolo·目标检测·机器学习·计算机视觉
lisw059 小时前
人工智能伦理与科技向善有何区别与联系?
人工智能·机器学习
JoannaJuanCV11 小时前
自动驾驶—CARLA仿真(25)synchronous_mode demo
人工智能·机器学习·自动驾驶·carla
鲨莎分不晴11 小时前
强化学习第七课 —— 策略网络设计指南:赋予 Agent“大脑”的艺术
网络·人工智能·机器学习
JoannaJuanCV12 小时前
自动驾驶—CARLA仿真(7)vehicle_physics demo
人工智能·机器学习·自动驾驶
听风吹等浪起12 小时前
机器学习算法:随机梯度下降算法
人工智能·深度学习·算法·机器学习
Yuner200012 小时前
Python机器学习:从零基础到深度实战
人工智能·python·机器学习