1. 程式人生 > >knn演算法中關於k的取值

knn演算法中關於k的取值

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()

結果如下圖所示: