K-Nearest Neighbours

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.

?k = 3 → amber wins 2 to 1

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.

k = 1k = 15

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.

age40 years apartincome$1,000 apartafter scaling: both count

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.

02468100246810(4.03, 4.92) teal(2.92, 1.32) teal(3.31, 1.96) teal(1, 5.7) teal(3.93, 1.95) teal(2.4, 3.14) teal(3.6, 1.79) teal(2.02, 2.35) teal(3.85, 1.38) teal(2.83, 4.01) teal(3.88, 3.17) teal(2.14, 3.22) violet(1.13, 1.86) teal(2.59, 4.92) teal(2.13, 2.6) teal(3.67, 3.79) violet(3.27, 2.67) teal(2.98, 3.88) teal(5.95, 2.55) teal(3.59, 4.23) teal(3.91, 3.53) teal(3.18, 2.53) teal(6.58, 3.28) violet(6.92, 4.67) violet(6.22, 5.55) violet(8.08, 3.29) violet(8.01, 4.04) violet(6.23, 3.35) violet(4.42, 4.33) violet(5.87, 5.53) violet(5.81, 5.48) amber(5.97, 1.93) violet(7.55, 3.01) violet(6.13, 3.44) violet(5.97, 1.18) violet(4.77, 4.19) violet(7.86, 3.4) violet(6.28, 1.79) violet(4.24, 4.15) amber(3.51, 5.9) amber(4.69, 7.29) amber(5.7, 4.94) amber(2.94, 9.7) amber(3.74, 5.98) amber(3.79, 7.92) teal(6.46, 4.49) amber(3.88, 9.02) amber(3.19, 7.08) amber(3.79, 4.61) amber(3.77, 5.38) amber?
teal (21)violet (17)amber (12)◆ new pointdashed: the neighbourhood (a circle)
5
Distance
Votes
Map

Vote with k = 5

  • teal0
  • violet0
  • amber0
Step 0 / 9
700 ms

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.

110203040490.40.60.81
on the training pointson new pointsx: k (follows the slider above)
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.

203040506070406080100120buyers are mostly over 4566 years, $56,500: bought32 years, $73,500: didn't buy51 years, $90,500: bought57 years, $108,000: bought41 years, $71,500: bought69 years, $70,000: bought33 years, $96,500: didn't buy43 years, $26,000: didn't buy58 years, $34,000: bought36 years, $77,000: didn't buy34 years, $78,000: didn't buy63 years, $112,500: bought53 years, $72,500: bought68 years, $25,500: bought54 years, $77,500: bought58 years, $59,500: bought20 years, $48,000: didn't buy63 years, $32,000: bought69 years, $83,500: bought58 years, $54,000: bought29 years, $118,500: didn't buy67 years, $68,500: bought20 years, $36,000: didn't buy65 years, $114,000: bought39 years, $88,500: didn't buy52 years, $94,500: bought67 years, $92,500: bought62 years, $39,500: bought39 years, $120,000: bought58 years, $63,500: bought22 years, $90,500: didn't buy51 years, $78,500: bought39 years, $52,000: bought37 years, $33,000: didn't buy61 years, $55,000: bought27 years, $107,000: didn't buy59 years, $100,500: bought43 years, $77,000: didn't buy38 years, $70,000: didn't buy57 years, $38,000: bought49 years, $43,500: bought39 years, $57,000: didn't buy44 years, $86,000: bought30 years, $60,000: didn't buy24 years, $38,000: didn't buy52 years, $62,500: bought58 years, $85,000: bought49 years, $114,500: bought28 years, $113,500: didn't buy64 years, $109,500: bought57 years, $99,000: bought64 years, $119,000: bought51 years, $108,500: bought59 years, $89,500: bought29 years, $79,000: didn't buy62 years, $105,000: bought40 years, $38,000: didn't buy45 years, $108,000: didn't buy47 years, $102,000: bought61 years, $92,500: bought
boughtdidn't buyage across, income (in $1,000s) up
Features

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.

00.250.50.751distance ÷ largest distance
Dimensions
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.

dimensions12351020501003001000
nearest ÷ farthest0.000.010.040.190.250.330.610.730.840.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. 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. 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. 3

    Vote

    One vote each. The majority wins.

    teal: 1, amber: 2 → amber

  4. 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. 1

    Take the new point

    KNN does nothing until asked: a new, unlabelled point arrives.

    q = new point
  2. 2

    Measure every distance

    Distance from the new point to each training point, with the chosen metric.

    d[i] = dist(q, X[i])
  3. 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. 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. 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?”.
time O(n · d) per predictionspace O(n · d)

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.