Classify a point by asking its nearest neighbours. Move it around, change k and the distance, see why features must be scaled and why distances break down in high dimensions.
1Ask the neighbours
To label a new point, find the k training points closest to it and let them vote. Here k = 3: two amber, one teal, so the new point is amber.
2Small k is jumpy, big k is smooth
With k = 1 every point gets its own little territory, mislabelled ones included. A larger k averages over more neighbours, and the boundary smooths out.
3Distance only means something at the same scale
Income in dollars swamps age in years: a $1,000 difference outweighs 40 years. Rescale the features first, or the nearest neighbours are just the people with the closest income.
Start here
Ask the neighbours
K-nearest neighbours has no training step and no formula. To label a new point (the diamond), it finds the k training points closest to it and lets them vote. Click anywhere on the plot to move the new point, then step through. The shading shows what KNN would answer at every spot: the decision map.
Vote with k = 5
- teal0
- violet0
- amber0
Press Start to classify the new point with k = 5. (The answer will be amber.)
Euclidean distance
√((x₁ − x₂)² + (y₁ − y₂)²)
The straight line between two points. Everything the same distance away forms a circle. The usual default.
Manhattan distance
|x₁ − x₂| + |y₁ − y₂|
Walking the city grid: across, then up. Everything the same distance away forms a diamond. Less swayed by one huge difference.
The one setting that matters
Choosing k
With k = 1, every training point is right about itself, so training accuracy is a perfect 100%. But each mislabelled point grabs a little island of the map (turn the map on above and set k to 1). As k grows, the islands vanish and the boundary smooths. Too large and KNN just answers with the biggest class everywhere. Accuracy on 200 new points from the same groups tells the truth.
- Training, k = 5
- 84%
- New points, k = 5
- 74%
Somewhere in the middle is best; here the new-point accuracy peaks around k = 30.
In practice, pick k by cross-validation, and use an odd k for two classes so votes can't tie. Overfitting & cross-validation →
The classic mistake
Scale your features first
Sixty customers: age in years, income in dollars, and whether they bought. Buying depends on age. But KNN only sees distance, and a $1,000 income gap counts as much as 1,000 years of age. Unscaled, the “nearest” people are simply those with the closest income, whatever their age. Click any person to see their 5 nearest neighbours.
66 years, $56,500. Neighbours' ages: 39, 61, 58, 58, 30.
- Raw: accuracy
- 53%
- Standardised
- 88%
Raw units: the neighbours lie in a flat band of similar income, from young to old. Age, the feature that matters, is almost ignored.
Accuracy is measured on 120 new customers, with k = 5.
Where it breaks
The curse of dimensionality
KNN assumes the nearest points are much nearer than the rest. In two dimensions that's true. Add dimensions and something strange happens: all the distances bunch up, so the “nearest” point is barely nearer than the farthest, and the neighbours stop meaning anything. Here, 400 random points in a cube of each size, measured from one more random point.
- Nearest ÷ farthest
- 0.01
- Contrast
- 94×
In 2-D the distances spread from almost 0 to the maximum: the nearest point is far nearer than most.
Real data usually lives on a far simpler surface than its raw dimension count, which is why KNN on good embeddings still works. Reducing dimensions first (with PCA, for instance) also helps.
| dimensions | 1 | 2 | 3 | 5 | 10 | 20 | 50 | 100 | 300 | 1000 |
|---|---|---|---|---|---|---|---|---|---|---|
| nearest ÷ farthest | 0.00 | 0.01 | 0.04 | 0.19 | 0.25 | 0.33 | 0.61 | 0.73 | 0.84 | 0.90 |
Lazy learning
The catch, and where KNN shines
No training, slow answers
Training is just storing the data. Every prediction then measures the distance to all n points: cheap to build, expensive to ask, and the whole dataset must be kept.
Faster search
KD-trees and ball trees skip far-away regions in low dimensions. For millions of vectors, approximate indexes such as HNSW find almost-nearest neighbours fast. RAG →
Not just classes
KNN regression averages the neighbours' numbers instead of counting votes: a house's price from similar houses nearby.
Where you'll meet it
Recommendations (“people like you bought…”), semantic search over embeddings, filling in missing values, and as a quick baseline. Embeddings →
No magic, just arithmetic
The maths, step by step
A new point at (4, 5) and five labelled points. With k = 3, which class is it? Then, does weighting the votes by distance change the answer?
- 1
Measure every distance
Euclidean distance: the straight line, by Pythagoras.d(new, A) = √((3.5 − 4)² + (4.5 − 5)²) = 0.7071
d(new, B) = √((6 − 4)² + (5 − 5)²) = 2.0000
d(new, C) = √((4 − 4)² + (7 − 5)²) = 2.0000
d(new, D) = √((2 − 4)² + (6 − 5)²) = 2.2361
d(new, E) = √((7 − 4)² + (8 − 5)²) = 4.2426
- 2
Keep the 3 nearest
Sort by distance and cut after k.A (0.707), B (2.000), C (2.000) | D (2.236), E (4.243)
- 3
Vote
One vote each. The majority wins.teal: 1, amber: 2 → amber
- 4
Or weight each vote by 1 ÷ distance
Closer neighbours count for more. One very close point can outvote two that are further away.weight A = 1 ÷ 0.7071 = 1.4142
weight B = 1 ÷ 2.0000 = 0.5000
weight C = 1 ÷ 2.0000 = 0.5000
teal: 1.414, amber: 1.000 → teal
The answer flips: A is so close that its single vote outweighs the other two.
Keep going
Resources
Hand-picked places to go deeper. They're all free to read or watch, and they open in a new tab.
How it works: K-Nearest Neighbours
Step by step
- Teal class
- Violet class
- Amber class
Press Start or Step: the step the animation is on lights up below.
- 1
Take the new point
KNN does nothing until asked: a new, unlabelled point arrives.
q = new point - 2
Measure every distance
Distance from the new point to each training point, with the chosen metric.
d[i] = dist(q, X[i]) - 3
Sort by distance
Rank the training points from nearest to farthest. (A heap or a search index avoids a full sort.)
order = argsort(d) - 4
Take the k nearest
Keep the first k. The neighbourhood is a circle (Euclidean) or a diamond (Manhattan) reaching the k-th point.
nn = order[:k] - 5
Vote
Majority class among the neighbours, optionally weighted by 1 / distance. Break ties by the nearest tied point.
return mode(y[nn])
K-nearest neighbours (KNN) classifies a new point by finding the k training points closest to it and taking a vote. There is no training step: the model is the stored data, which is why it's called a lazy learner.
Everything rests on the distance. Euclidean (straight line) is the usual choice, Manhattan (along the axes) another. Because distance mixes all the features, they must be on comparable scales: standardise them first.
k controls the trade-off. k = 1 memorises the training data, noise included (overfitting); a very large k ignores local structure and predicts the biggest class (underfitting). Choose k by cross-validation. Votes can also be weighted by 1 / distance so closer neighbours count for more.
Where you'll meet it
- Small to medium datasets with few features, where similar inputs really do have similar labels.
- Recommendations and search over embeddings (“find the items most like this one”), and as a fast baseline before training anything.
- Interview favourites: “how do you pick k?”, “why must features be scaled?”, “what is the curse of dimensionality?”, “what does KNN cost at prediction time?”.
Training is free, but every prediction measures the distance to all n stored points of d features each, so the whole dataset is kept in memory. KD-trees and ball trees speed up low-dimensional search; approximate indexes like HNSW scale to millions of high-dimensional vectors.