赞
踩
- from sklearn import datasets
- from sklearn.neighbors import KNeighborsClassifier
- from sklearn.model_selection import GridSearchCV
-
- # 导入鸢尾花数据集
- iris = datasets.load_iris()
- X = iris.data
- y = iris.target
-
- # 设置需要搜索的K值
- parameters = {'n_neighbors': [1, 3, 5, 7, 9, 11, 13, 15]}
-
- # 创建KNN分类器
- knn = KNeighborsClassifier()
-
- # 使用GridSearchCV来找到最佳的K值
- clf = GridSearchCV(knn, parameters, cv=5)
- clf.fit(X, y)
-
- # 输出最佳参数及相应的准确度
- print("最佳准确度:%.2f" % clf.best_score_, "最佳K值:", clf.best_params_)
-
- import matplotlib.pyplot as plt
-
- # 提取每个K值对应的准确度和K值
- k_values = [param['n_neighbors'] for param in clf.cv_results_['params']]
- accuracies = clf.cv_results_['mean_test_score']
-
- # 绘制折线图
- plt.plot(k_values, accuracies, marker='o')
- plt.title('Grid Search Results')
- plt.xlabel('K Value')
- plt.ylabel('Accuracy')
- plt.show()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。