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_)
相关推荐
触底反弹8 小时前
🔥 从点积到 Transformer:我终于搞懂大模型是怎么"猜"出下一个词的了
人工智能·机器学习·架构
极光代码工作室11 小时前
基于YOLO目标检测的智能监控系统
python·深度学习·yolo·机器学习·计算机视觉
星马梦缘13 小时前
机器学习与模式识别 第十六章 Transformers 模拟卷及答案
人工智能·机器学习·cnn·transformer·attention·注意力机制·mlp
xx_xxxxx_14 小时前
AI的工程基础1-最优化算法
人工智能·机器学习
星马梦缘14 小时前
机器学习与模式识别 第十三章 从线性模型到神经网络 考点压缩
人工智能·pytorch·神经网络·机器学习·激活函数·relu
AI科技星14 小时前
乖乖数学全域数学加速正电荷会产生反向引力
人工智能·机器学习·概率论·量子计算·乖乖数学·全域数学·引力
大囚长14 小时前
信息约简对智能系统预测的重要性
人工智能·深度学习·机器学习
m0_6265352015 小时前
MRR(Mean Reciprocal Rank)和 NDCG(Normalized Discounted Cumulative Gain)
人工智能·机器学习
FL162386312915 小时前
养猪场耳标检测数据集VOC+YOLO格式744张1类别有增强
深度学习·yolo·机器学习
AI科技星15 小时前
拓扑生命系统确定性理论:基于32维流形的遗传密码起源与衰老动力学( 中英双语顶刊终稿·标准数学符号)
开发语言·网络·人工智能·算法·机器学习·乖乖数学·全域数学