Classify points by majority vote of their nearest neighbours

k-nearest neighbours has no training step. To label a new point, find the k closest training points and take the most common label.

Write knn_predict(X_train, y_train, X_test, k). Use Euclidean distance. For ties in distance, the lower training index wins (use a stable sort). For ties in the vote, the smallest label wins. Return a list of ints.

Signaturedef knn_predict(X_train, y_train, X_test, k)

Understand the idea

k-nearest neighbours has no training. To label a new point you find the k closest training points and take a vote, like asking your nearest neighbours which shop is best. Two tie rules make it testable: when distances tie, the lower training index comes first (a stable sort does this), and when votes tie, the smallest label wins. Worked example: X_train = [[0], [1], [5]], y_train = [0, 0, 1], test point [4]. Distances are 4, 3 and 1. With k = 1 the closest is index 2, label 1. With k = 3 the votes are 0, 0, 1, so label 0. With k = 2 the closest are index 2 (label 1) and index 1 (label 0), a 1 to 1 tie, so the smaller label 0 wins. Rule: sort by Euclidean distance ascending, keep k, majority label with smallest-label tie-break. Sorting by negative distance picks the farthest points, a classic bug. kNN is used in recommendations and as a baseline.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: two clustersknn_predict(_Xt, _yt, [[0.2, 0.3], [5.5, 5.2]], 3)
  • Sample 2: k = 1knn_predict(_Xt, _yt, [[4, 4]], 1)
  • Test 3: vote tie goes to smaller labelknn_predict([[0], [2]], [1, 0], [[1]], 2)