Sub topic 8
Predicting numbers with k-NN regression
This chapter assumes you know how k-NN classification works: distance to every training point, pick the k closest, vote. It also assumes you have used scikit-learn estimators (fit, predict) and know why features should be scaled before computing distances. Here the target is a number instead of a class.
From voting to averaging
A classifier needs a label, so the k neighbours vote. A regressor needs a number, so the k neighbours are averaged. The rest of the algorithm is unchanged. Nothing is fitted, fit only stores the data, and all the work happens at prediction time.
For a query point x with neighbour set N_k(x), the prediction is:
ŷ(x) = (1/k) · Σ yi, summed over i in Nk(x)
The diagram shows the steps.
The comparison with classification is short:
| Aspect | Classification | Regression |
|---|---|---|
| Target | Class label | Real number |
| Combine neighbours by | Majority vote | Mean (or weighted mean) |
| Ties | Possible, need a rule | Not an issue |
| Typical metric | Accuracy | MSE, MAE, R² |
| scikit-learn class | `KNeighborsClassifier` | `KNeighborsRegressor` |
Ties disappear because an average always exists. The other pitfalls, such as scaling and the curse of dimensionality, carry over unchanged.
A minimal example
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 query 1.5 is exactly 0.5 away from both 1 and 2. Their targets are 0 and 1, so the prediction is 0.5. No training point has the target 0.5, so the model can output values it never saw as a label. It cannot, as we will see, output values outside the range of the training targets.
Implementing it from scratch
This extends the classifier from earlier in the tutorial. Only the last step changes.
import numpy as np
def knn_regress(X_train, y_train, x, k=3, weighted=False):
# Euclidean distance from x to every training point
dists = np.linalg.norm(X_train - x, axis=1)
nearest = np.argsort(dists)[:k]
targets = y_train[nearest]
if not weighted:
return targets.mean()
d = dists[nearest]
# An exact match would give an infinite weight, so return its target
if np.any(d == 0):
return targets[d == 0].mean()
return np.average(targets, weights=1.0 / d)
X_train = np.array([[0.0], [1.0], [2.0], [3.0]])
y_train = np.array([0.0, 0.0, 1.0, 1.0])
print(knn_regress(X_train, y_train, np.array([1.5]), k=2)) # 0.5
print(round(knn_regress(X_train, y_train, np.array([1.2]), k=2, weighted=True), 3)) # 0.2The weighted call is worked by hand below.
Distance-weighted averaging
With uniform weights, a neighbour at distance 0.8 counts as much as one at distance 0.2. Weighting each neighbour by 1/distance gives closer points more influence.
For the query 1.2 with k=2, the neighbours are 1 (distance 0.2, target 0) and 2 (distance 0.8, target 1).
- Uniform average: (0 + 1) / 2 = 0.5
- Weights: 1/0.2 = 5 and 1/0.8 = 1.25
- Weighted average: (5·0 + 1.25·1) / 6.25 = 0.2
In scikit-learn, set weights="distance":
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, round(float(model.predict([[1.2]])[0]), 3))
# uniform 0.5
# distance 0.2If a query coincides with a training point, scikit-learn uses only the zero-distance points. With weights="distance" and k > 1, the prediction at a training point therefore equals its own target (or the mean of duplicates). This makes training error look perfect, so never judge the model by training error.
What the prediction function looks like
A k-NN regressor is a piecewise-constant function of x in one dimension. The prediction changes only when the set of k nearest neighbours changes. Three consequences follow.
- k = 1 passes through every training point. It reproduces the noise in the targets exactly, so it has low bias and high variance.
- k = n (all training points) predicts the global mean everywhere. It has high bias and zero variance.
- Intermediate k smooths the noise, but it also flattens real peaks and valleys. The curve is steppy rather than smooth, and weighting by distance reduces the steps only partly.
This is the same bias-variance trade-off as in classification, but it is easier to see. Larger k averages more noisy targets, which lowers variance, while the averaging window widens, which raises bias.
No extrapolation
Every prediction is an average of training targets, so it always lies between the smallest and largest training target. Far from the data, the nearest neighbours are the same few edge points, and the prediction becomes a constant.
The same effect, milder, occurs near the edges inside the range. A query near the boundary has neighbours on one side only, so the average is pulled toward the interior and underestimates peaks at the edge.
Choosing k and the weighting rule
As in classification, pick k by cross-validation, and put scaling in a pipeline so each fold fits its own scaler. The example below uses a noisy sine curve. The score is negative mean squared error, because scikit-learn maximizes scores.
import numpy as np
from sklearn.model_selection import KFold, cross_val_score
from sklearn.neighbors import KNeighborsRegressor
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
X = rng.uniform(0, 6, size=(200, 1))
y = np.sin(X).ravel() + rng.normal(0, 0.3, size=200)
cv = KFold(n_splits=5, shuffle=True, random_state=0)
for k in [1, 5, 15, 50, 150]:
pipe = make_pipeline(StandardScaler(), KNeighborsRegressor(n_neighbors=k))
scores = cross_val_score(pipe, X, y, cv=cv, scoring="neg_mean_squared_error")
print(f"k={k:3d} MSE={-scores.mean():.3f}")Expect a U-shaped curve. The error is high at k=1 because the model fits noise, falls for moderate k, and rises again at k=150 because the model approaches a global mean. The exact numbers depend on the random data, but the shape should hold. The noise has variance 0.09, so no model can achieve a MSE much below about 0.09.
Two details in this code matter.
- The largest k must be smaller than the number of training samples in a fold. With 200 points and 5 folds, each training fold has 160, so
n_neighbors=200would raise an error. KFoldis shuffled. Without shuffling, data sorted by x would put whole regions of x into a single test fold. The model would then be asked to extrapolate, and the scores would be pessimistic.
Evaluating a regressor
Pick a metric that matches how errors cost you.
- MSE or RMSE penalizes large errors heavily. RMSE has the same units as the target.
- MAE weighs all errors linearly and is less sensitive to outliers.
- R² compares the model with always predicting the mean.
KNeighborsRegressor.scorereturns R². A value near 0 means the model is no better than the mean, and negative values mean it is worse.
Compare against a baseline such as DummyRegressor, which predicts the training mean. If k-NN barely beats it, the features probably do not carry the signal, or the scaling or dimensionality is hurting distance quality.
Practical considerations
- Outliers in the target. The mean follows a single extreme neighbour. For heavy-tailed targets you can take the median of the neighbours' targets instead. scikit-learn does not offer this directly, but you can use
kneighborsto get the indices and compute the median yourself. - Scaling. A feature measured in thousands will dominate one measured in fractions. Scale inside the pipeline, as shown above.
- Irrelevant features. Every feature contributes to the distance equally, so noise features blur the neighbourhood. This is the curse of dimensionality seen in regression: neighbours stop being similar in the way that matters for the target.
- Multiple targets.
ymay be a 2-D array with one column per target. The regressor then averages each column over the same neighbours. - Radius-based variant.
RadiusNeighborsRegressoraverages all points within a fixed radius instead of a fixed count. It adapts to density, but a query with no points in the radius needs a fallback, so you must handle that case. - Cost. Prediction scans or searches the stored data. Memory grows with the training set. The search structures in a later chapter apply here as well.
Exercises
Exercise
A model is trained with X = [[0], [1], [2], [3], [4]] and y = [0, 2, 4, 6, 8] using KNeighborsRegressor(n_neighbors=2). What does it predict for the query 10, and why is that different from the true line y = 2x?
Show answer
The two nearest points to 10 are 4 and 3, with targets 8 and 6. The prediction is (8 + 6) / 2 = 7. The line would give 20. A k-NN regressor only averages stored targets, so it cannot predict above the largest training target (8) and cannot extrapolate.
Exercise
A query has three neighbours at distances 1, 2 and 4 with targets 10, 20 and 40. Compute the prediction with uniform weights and with weights 1/distance.
Show answer
Uniform: (10 + 20 + 40) / 3 = 23.33. Weighted: the weights are 1, 0.5 and 0.25, which sum to 1.75. The numerator is 10·1 + 20·0.5 + 40·0.25 = 30, so the prediction is 30 / 1.75 ≈ 17.14. The weighted result is closer to the nearest target, 10.
Exercise
You tune k on sorted data with cross_val_score(..., cv=5) without shuffling, and the cross-validated error is much worse than the error on a random held-out set. What is the likely cause, and how do you fix it?
Show answer
Without shuffling, each test fold covers a contiguous region of x that is missing from the training folds, so the model must extrapolate, which k-NN does badly. Use KFold(n_splits=5, shuffle=True, random_state=0) as the cv argument, unless the real task is to predict outside the observed range, in which case a time- or range-based split is correct and the poor score is genuine.