How Many Neighbours?

Machine Learning in CodeMedium+10 XP+10

How Many Neighbours?

How many neighbours should get a vote? You decide to try a few values and keep the one that does best on the test rows.

Task: write best_k(ks). ks is a list of whole numbers to try for n_neighbors.

  • Load the breast cancer data and split it with train_test_split(X, y, test_size=0.25, random_state=0). Split once and reuse it for every k.
  • For each k, train a KNeighborsClassifier(n_neighbors=k) on the training rows and score it on the test rows.
  • Return [best k, its test score rounded to 3 decimal places].
  • If several values of k tie for the best score, pick the smallest of them.

Examples

ks = [1, 3, 5]
returns [5, 0.937]
ks = [7, 9, 11, 13]
returns [9, 0.958]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run