Sub topic 7
Giving closer neighbours more weight
This chapter assumes you know how plain k-NN classifies by majority vote, what Euclidean distance is, and how to use scikit-learn estimators with fit and predict.
The problem with one vote per neighbour
In plain k-NN, every one of the k neighbours gets exactly one vote. A neighbour at distance 0.1 counts the same as one at distance 2.0. This can give odd results when k is large relative to the local cluster. A query sitting almost on top of one training point can be outvoted by several distant points that only made the top k because nothing closer was left.
Distance-weighted voting fixes this. Each neighbour votes with a weight that shrinks as its distance grows. The most common choice is inverse distance:
- weight = 1 / distance
- Each class's score is the sum of the weights of its neighbours.
- The class with the highest total score wins.
A worked example
Take four one-dimensional training points and a query at 0.0. Use k = 3.
| Point | Label | Distance to query | Weight (1/d) |
|---|---|---|---|
| 0.1 | 1 | 0.1 | 10.0 |
| 2.0 | 0 | 2.0 | 0.5 |
| 2.1 | 0 | 2.1 | about 0.48 |
| 9.0 | 1 | 9.0 | not used (outside the k = 3) |
With uniform voting, label 0 wins two votes to one. With distance weighting, label 1 scores 10.0 and label 0 scores about 0.98, so label 1 wins. The very close neighbour dominates.
From scratch
import numpy as np
from collections import defaultdict
def knn_predict_weighted(X_train, y_train, x, k=3, eps=1e-12):
dists = np.linalg.norm(X_train - x, axis=1)
nearest = np.argsort(dists)[:k]
scores = defaultdict(float)
for i in nearest:
# eps avoids division by zero when x equals a training point
scores[y_train[i]] += 1.0 / (dists[i] + eps)
return max(scores, key=scores.get)
X_train = np.array([[0.1], [2.0], [2.1], [9.0]])
y_train = np.array([1, 0, 0, 1])
print(knn_predict_weighted(X_train, y_train, np.array([0.0]))) # 1In scikit-learn
The weights parameter of KNeighborsClassifier selects the rule. "uniform" is the default. "distance" uses inverse distance.
from sklearn.neighbors import KNeighborsClassifier
X = [[0.1], [2.0], [2.1], [9.0]]
y = [1, 0, 0, 1]
for w in ["uniform", "distance"]:
model = KNeighborsClassifier(n_neighbors=3, weights=w).fit(X, y)
print(w, model.predict([[0.0]]))
# uniform [0]
# distance [1]KNeighborsRegressor accepts the same parameter. There the prediction becomes a weighted average of neighbour targets instead of a plain mean.
Common errors
- Assuming weighting always helps. With a small k or evenly spaced neighbours, the two rules often agree. Weighting matters most when k is large or when neighbour distances differ a lot.
- Weighting noisy duplicates too heavily. A mislabelled point very close to the query can dominate the vote. Inverse distance lowers the effective bias but raises variance, much like a smaller k.
- Forgetting to scale features. Weights depend directly on distances, so unscaled features distort the weights as well as the neighbour choice.
- Treating
weightsas fixed. It is a hyperparameter. Tune it together with k using cross-validation, as covered in a later chapter.
You can also pass a callable to weights. It receives an array of distances and returns an array of weights of the same shape, so you can try a Gaussian kernel such as lambda d: np.exp(-d**2).
Exercise
In the worked example, you change the query from 0.0 to 5.0 with the same training data and k = 3. Which three points are the neighbours, and does distance weighting change the answer compared with uniform voting?
Show answer
The distances are 4.9 (label 1), 3.0 (label 0), 2.9 (label 0) and 4.0 (label 1 at 9.0). The three nearest are 2.1 (distance 2.9, label 0), 2.0 (distance 3.0, label 0) and 9.0 (distance 4.0, label 1). Uniform voting gives label 0 two votes to one. Weighted scores are label 0: 1/2.9 + 1/3.0 ≈ 0.345 + 0.333 = 0.678, and label 1: 1/4.0 = 0.25. Label 0 wins under both rules, so weighting does not change the answer.