Search code examples
pythonknn

Print k value which corresponds to the most accurate score, instead of printing the scores


As you can see it's currently printing the scores. How would I simply print the k value which corresponds to the highest score?

k_range = range(1, 26)

scores = []

for k in k_range:
    knn = KNeighborsClassifier(n_neighbors=k)
    knn.fit(X_train, y_train)
    y_pred = knn.predict(X_test)
    scores.append(metrics.accuracy_score(y_test, y_pred))

print(scores)

Solution

  • print( k_range[ scores.index( max(scores) ) ] )