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.
def 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.