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_)
相关推荐
司小豆11 小时前
机器学习基本概念与建模流程
机器学习
phoenix@Capricornus13 小时前
杉山将(Sugiyama Masa)《图解机器学习》
机器学习
强盛小灵通专卖员14 小时前
目标检测中F1-Score指标的详细解析:深度理解,避免误区
人工智能·目标检测·机器学习·视觉检测·rt-detr
Humbunklung17 小时前
全连接层和卷积层
人工智能·python·深度学习·神经网络·机器学习·cnn
神经星星17 小时前
基于8.6万蛋白质结构数据,融合量子力学计算的机器学习方法挖掘69个全新氮-氧-硫键
人工智能·深度学习·机器学习
亚图跨际17 小时前
深入偏微分方程的世界-AI云计算
人工智能·机器学习·云计算
柠石榴19 小时前
《机器学习》(周志华)第一章 绪论
人工智能·机器学习
Dfreedom.19 小时前
过拟合和欠拟合
人工智能·机器学习
武乐乐~19 小时前
强化学习入门:交叉熵方法实现CartPole智能体
人工智能·深度学习·机器学习
音沐mu.20 小时前
【20】番茄叶片病害数据集(有v5/v8模型)/YOLO番茄叶片病害检测
人工智能·yolo·目标检测·机器学习·计算机视觉·番茄叶片病害检测·番茄叶片病害数据集