from __future__ import print_function from sklearn.datasets import load_iris from sklearn.cross_validation import cross_val_score import matplotlib.pyplot as plt from sklearn.neighbors import KNeighborsClassifier iris = load_iris() X = iris.data y = iris.target k_range = range(1, 31) k_scores = [] for k in k_range: knn = KNeighborsClassifier(n_neighbors=k) ## loss = -cross_val_score(knn, X, y, cv=10, scoring='mean_squared_error') # for regression scores = cross_val_score(knn, X, y, cv=10, scoring='accuracy') # for classification k_scores.append(scores.mean()) plt.plot(k_range, k_scores) plt.xlabel('Value of K for KNN') plt.ylabel('Cross-Validated Accuracy')plt.show()
结果如下图所示:
knn算法中关于k的取值
最新推荐文章于 2023-03-05 22:25:47 发布