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 -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 for a training object 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 between objects. For a query , let be the indices of the training objects nearest to ; in this topic always counts neighbours. For classification, predict the most frequent class among them:
For regression, predict the mean of their targets:
The topic Conditional expectation showed that the best predictor under squared loss is . The regression rule estimates it locally: it averages over the training points whose lies close to . In the same way, the vote shares estimate the class probabilities . "Training" is just storing the sample; all the work happens at prediction time.
A worked example. The query is . Two training points have class : and . Three have class : , and . The Euclidean distances from the query to are , , , and .
- : the only neighbour is , so the answer is .
- : , and vote two to one for .
- : all five points vote three to two for .
The answer depends on , and so does its quality.
Choosing k: bias against variance
Small follows the data closely. Large averages over a wide neighbourhood. Both extremes fail, for opposite reasons.
Take regression with noise of variance around the true . The mean of independent noisy targets has variance , the sample-mean result from Estimators: bias and variance. So a larger lowers the variance of the prediction. But the -th neighbour lies farther from , where differs from its value at . So a larger 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 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 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 . The risk of each rule is computed exactly from the known distribution.
| training error | risk | |
|---|---|---|
| 1 | 0.000 | 0.188 |
| 15 | 0.115 | 0.141 |
| 101 | 0.175 | 0.204 |
At the boundary circles single points of the wrong class: overfitting. At the vote averages over half the sample and the boundary is too smooth: underfitting. At the risk comes close to the Bayes error.
In practice the risk is unknown, so 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.968The grid picks with a cross-validated accuracy of , and the nested estimate of the whole procedure is . 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, at distance counts as much as at distance . Weighted kNN gives each neighbour a weight that falls with distance. With weights and , class gets and class gets . The answer returns to .
Push the idea further and give every training point a weight from a smoothing kernel with a bandwidth . The weighted mean of the targets is the Nadaraya–Watson estimator (Nadaraya, 1964; Watson, 1964):
It is the constant that minimizes the weighted squared error , so the regression reading carries over. For classification, set for class and otherwise; then is the weighted share of class .
Take the Gaussian kernel and . The five points of the example get weights , , , and , and the share of class is .
The bandwidth plays the role of . With the share is : almost only counts. With it is : far points get nearly as much say as near ones. Small is local and noisy, large smooth and biased, and is chosen by cross-validation like .
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 | numeric features on comparable scales | |
| Manhattan | less dominated by one large coordinate difference | |
| cosine | word counts, embeddings: direction matters, length does not | |
| Hamming, Jaccard | share of differing coordinates; | 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 , while all the others stay below . 5-NN on raw columns reaches an accuracy of in 5-fold cross-validation, and on standardized columns. On the breast-cancer data of the previous block, the same change raises the best cross-validated accuracy from to .
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 on raw pixels and 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 (Hastie, Tibshirani and Friedman, 2009, Section 2.5).
Neighbourhoods stop being local. A sub-cube that holds a share of the data has edge . For the edge is at , at and at . A "neighbourhood" with 1% of the data spans most of the range of every feature.
Volume sits near the surface. The share of a -dimensional ball that lies within 5% of its radius from the surface is : at , at and at .
All distances look alike. Take 1,000 uniform points and 100 queries, and average the ratio of the nearest distance to the farthest:
| 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 holds a share of uniform data, so finding 10 neighbours inside it takes about points: a thousand for , a hundred billion for .
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 , write , and let be the Bayes error from What machine learning is.
As , the nearest neighbour of comes arbitrarily close to . Its label becomes an independent draw from the same conditional distribution as the label of . The rule errs when the two labels differ:
Write for the Bayes error at , so that and . The large-sample 1-NN error is . Since , each term is at least ; and since ,
A single neighbour is at most twice as bad as the best possible rule. A worked example on with uniform : on the left half and on the right. Then , , and the bound is . Trained on 20,000 simulated points, 1-NN has a test error of .
The statement is precise in two ways. It is a limit of the expected error as , 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 and , the kNN rule converges to the Bayes error for every distribution on with the Euclidean distance (Stone, 1977). In the example, 101-NN on the same 20,000 points errs of the time, close to . This is the large-sample face of the trade-off: must grow to kill the variance, but more slowly than , so that neighbours stay local.
Fast search and what comes next
kNN pays at prediction time. A brute-force search computes distances in dimensions per query, 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 . 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 best candidates and finally returns the nearest of them. A larger 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, 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.
Answers are saved on the server and tied to this browser until you sign in.