Sub topic 3
Predicting Numbers with k-NN Regression
Assume you know feature vectors, train/test splits, and Euclidean distance. In k-nearest-neighbours (k-NN) regression, a new value is predicted by averaging the target values of its nearest training points.
Regression and model selection
For a query point, k-NN regression:
- Computes its distance from every training point.
- Selects the \(k\) closest points.
- Averages their target values.
from sklearn.neighbors import KNeighborsRegressor
X = [[0], [1], [2], [3]]
y = [0, 0, 1, 1]
model = KNeighborsRegressor(n_neighbors=2, weights="distance")
model.fit(X, y)
print(model.predict([[1.5]]))The choice of \(k\) controls smoothness. Cross-validation tests candidate values on several validation folds. Tune n_neighbors and weights inside a pipeline when scaling features:
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsRegressor
pipe = make_pipeline(StandardScaler(), KNeighborsRegressor())
grid = GridSearchCV(
pipe,
{"kneighborsregressor__n_neighbors": [3, 5, 9],
"kneighborsregressor__weights": ["uniform", "distance"]},
cv=5,
)
grid.fit(X, y)The pipeline fits the scaler separately in each fold, preventing validation information from leaking into training.
Search quality and speed
In high-dimensional data, distances become less informative. Points tend to appear similarly far away, so “nearest” neighbours may not be meaningfully similar. This is the curse of dimensionality. Remove irrelevant features, reduce dimensions, or use a more suitable representation.
KD-trees split space along feature axes. Ball trees group points inside hyperspheres. Both can accelerate low- or medium-dimensional searches, but brute force can be faster for small or high-dimensional datasets.
| Method | Good fit |
|---|---|
| Brute force | Small or high-dimensional data |
| KD-tree or ball tree | Larger low-dimensional data |
| Approximate search | Very large datasets where small errors are acceptable |
Approximate nearest-neighbour systems search only promising regions. They trade a small loss in neighbour accuracy for lower latency and memory use at scale.
Practical pitfalls
- Equal-distance neighbours can create unstable boundary decisions. Use deterministic tie handling.
- Imbalanced targets or classes can make local averages misleading. Inspect neighbour composition and evaluation metrics.
- Encode categorical features carefully. Arbitrary numeric codes create false distances.
- k-NN stores the training data, so memory use grows with dataset size.
Exercise
Why can increasing k reduce variance but increase bias?
Show answer
A larger neighbourhood averages out local noise, reducing variance, but it can smooth away real local patterns, increasing bias.