Skip to content
BIASED

Nearest neighbours

The k-nearest-neighbour rule for classification and regression, k as a knob between bias and variance, weighted votes and kernel smoothing, distances and scaling, the curse of dimensionality in numbers, the Cover–Hart bound and fast neighbour search.

From memorizing to neighbours

The topic Validation and overfitting built a protocol that measures any model honestly: hold-out and KK-fold cross-validation, a test set touched once, nested cross-validation when a model is chosen among many. So far it had little to measure. The only models were thought experiments, such as the memorizer from What machine learning is: it returns yiy_i for a training object xix_i and a default answer for everything else.

The smallest change that makes the memorizer useful is to answer a new question with the answers to the most similar questions seen before. That is the nearest-neighbour method (Fix and Hodges, 1951), the first real model of the course.

It needs a distance ρ(x,x′)≥0\rho(x, x') \ge 0 between objects. For a query xx, let Nk(x)N_k(x) be the indices of the kk training objects nearest to xx; in this topic kk always counts neighbours. For classification, predict the most frequent class among them:

a(x)=arg⁡max⁡c∑i∈Nk(x)[yi=c].a(x) = \arg\max_{c} \sum_{i \in N_k(x)} [y_i = c] .

For regression, predict the mean of their targets:

a(x)=1k∑i∈Nk(x)yi.a(x) = \frac1k \sum_{i \in N_k(x)} y_i .

The topic Conditional expectation showed that the best predictor under squared loss is E[Y∣X=x]\mathbb E[Y \mid X = x]. The regression rule estimates it locally: it averages YY over the training points whose XX lies close to xx. In the same way, the vote shares estimate the class probabilities P(Y=c∣X=x)P(Y = c \mid X = x). "Training" is just storing the sample; all the work happens at prediction time.

A worked example. The query is x=(0,0)x = (0, 0). Two training points have class ++: A=(1,0)A = (1, 0) and C=(−2,0)C = (-2, 0). Three have class −-: B=(0,2)B = (0, 2), D=(2,2)D = (2, 2) and E=(0,−3)E = (0, -3). The Euclidean distances from the query to A,B,C,D,EA, B, C, D, E are 11, 22, 22, 2.832.83 and 33.

  • k=1k = 1: the only neighbour is AA, so the answer is ++.
  • k=3k = 3: AA, BB and CC vote two to one for ++.
  • k=5k = 5: all five points vote three to two for −-.

The answer depends on kk, and so does its quality.

Choosing k: bias against variance

Small kk follows the data closely. Large kk averages over a wide neighbourhood. Both extremes fail, for opposite reasons.

Take regression with noise of variance σ2\sigma^2 around the true E[Y∣X]\mathbb E[Y \mid X]. The mean of kk independent noisy targets has variance σ2/k\sigma^2/k, the sample-mean result from Estimators: bias and variance. So a larger kk lowers the variance of the prediction. But the kk-th neighbour lies farther from xx, where E[Y∣X]\mathbb E[Y \mid X] differs from its value at xx. So a larger kk raises the bias. The number of neighbours is a knob between the two; the topic Bias–variance decomposition will make the trade-off exact.

The extremes are easy to see. At k=1k = 1 every training point is its own nearest neighbour, so the training error is zero: the memorizer again, now with a sensible answer for new points. At k=nk = n every query gets the overall majority class.

Here is the trade-off on simulated data where the best rule is known: two classes in the plane, 200 training points, Bayes error 0.1350.135. The risk of each rule is computed exactly from the known distribution.

kk training error risk
1 0.000 0.188
15 0.115 0.141
101 0.175 0.204

At k=1k = 1 the boundary circles single points of the wrong class: overfitting. At k=101k = 101 the vote averages over half the sample and the boundary is too smooth: underfitting. At k=15k = 15 the risk comes close to the Bayes error.

In practice the risk is unknown, so kk is chosen by cross-validation. The best score of a grid is optimistic, as Validation and overfitting showed, and the honest report comes from nested cross-validation. Here it is on the breast-cancer data bundled with scikit-learn, 30 numeric features and two classes:

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import GridSearchCV, StratifiedKFold, cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
 
X, y = load_breast_cancer(return_X_y=True)
model = make_pipeline(StandardScaler(), KNeighborsClassifier())
grid = {"kneighborsclassifier__n_neighbors": list(range(1, 50, 4))}
search = GridSearchCV(model, grid, cv=StratifiedKFold(5, shuffle=True, random_state=0))
search.fit(X, y)
print(search.best_params_, round(search.best_score_, 3))
outer = StratifiedKFold(5, shuffle=True, random_state=1)
print(round(cross_val_score(search, X, y, cv=outer).mean(), 3))
{'kneighborsclassifier__n_neighbors': 5} 0.965
0.968

The grid picks k=5k = 5 with a cross-validated accuracy of 0.9650.965, and the nested estimate of the whole procedure is 0.9680.968. Here the two agree; on small or noisy data the flat score can run well above the nested one. The scaler sits inside the pipeline, so it is refitted on the training part of every fold, as Data, features and leakage requires.

Weighted votes and kernel smoothing

A plain vote ignores how close the neighbours are. In the worked example, AA at distance 11 counts as much as EE at distance 33. Weighted kNN gives each neighbour a weight that falls with distance. With weights 1/ρ1/\rho and k=5k = 5, class ++ gets 1+0.5=1.51 + 0.5 = 1.5 and class −- gets 0.5+0.354+0.333=1.1870.5 + 0.354 + 0.333 = 1.187. The answer returns to ++.

Push the idea further and give every training point a weight from a smoothing kernel KK with a bandwidth h>0h > 0. The weighted mean of the targets is the Nadaraya–Watson estimator (Nadaraya, 1964; Watson, 1964):

a(x)=∑i=1nK(ρ(x,xi)/h) yi∑i=1nK(ρ(x,xi)/h).a(x) = \frac{\sum_{i=1}^n K\big(\rho(x, x_i)/h\big)\, y_i}{\sum_{i=1}^n K\big(\rho(x, x_i)/h\big)} .

It is the constant cc that minimizes the weighted squared error ∑iK(ρ(x,xi)/h) (yi−c)2\sum_i K\big(\rho(x, x_i)/h\big)\,(y_i - c)^2, so the regression reading carries over. For classification, set yi=1y_i = 1 for class ++ and yi=0y_i = 0 otherwise; then a(x)a(x) is the weighted share of class ++.

Take the Gaussian kernel K(t)=e−t2/2K(t) = e^{-t^2/2} and h=1h = 1. The five points of the example get weights 0.6070.607, 0.1350.135, 0.1350.135, 0.0180.018 and 0.0110.011, and the share of class ++ is (0.607+0.135)/0.907=0.818(0.607 + 0.135)/0.907 = 0.818.

The bandwidth plays the role of kk. With h=0.5h = 0.5 the share is 0.9980.998: almost only AA counts. With h=2h = 2 it is 0.5340.534: far points get nearly as much say as near ones. Small hh is local and noisy, large hh smooth and biased, and hh is chosen by cross-validation like kk.

A warning about the word. Here a kernel is a smoothing weight: a non-negative function of a distance that decreases away from zero. In the topic Kernels the word will mean a similarity that is an inner product of feature maps. The Gaussian happens to be both.

Distances and scaling

Everything rests on the distance. Four common choices:

distance formula typical use
Euclidean ∑j(xj−xj′)2\sqrt{\sum_j (x_j - x'_j)^2} numeric features on comparable scales
Manhattan ∑j∣xj−xj′∣\sum_j \lvert x_j - x'_j \rvert less dominated by one large coordinate difference
cosine 1−⟨x,x′⟩∥x∥ ∥x′∥1 - \frac{\langle x, x' \rangle}{\lVert x \rVert\, \lVert x' \rVert} word counts, embeddings: direction matters, length does not
Hamming, Jaccard share of differing coordinates; 1−∣S∩S′∣∣S∪S′∣1 - \frac{\lvert S \cap S' \rvert}{\lvert S \cup S' \rvert} binary features, sets of tags

The topic Inner products, norms and orthogonality showed that once vectors are normalized to length one, the cosine and the Euclidean distance give the same neighbours.

The Euclidean distance adds squared differences in each feature's own units. So the feature with the largest spread decides who is a neighbour. In the wine data bundled with scikit-learn, one of the 13 features has standard deviation 314314, while all the others stay below 1515. 5-NN on raw columns reaches an accuracy of 0.6630.663 in 5-fold cross-validation, and 0.9610.961 on standardized columns. On the breast-cancer data of the previous block, the same change raises the best cross-validated accuracy from 0.9320.932 to 0.9650.965.

Standardizing is not automatically right. In the digits data every feature is a pixel intensity from 0 to 16, already one shared unit. There 1-NN reaches 0.9880.988 on raw pixels and 0.9730.973 after standardizing, because standardizing blows up the noise of nearly constant border pixels.

Irrelevant features are worse than badly scaled ones. Each adds noise to every distance, and no scaling removes it. kNN has no way to learn which features matter; feature selection, or a distance learned from the data, has to do that job.

The curse of dimensionality

Nearest neighbours rely on training points lying close to the query. In many dimensions they do not. Here are three facts for data uniform in the unit cube [0,1]d[0, 1]^d (Hastie, Tibshirani and Friedman, 2009, Section 2.5).

Neighbourhoods stop being local. A sub-cube that holds a share pp of the data has edge p1/dp^{1/d}. For p=1%p = 1\% the edge is 0.10.1 at d=2d = 2, 0.630.63 at d=10d = 10 and 0.950.95 at d=100d = 100. A "neighbourhood" with 1% of the data spans most of the range of every feature.

Volume sits near the surface. The share of a dd-dimensional ball that lies within 5% of its radius from the surface is 1−0.95d1 - 0.95^d: 0.0980.098 at d=2d = 2, 0.4010.401 at d=10d = 10 and 0.9940.994 at d=100d = 100.

All distances look alike. Take 1,000 uniform points and 100 queries, and average the ratio of the nearest distance to the farthest:

dd 2 10 100 1000
nearest / farthest 0.02 0.27 0.69 0.89

In two dimensions the nearest point is 50 times closer than the farthest; in a thousand, only about 1.1 times. Beyer et al. (1999) proved that for i.i.d. coordinates this ratio tends to 1 as the dimension grows. The nearest neighbour is then hardly nearer than any other point.

To keep neighbourhoods local, the data must grow exponentially. A cube of edge 0.10.1 holds a share 0.1d0.1^d of uniform data, so finding 10 neighbours inside it takes about 10⋅10d10 \cdot 10^d points: a thousand for d=2d = 2, a hundred billion for d=10d = 10.

Two things soften the curse. Real data rarely fill all their dimensions: images, texts and sensor readings lie near low-dimensional structures, and what matters is that intrinsic dimension, not the number of columns. And a good representation changes the distances: kNN on raw pixels is mediocre, while kNN on the embeddings of a trained network is the basis of modern search. For generic tabular features, though, the curse is real.

At most twice the Bayes error

How good can such a simple rule be? Cover and Hart (1967) answered for 1-NN as the sample grows. Take two classes {0,1}\{0, 1\}, write η(x)=P(Y=1∣X=x)\eta(x) = P(Y = 1 \mid X = x), and let R∗R^* be the Bayes error from What machine learning is.

As n→∞n \to \infty, the nearest neighbour of xx comes arbitrarily close to xx. Its label becomes an independent draw from the same conditional distribution as the label of xx. The rule errs when the two labels differ:

P(a(x)≠Y∣X=x)=η(x)(1−η(x))+(1−η(x))η(x)=2η(x)(1−η(x)).P\big(a(x) \ne Y \mid X = x\big) = \eta(x)\big(1 - \eta(x)\big) + \big(1 - \eta(x)\big)\eta(x) = 2\eta(x)\big(1 - \eta(x)\big) .

Write r(x)=min⁡(η(x),1−η(x))r(x) = \min\big(\eta(x), 1 - \eta(x)\big) for the Bayes error at xx, so that R∗=E r(X)R^* = \mathbb E\, r(X) and 2η(1−η)=2r(1−r)2\eta(1 - \eta) = 2r(1 - r). The large-sample 1-NN error is R1NN=E[2r(X)(1−r(X))]R_{1\mathrm{NN}} = \mathbb E\big[2r(X)\big(1 - r(X)\big)\big]. Since r≤1/2r \le 1/2, each term is at least rr; and since E[r(X)2]≥(E r(X))2\mathbb E[r(X)^2] \ge (\mathbb E\, r(X))^2,

R∗≤R1NN≤2R∗(1−R∗)≤2R∗.R^* \le R_{1\mathrm{NN}} \le 2R^*(1 - R^*) \le 2R^* .

A single neighbour is at most twice as bad as the best possible rule. A worked example on [0,1][0, 1] with uniform XX: η=0.1\eta = 0.1 on the left half and 0.70.7 on the right. Then R∗=12(0.1+0.3)=0.2R^* = \frac12(0.1 + 0.3) = 0.2, R1NN=12(2⋅0.1⋅0.9+2⋅0.3⋅0.7)=0.30R_{1\mathrm{NN}} = \frac12(2 \cdot 0.1 \cdot 0.9 + 2 \cdot 0.3 \cdot 0.7) = 0.30, and the bound is 2⋅0.2⋅0.8=0.322 \cdot 0.2 \cdot 0.8 = 0.32. Trained on 20,000 simulated points, 1-NN has a test error of 0.3060.306.

The statement is precise in two ways. It is a limit of the expected error as n→∞n \to \infty, not a guarantee for any finite sample. And it needs mild conditions on the distribution, for example continuous class densities.

Cover and Hart put it this way: half the information of an infinite sample sits in the single nearest neighbour. The other half needs a growing neighbourhood. If k→∞k \to \infty and k/n→0k/n \to 0, the kNN rule converges to the Bayes error for every distribution on Rd\mathbb R^d with the Euclidean distance (Stone, 1977). In the example, 101-NN on the same 20,000 points errs 0.2060.206 of the time, close to R∗=0.2R^* = 0.2. This is the large-sample face of the trade-off: kk must grow to kill the variance, but more slowly than nn, so that neighbours stay local.

Fast search and what comes next

kNN pays at prediction time. A brute-force search computes nn distances in dd dimensions per query, O(nd)O(nd) operations, which is too slow for millions of objects and thousands of queries per second. Three families of indexes help.

  • kd-trees (Bentley, 1975) split the space along one coordinate at a time and prune branches that cannot hold a closer point. In a few dimensions a query costs about O(log⁡n)O(\log n). In many dimensions pruning stops working and the search slides back towards brute force: the curse again.
  • Locality-sensitive hashing (Indyk and Motwani, 1998) hashes objects so that near ones collide often and far ones rarely, then searches only the query's buckets.
  • Graph indexes such as HNSW (Malkov and Yashunin, 2020) link every stored vector to a few near neighbours, forming a proximity graph. Several such graphs are stacked on nested subsets, like a skip list, so the upper layers are sparse and their links long.

An HNSW search starts at the entry point of the top layer. There it walks greedily, always moving to a linked vector closer to the query, until no link brings it closer. From the vector it reached, it descends one layer and walks again. The bottom layer holds every vector; there the search keeps a list of the efef best candidates and finally returns the kk nearest of them. A larger efef trades speed for recall: the answer is the true set of nearest neighbours most of the time, not always. Such indexes make neighbours the core of retrieval, as the Natural Language Processing course will show with embeddings.

What changed since the memorizer: a new object now gets the answers of its most similar training objects, kk chosen by cross-validation controls complexity, and in the large-sample limit 1-NN is at most twice the Bayes error. What did not change: nothing is learned about the relationship as a whole, the whole sample is stored and searched, and in many dimensions the nearby points are not there.

The topic Least squares takes the opposite bet: a global model with one weight per feature, fitted to all the data at once. It has a closed-form solution, a geometric meaning as a projection, and a reading as maximum likelihood under Gaussian noise.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Go deeper — optional

Code and labs do not count toward the main percentage or the certificate.

  • k-NN majority voteoptional

    NumPy: distances, k nearest, majority class. Self-check in the notebook.

    ~15 min · easier on a computer · Nearest neighbours topic read.

    Self-check in the notebook — not part of mastery or the certificate.

Full notes

Answers are saved on the server and tied to this browser until you sign in.