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_)
相关推荐
一只鱼丸yo9 小时前
70B大模型也能在笔记本上跑?揭秘让AI“瘦身”的黑科技
人工智能·科技·机器学习·语言模型
hallo12812 小时前
学习机器学习能看哪些书籍
人工智能·深度学习·机器学习
中國龍在廣州12 小时前
哈工大提出空间机器人复合框架,突破高精度轨迹跟踪
人工智能·深度学习·机器学习·计算机视觉·机器人
石氏是时试12 小时前
拉格朗日多项式
人工智能·算法·机器学习
非门由也13 小时前
《sklearn机器学习——聚类性能指数》同质性,完整性和 V-measure
机器学习·聚类·sklearn
骑驴看星星a13 小时前
三维聚类建模
机器学习·数据挖掘·聚类
非门由也13 小时前
《sklearn机器学习——聚类性能指标》调整兰德指数、基于互信息(mutual information)的得分
机器学习·聚类·sklearn
悠哉悠哉愿意13 小时前
【数学建模学习笔记】机器学习分类:XGBoost分类
学习·机器学习·数学建模
悠哉悠哉愿意1 天前
【机器学习学习笔记】线性回归实现与应用
笔记·学习·机器学习
THMAIL1 天前
机器学习从入门到精通 - 机器学习调参终极手册:网格搜索、贝叶斯优化实战
人工智能·python·算法·机器学习·支持向量机·数据挖掘·逻辑回归