text_plain_output_1.png
from sklearn import metrics

from sklearn.neighbors import KNeighborsClassifier

import matplotlib.pyplot as plt

val_results = []
train_results = []

k_range = range(1, 21)

for k in k_range:
    clf_2 = KNeighborsClassifier(n_neighbors=k)
    clf_2 = clf_2.fit(X_train, y_train)
    pred_train = clf_2.predict(X_train)
    train_score = metrics.accuracy_score(y_train, pred_train)
    train_results.append(train_score)
    pred_val = clf_2.predict(X_val)
    val_score = metrics.accuracy_score(y_val, pred_val)
    val_results.append(val_score)

plt.plot(k_range, val_results, 'b-', label='Val score')
plt.plot(k_range, train_results, 'r-', label='Train score')
plt.ylabel('Score')
plt.xlabel('Model complexity: k')
plt.legend()
plt.grid(True)
plt.show()