Exemplo de Classificador KNN

from sklearn.neighbors import KNeighborsClassifier
from sklearn import metrics
#Try running from k=1 through 20 and record testing accuracy
k_range = range(1,21)
scores = {}
scores_list = []
for k in k_range:
    knn = KNeighborsClassifier(n_neighbors=k)
    knn.fit(X_train,y_train)
    y_pred=knn.predict(x_test)
    scores[k] = metrics.accuracy_score(y_test,y_pred)
    scores_list.append(metrics.accuracy_score(y_test,y_pred))

#after running the code above, assign to n_neighbors the best performing value
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X,y)
y_pred= knn.predict(x_test)
Luis Magalhaes