k-Nearest Neighbours
To guess the price of a flat, an estate agent looks at the few most similar flats that sold recently. k-nearest neighbours (kNN) does exactly that: to predict for a new point, find the training points closest to it and let them vote (classification) or average their targets (regression). There is no training at all beyond storing the data, which makes kNN the simplest model to explain and a good check on whether "similar inputs have similar outputs" holds in your data. The Machine Learning course introduces it; this lesson covers the vectorised implementation, the choice of , scaling and why kNN struggles in high dimensions.
Definition
Given a distance (usually Euclidean), let be the training points nearest to . Then
With weights="distance", closer neighbours count more (weight ). Other distances: Manhattan , Minkowski , cosine for text and embeddings (Distances, Angles and Orthogonality, Norms).
See it
The lab trains kNN on 80 noisy points (the noise slider starts at its maximum). With every training point claims its own region and the boundary is jagged: 80 of 80 training points right, but only 91.5 % of 200 new test points. At the boundary smooths, training accuracy drops to 92.5 % and test accuracy rises to 94.5 %. Very large blurs real structure; lower the noise to see that small is fine when the data is clean.
From scratch, vectorised
The distance from every query to every training point comes from one identity, , so a matrix product computes the whole table:
import numpy as np
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor
X, y = load_wine(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
sc = StandardScaler().fit(X_tr)
X_tr, X_te = sc.transform(X_tr), sc.transform(X_te)
def pairwise_sq_dist(A, B):
# ||a - b||^2 = ||a||^2 - 2 a.b + ||b||^2, for all pairs at once
return (A ** 2).sum(1)[:, None] - 2 * A @ B.T + (B ** 2).sum(1)[None, :]
def knn_classify(X_tr, y_tr, X, k):
nearest = np.argsort(pairwise_sq_dist(X, X_tr), axis=1, kind="stable")[:, :k]
votes = np.apply_along_axis(np.bincount, 1, y_tr[nearest], minlength=y_tr.max() + 1)
return votes.argmax(axis=1)
def knn_regress(X_tr, y_tr, X, k):
nearest = np.argsort(pairwise_sq_dist(X, X_tr), axis=1, kind="stable")[:, :k]
return y_tr[nearest].mean(axis=1)
for k in [1, 5, 15]:
ours = knn_classify(X_tr, y_tr, X_te, k)
sk = KNeighborsClassifier(n_neighbors=k).fit(X_tr, y_tr).predict(X_te)
print(f"k={k:2d}: test accuracy {np.mean(ours == y_te):.3f}, same as sklearn: {bool(np.all(ours == sk))}")
# regression: predict alcohol (column 0) from the other 12 standardised features
r_ours = knn_regress(X_tr[:, 1:], X_tr[:, 0], X_te[:, 1:], 5)
r_sk = KNeighborsRegressor(n_neighbors=5).fit(X_tr[:, 1:], X_tr[:, 0]).predict(X_te[:, 1:])
print("kNN regression matches sklearn:", np.allclose(r_ours, r_sk))k= 1: test accuracy 1.000, same as sklearn: True
k= 5: test accuracy 0.963, same as sklearn: True
k=15: test accuracy 0.981, same as sklearn: True
kNN regression matches sklearn: True
The from-scratch version agrees with scikit-learn for every , for classification and regression. On 54 test wines the differences between values are one or two wines, too few to choose from; that is the job of cross-validation below. Prediction costs per query with brute force; scikit-learn can switch to KD-trees or ball trees (algorithm="auto"), which are much faster in low dimensions and lose their advantage beyond about 20.
Choosing k, and why scaling is not optional
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
# 1) choosing k by cross-validation, with and without scaling
X, y = load_breast_cancer(return_X_y=True)
cv = StratifiedKFold(5, shuffle=True, random_state=0)
print(" k raw scaled")
for k in [1, 3, 5, 11, 21, 51]:
raw = cross_val_score(KNeighborsClassifier(k), X, y, cv=cv).mean()
scaled = cross_val_score(make_pipeline(StandardScaler(), KNeighborsClassifier(k)), X, y, cv=cv).mean()
print(f"{k:3d} {raw:.3f} {scaled:.3f}")
# 2) the curse of dimensionality: distances concentrate
rng = np.random.default_rng(0)
print("dims nearest/farthest distance from a random point")
for d in [2, 10, 100, 1000]:
P = rng.uniform(size=(1000, d))
dist = np.sqrt(((P[1:] - P[0]) ** 2).sum(axis=1))
print(f"{d:4d} {dist.min() / dist.max():.3f}") k raw scaled
1 0.914 0.958
3 0.932 0.965
5 0.932 0.965
11 0.933 0.967
21 0.928 0.958
51 0.914 0.947
dims nearest/farthest distance from a random point
2 0.006
10 0.287
100 0.699
1000 0.900
Two lessons in one output. First, scaling: the breast-cancer features range from fractions to thousands (the area of a nucleus), so unscaled distances are mostly "difference in area". Standardising inside the pipeline lifts accuracy at every . Second, the U-shape in : has high variance, too much bias, and the best values lie around 3 to 11.
The last table shows the curse of dimensionality. For 1000 random points in the unit cube, the nearest point is 0.006 times as far as the farthest in 2 dimensions, but 0.900 times as far in 1000 dimensions: almost every point is about equally far away, so "nearest" carries little information. kNN works when the data really lives in few dimensions (as images and embeddings often do) or after dimensionality reduction (PCA).
Hyperparameters
| Hyperparameter | Effect |
|---|---|
n_neighbors () |
small: flexible, high variance; large: smooth, high bias. Odd avoids ties in binary problems |
weights |
"uniform" or "distance" (closer neighbours count more) |
metric, p |
Euclidean, Manhattan, Minkowski, cosine; must suit the features |
algorithm |
brute force, KD-tree, ball tree: speed only, not results |
Strengths, weaknesses, when to use it
| Strengths | Weaknesses |
|---|---|
| no training; new data is added instantly | slow predictions and memory for the whole training set |
| any boundary shape; naturally multiclass | needs scaling and a meaningful distance |
| one intuitive hyperparameter | degrades in high dimensions and with irrelevant features |
| explanations by example ("these 5 similar cases") | no model to inspect beyond the stored data |
Use kNN as a quick baseline on low-dimensional, well-scaled data, for recommendation and retrieval by similarity (with approximate nearest-neighbour indexes for large data), and for imputation (KNNImputer).
Pitfalls
- Forgetting to scale, or scaling on all the data. Put the scaler in a pipeline so it is fitted on training folds only.
- Irrelevant features. Every useless feature adds noise to every distance; select or reduce features first.
- Using kNN's training score. With the training accuracy is 100 % by construction (each point is its own neighbour).
Practice
- Two features: income in dollars (range 20 000 to 200 000) and age (20 to 70). Without scaling, which feature decides who the neighbours are?
Answer
Income: a difference of a few thousand dollars dwarfs any age difference, so neighbours are simply the people with the closest income and age is ignored. Standardising puts both on a comparable scale.
- Why does give 100 % training accuracy, and what does that say about the training score of kNN?
Answer
Each training point's nearest neighbour is itself (distance 0), so it predicts its own label. The training score therefore measures nothing about generalisation; only validation or cross-validation scores are meaningful for kNN.
Test yourself
What does kNN do during fit?
- Learns a weight per feature
- Stores the training data (and maybe builds a search index)
- Computes class centroids
- Fits a tree
Increasing in kNN classification tends to…
- increase variance
- increase bias and smooth the decision boundary
- make training slower
- require scaling
In 1000 dimensions, the nearest and farthest random points were at a distance ratio of 0.9. Why is that bad for kNN?
- Distances become negative
- All points are nearly equally far away, so the nearest neighbours are barely more similar than random points
- The computation overflows
- kNN needs odd dimensions