Sub topic 7
Giving Closer Neighbours More Weight
Plain k-NN gives every one of the k neighbours exactly one vote. A neighbour at distance 0.1 counts the same as one at distance 5.0. This chapter replaces that rule with distance-weighted voting, so closer neighbours count for more. It covers the formulas, the scikit-learn options, and the edge cases that cause trouble.
It assumes you know how k-NN classifies by majority vote, how to compute Euclidean distance, and how to fit a scikit-learn estimator. It also assumes you know why features need scaling before distances are computed.
Why uniform voting can mislead
Uniform voting has two weaknesses.
- Far neighbours get too much say. With k = 5, a point may have one very close neighbour of class A and four distant neighbours of class B. Uniform voting returns B, even though the nearest evidence points to A.
- The result jumps with k. A neighbour at rank k contributes fully, and one at rank k+1 contributes nothing. A small change in k can flip a prediction because of a point that sits only slightly outside the cutoff.
Weighting softens both effects. Each neighbour i at distance dᵢ gets a weight wᵢ that shrinks as dᵢ grows. The prediction is then the class with the largest total weight.
The voting rule
For classification, the score of class c is the sum of the weights of the neighbours that have label c:
score(c) = Σ wᵢ, summed over the neighbours i with label c
The prediction is the class with the highest score. With wᵢ = 1 for all neighbours, this is ordinary majority voting. Common weight functions are:
| Scheme | Weight | Behaviour |
|---|---|---|
| Uniform | 1 | Every neighbour counts the same. This is the scikit-learn default. |
| Inverse distance | 1 / d | Weight falls off steadily. Very close points dominate. |
| Inverse squared distance | 1 / d² | Falls off faster, so the nearest one or two points decide most votes. |
| Gaussian kernel | exp(−d² / (2σ²)) | Smooth falloff controlled by a bandwidth σ. Points far beyond σ count for almost nothing. |
Choosing a scheme sets how local the prediction is. Steeper weights make the model depend on the very nearest points.
A from-scratch weighted vote
This function extends the classifier from the earlier chapter. The tiny eps term avoids division by zero when the query sits exactly on a training point.
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:
scores[y_train[i]] += 1.0 / (dists[i] + eps)
return max(scores, key=scores.get)
X_train = np.array([[0.0, 0.0], [2.0, 0.0], [2.1, 0.0], [5.0, 5.0]])
y_train = np.array([0, 1, 1, 1])
query = np.array([0.2, 0.0])
# Unweighted vote among the 3 nearest: labels 0, 1, 1 -> class 1
nearest = np.argsort(np.linalg.norm(X_train - query, axis=1))[:3]
print(np.bincount(y_train[nearest]).argmax()) # 1
# Weighted vote: class 0 scores 1/0.2 = 5.0, class 1 scores about 1.08
print(knn_predict_weighted(X_train, y_train, query, k=3)) # 0The three nearest neighbours are the same in both calls. Two of them are class 1, so the plain vote returns 1. The single class 0 point is 1.8 units closer than the other two, and its weight of 5.0 outweighs their combined 1.08. The weighted vote returns 0.
Weighting in scikit-learn
KNeighborsClassifier and KNeighborsRegressor take a weights argument with three kinds of value:
"uniform"gives equal weights."distance"gives weights of 1 / d.- A callable receives an array of distances and must return an array of weights with the same shape.
The following example compares all three inside a pipeline, using cross-validation across several values of k. The scaler sits in the pipeline so it is fitted on each training fold only.
import numpy as np
from sklearn.datasets import load_wine
from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_wine(return_X_y=True)
def gaussian(d, sigma=1.5):
return np.exp(-(d ** 2) / (2 * sigma ** 2))
schemes = {"uniform": "uniform", "distance": "distance", "gaussian": gaussian}
for name, weights in schemes.items():
for k in (1, 5, 15, 31):
model = make_pipeline(
StandardScaler(),
KNeighborsClassifier(n_neighbors=k, weights=weights),
)
scores = cross_val_score(model, X, y, cv=5)
print(f"{name:9s} k={k:2d} mean accuracy={scores.mean():.3f}")Run it and compare the rows. On most datasets, the gap between schemes is small at small k and tends to grow as k gets larger. The exact numbers depend on the data and the folds, so check your own output rather than trusting a general rule.
Zero distances
When the query coincides with one or more training points, 1 / d is infinite. scikit-learn handles this explicitly. If any neighbour is at distance 0, those exact matches get weight 1 and every other neighbour gets weight 0. This is sensible, but note the consequence: a duplicate row of the query in the training data decides the prediction alone.
This often shows up when you evaluate on the training set. Each point is its own nearest neighbour at distance 0, so training accuracy with weights="distance" is close to perfect, and it says nothing about generalisation.
Custom weight functions
A callable must be vectorised. It receives a 2D array of shape (n_queries, k) and returns an array of the same shape. Operations such as np.exp(-d**2) satisfy this automatically.
Pay attention to the scale of the distances. In a standardised feature space with many features, typical neighbour distances are often several units. If σ is much smaller than those distances, every weight underflows towards 0. Then votes tie at 0 and the result is arbitrary. Choose σ relative to the distances you actually see, for example a value near the median distance to the k-th neighbour. You can inspect these distances with kneighbors.
Weighted regression
Regression uses the same idea with a weighted average. The prediction is
ŷ = Σ wᵢ yᵢ / Σ wᵢ
Dividing by the sum of the weights keeps the result inside the range of the neighbours' targets.
from sklearn.neighbors import KNeighborsRegressor
X = [[0], [1], [2]]
y = [0, 10, 20]
uniform = KNeighborsRegressor(n_neighbors=2, weights="uniform").fit(X, y)
weighted = KNeighborsRegressor(n_neighbors=2, weights="distance").fit(X, y)
print(uniform.predict([[0.8]]), weighted.predict([[0.8]])) # [5.] [8.]The two neighbours of 0.8 are at distances 0.2 (target 10) and 0.8 (target 0). The uniform average is 5. The weights are 5 and 1.25, so the weighted average is (5 × 10 + 1.25 × 0) / 6.25 = 8. The weighted prediction follows the closer point, which gives smoother and more local estimates.
What weighting does and does not fix
Weighting changes the bias and variance balance a little, but it does not replace tuning.
- Sensitivity to k drops. Distant neighbours contribute little, so a large k behaves more like a smaller one. Curves of accuracy against k are often flatter, which makes the choice of k less fragile.
- Noise can hurt. If the nearest point has a wrong label, a steep weight such as 1 / d² lets that one point override several correct neighbours. Mislabelled data therefore favours gentler weights or uniform voting.
- Scaling still matters. Weights are computed from distances. If one feature dominates the distance, it dominates the weights too.
- Class imbalance is not solved. Weights depend on distance, not on class frequency. A rare class still loses a vote when its points are farther from the query than the points of a common class.
- Ties become rare, not impossible. Exact distance ties between classes are unlikely with continuous features, but they can occur with integer or duplicated data.
- Cost is almost unchanged. Finding the neighbours is the expensive step. Computing weights over k values is negligible.
Choosing a scheme in practice
- Start with
"uniform"and a cross-validated k. This is your baseline. - Try
"distance". If accuracy improves or stays equal with a flatter curve over k, keep it. - Try a Gaussian or steeper kernel only if you have a reason to want a strongly local model, and check σ against real neighbour distances.
- Check for duplicate rows between training and evaluation data. They distort weighted results.
- If labels are noisy, prefer the gentler schemes.
Exercise
A query has three neighbours. Two are class A at distances 1.0 and 2.0, and one is class B at distance 0.25. Compute the class scores using 1 / d weights and name the predicted class. What does a uniform vote predict?
Show answer
Class A scores 1/1.0 + 1/2.0 = 1.5. Class B scores 1/0.25 = 4.0. The weighted prediction is class B. A uniform vote counts two A votes against one B vote, so it predicts class A.
Exercise
You train KNeighborsClassifier(weights="distance") and score it on the same data it was trained on. The accuracy is 100%. Why, and how should you evaluate the model instead?
Show answer
Each training point is its own nearest neighbour at distance 0. scikit-learn gives zero-distance neighbours weight 1 and all others weight 0, so each point predicts its own label. Evaluate on a held-out test set or with cross-validation, scaling inside a pipeline.
Exercise
Why is it risky to use a Gaussian weight function with sigma = 0.1 on standardised data with 30 features?
Show answer
In 30 standardised dimensions, neighbour distances are usually several units. With sigma = 0.1, exp(-d²/(2σ²)) is near 0 for every neighbour. The weights underflow, the class scores tie at about 0, and the prediction becomes arbitrary. Choose sigma relative to the observed neighbour distances.