Sub topic 8
Predicting numbers with k-NN regression
This chapter assumes you know how k-NN classification works, how Euclidean distance is computed, and why features are scaled before distances are compared. Here the target is a number instead of a class label.
From voting to averaging
In classification, the k nearest neighbours vote on a label. In regression, they contribute their target values, and the prediction is the mean of those values. Nothing else changes. Distance metrics, the choice of k, scaling, and neighbour search all work as before. As in classification, there is still no fitting step. fit only stores the training data.
| Aspect | Classification | Regression |
|---|---|---|
| Target | Class label | Real number |
| Combine neighbours by | Majority vote | Mean (optionally weighted) |
| Typical score | Accuracy | R², mean squared error |
A worked example
The training data has four points on one axis. The targets are 0, 0, 1, 1. The query is 1.5, which is exactly halfway between the points at 1 and 2.
from sklearn.neighbors import KNeighborsRegressor
X = [[0], [1], [2], [3]]
y = [0, 0, 1, 1]
model = KNeighborsRegressor(n_neighbors=2).fit(X, y)
print(model.predict([[1.5]])) # [0.5]The two nearest points are 1 and 2, both at distance 0.5. Their targets are 0 and 1, so the prediction is (0 + 1) / 2 = 0.5.
Weighting by distance
With weights="distance", each neighbour's target is multiplied by 1/distance. The weighted sum is then divided by the sum of the weights. A closer neighbour pulls the prediction harder. Take a query at 1.2 with the same data:
from sklearn.neighbors import KNeighborsRegressor
X = [[0], [1], [2], [3]]
y = [0, 0, 1, 1]
for w in ["uniform", "distance"]:
model = KNeighborsRegressor(n_neighbors=2, weights=w).fit(X, y)
print(w, model.predict([[1.2]]).round(2))
# uniform [0.5]
# distance [0.2]The neighbours are at distances 0.2 (target 0) and 0.8 (target 1). Their weights are 5 and 1.25. The prediction is (5·0 + 1.25·1) / 6.25 = 0.2. This is much closer to the nearer neighbour's target than the plain mean of 0.5.
How k affects the fit
The same bias-variance trade-off applies, but its effect is easiest to see in the shape of the prediction curve.
- k = 1 reproduces every training target exactly. The curve is jagged and follows noise (low bias, high variance).
- Large k averages over wide regions. The curve is smooth but flattens real peaks and valleys (high bias, low variance).
- k equal to the training set size predicts the global mean for every query.
Because each prediction is an average of stored targets, the prediction curve is piecewise constant. It changes in steps as the set of nearest neighbours changes. Distance weighting makes these steps smoother.
Common errors
- Extrapolating. A prediction can never be larger than the largest stored target or smaller than the smallest. Beyond the edge of the training data, the curve goes flat. If the true relationship is a trend that continues, k-NN will underpredict. A linear model suits that case better.
- Skipping scaling. A feature measured in thousands dominates the distance, so the other features are effectively ignored. Put a
StandardScalerin a pipeline so that it is fitted inside each cross-validation fold. - Scoring with accuracy. Regression estimators report R² from
score. A value near 0 means the model does no better than predicting the mean of the targets. - Outliers in the targets. A mean is sensitive to extreme values. If a neighbour has a wildly large target, it pulls the whole prediction. A smaller k limits the damage, and you can also clean the targets first.
- Tuning k on the test set. Choose k and the weighting rule with cross-validation on the training data, as in the classification chapter, and use the test set once at the end.
Exercise
A k-NN regressor with k=3 is trained on points whose targets range from 10 to 50. A query lies far outside the training region, and its three nearest neighbours have targets 40, 45 and 50. What is the prediction with uniform weights, and what does this show about extrapolation?
Show answer
The prediction is (40 + 45 + 50) / 3 = 45. It stays within the range of stored targets (10 to 50), so k-NN can never predict above 50 or below 10. Even if the true trend keeps rising past the training data, the prediction cannot follow it.