Classify with distance-weighted k nearest neighbour votes

Why it matters Weighted KNN is a common baseline for recommendation, similar-item lookup and embedding classifiers, where near neighbours are much more reliable than far ones.

Closer neighbours should count more than far ones. Weighted KNN gives each of the k neighbours a vote of 1 / distance.

Write weighted_knn_predict(X_train, y_train, X_test, k). Use Euclidean distance; among equal distances the smaller training index comes first. For each test point take the k nearest training points. If any of them is at distance 0 (below 1e-12), only those zero-distance points vote, with weight 1 each. Otherwise each votes with weight 1 / distance. Predict the label with the largest total weight (smaller label on ties). Return a list of labels.

Signaturedef weighted_knn_predict(X_train, y_train, X_test, k)

Example

X_train [[0], [1], [5], [6], [7]], y_train [0, 0, 1, 1, 1], X_test [[2.5]], k 5 gives [0].

Understand the idea

Plain KNN lets each of the k nearest points cast one vote. That is unfair when some neighbours are right next to the query and others are far away. Weighted KNN gives each neighbour a vote of 1 / distance, so a neighbour twice as close counts twice as much.

Worked example: query 2.5, training points 0 and 1 (class 0) and 5, 6, 7 (class 1), k = 5. Class 0 weight = 1/2.5 + 1/1.5 = 0.4 + 0.667 = 1.067. Class 1 weight = 1/2.5 + 1/3.5 + 1/4.5 = 0.4 + 0.286 + 0.222 = 0.908. Class 0 wins, even though plain voting would pick class 1 three votes to two.

Rule: weight_i = 1 / d_i, prediction = label with the largest total weight. If a neighbour has d = 0, only exact matches vote.

This is the same weighting option used by common KNN classifiers, and it is popular on top of embedding search.

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

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

  • Sample 1: exampleweighted_knn_predict([[0], [1], [5], [6], [7]], [0, 0, 1, 1, 1], [[2.5]], 5)
  • Sample 2: exact matchweighted_knn_predict([[0, 0], [1, 1], [1, 1], [3, 3]], [2, 1, 1, 2], [[1, 1], [2.9, 3]], 3)
  • Test 3: 2dweighted_knn_predict([[0, 0], [0, 1], [4, 4], [5, 4], [4, 5]], [1, 1, 0, 0, 0], [[1, 1], [3, 3]], 4)
  • Test 4: tie goes to smaller labelweighted_knn_predict([[0], [2]], [3, 1], [[1]], 2)