当前位置:   article > 正文

KNN算法对鸢尾花进行分类:添加网格搜索和交叉验证

KNN算法对鸢尾花进行分类:添加网格搜索和交叉验证

优化——添加网格搜索和交叉验证

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_)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

运行结果

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/235630
推荐阅读
相关标签
  

闽ICP备14008679号