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科技星1 小时前
光速螺旋量子几何统一场论——基于 v ≡ c 公理的四大基本力全维度求导证明与精准数值验证
c语言·开发语言·人工智能·算法·机器学习·平面
陪你步步前行1 小时前
关于dice, miou, loss计算的细节
人工智能·深度学习·机器学习
rgb2gray2 小时前
论文详解:基于POI数据的城市功能区动态演化分析——以北京为例
人工智能·算法·机器学习·回归·gwr
Yao.Li2 小时前
LINEMOD 训练流程与实施细节
人工智能·深度学习·机器学习
HyperAI超神经2 小时前
数据集汇总丨英伟达/OpenAI及多所科研机构开源推理数据集,覆盖数学/全景空间/Wiki问答/科研任务/视觉常识等
人工智能·深度学习·机器学习·数据集·ai编程·llama·图像合成
高洁013 小时前
基于知识图谱的故障推理方法与算法
人工智能·机器学习·数据挖掘·transformer·知识图谱
Oflycomm4 小时前
高通携手Wayve:推动端到端AI自动驾驶迈向量产时代
人工智能·机器学习·自动驾驶·高通·wifi模块·qogrisys
科学创新前沿4 小时前
从原子结构到宏观性能:机器学习驱动的固态电解质设计与高通量筛选
人工智能·python·深度学习·机器学习·固态电池·固态电解质
人工智能培训4 小时前
基于知识图谱的故障推理方法与算法
人工智能·python·深度学习·机器学习·知识图谱·故障诊断