Search

Search papers and lessons

K-Nearest Neighbors

Level 2 · 9 min read

K-nearest neighbors predicts a new point's label from the k training points closest to it, with no training step beyond storing the examples.

On this page

  • Colour = topic mix
  • Discrete math
  • Calculus
  • Linear algebra
  • Probability
  • Learning basics
  • Losses & regularization
  • ReadReady to readNot yet

TL;DR

K-nearest neighbors (KNN) predicts the label of a new point by looking at the k training points closest to it. For a class label it takes a majority vote among those neighbours; for a number it takes their average. Its training step is just storing the examples, so all the work happens at prediction time.

Builds on: Euclidean Distance, Supervised Learning · Leads to: Curse of Dimensionality, Feature Scaling

Where it's used

Handwritten digit recognition. A reader sees an image of a digit as a list of pixel brightnesses. KNN compares it with stored images of known digits and labels it with the most common digit among the closest ones. On the standard digit benchmark (MNIST), plain KNN reaches error rates of a few percent, which is competitive for so simple a method.

Similar-item lookup. A shop wants "customers who viewed this also viewed". Each product is represented as a vector of numbers, and the nearest products in that space are shown. Modern search systems over text embeddings use the same idea at a much larger scale, with approximate methods that trade a little accuracy for speed.

A quick baseline for tables. Given rows of measurements with a known outcome, KNN is often the first thing tried because it needs no assumptions about the shape of the relationship. If it does well, a more complex model may not be needed; if it does badly, the features may need work.

How it works

Here is a tiny training set of five labelled points in two dimensions, with k = 3.

PointCoordinatesLabel
P1(1, 1)red
P2(2, 1)red
P3(1, 3)blue
P4(4, 5)blue
P5(5, 4)blue

A new point arrives at (2, 3).

  1. Store the examples. Training means keeping the five points and their labels. Nothing is fitted.
  2. Measure the distance to every stored point. Use straight-line distance. P3 at (1, 3) differs by 1 in the first coordinate and 0 in the second, so its distance is 1. Check: 12+02=1\sqrt{1^2 + 0^2} = 1.
  3. Repeat for the others. P2 is at distance 2, P1 at about 2.24, P4 at about 2.83, P5 at about 3.16.
  4. Keep the k closest. With k = 3 these are P3, P2 and P1. Check: the other two are farther away than 2.24.
  5. Vote. P3 is blue, P2 and P1 are red. Two votes for red beat one for blue, so the new point is red.
flowchart LR
  A["New point"] --> B["Distance to every stored point"]
  B --> C["Keep the k closest"]
  C --> D["Majority vote or average of their labels"]

The math

Definition: K-nearest-neighbour prediction

Let the training set be pairs (xi,yi)(\mathbf{x}_i, y_i) for i=1,…,ni = 1, \dots, n, where each xi\mathbf{x}_i is a vector of features and yiy_i is its label. For a new point q\mathbf{q}, let Nk(q)N_k(\mathbf{q}) be the set of the kk training points with the smallest Euclidean distance ∥xi−q∥\lVert \mathbf{x}_i - \mathbf{q} \rVert to q\mathbf{q}. The classification rule is the most common label in Nk(q)N_k(\mathbf{q}); the regression rule is their average, y^=1k∑i∈Nk(q)yi\hat{y} = \frac{1}{k} \sum_{i \in N_k(\mathbf{q})} y_i.

Step 2 in symbols

For the query q=(2,3)\mathbf{q} = (2, 3) and x3=(1,3)\mathbf{x}_3 = (1, 3), the difference is x3−q=(−1,0)\mathbf{x}_3 - \mathbf{q} = (-1, 0), so ∥x3−q∥=(−1)2+02=1.\lVert \mathbf{x}_3 - \mathbf{q} \rVert = \sqrt{(-1)^2 + 0^2} = 1. Every other distance is computed the same way.

Step 4 in symbols

Sorting the five distances gives 1 (P3), 2 (P2), about 2.24 (P1), about 2.83 (P4), about 3.16 (P5). The set N3(q)N_3(\mathbf{q}) is therefore P3, P2 and P1.

Step 5 in symbols

The labels in N3N_3 are blue, red, red. Counting gives red 2 and blue 1, so the prediction is red.

Changing k changes the answer. With k=1k = 1 only P3 counts, so the label is blue. With k=5k = 5 all five points vote: blue 3 and red 2, so the label is blue. Small k follows local detail; large k smooths it out.

Worked examples

Example
1. Two training points on a line

A red point sits at x=0x = 0 and a blue point at x=10x = 10. Use k=1k = 1 and classify x=3x = 3.

  1. Distance from 3 to the red point: ∣3−0∣=3|3 - 0| = 3.
  2. Distance from 3 to the blue point: ∣3−10∣=7|3 - 10| = 7.
  3. The closest point is the red one, so the nearest neighbour is red.
  4. Interpretation: the query sits closer to the red point, so it inherits the red label. Nothing else is needed to make the prediction.
Example
2. The standard case: the five points above

Use the table from How it works with query q=(2,3)\mathbf{q} = (2, 3), and compare k=1k = 1, k=3k = 3 and k=5k = 5.

  1. Squared distances (no square roots needed for ranking): P1 gives 12+22=51^2 + 2^2 = 5, P2 gives 02+22=40^2 + 2^2 = 4, P3 gives 12+02=11^2 + 0^2 = 1, P4 gives 22+22=82^2 + 2^2 = 8, P5 gives 32+12=103^2 + 1^2 = 10.
  2. Ranking by squared distance, from closest: P3 (1), P2 (4), P1 (5), P4 (8), P5 (10).
  3. k=1k = 1: the closest is P3, blue. Prediction: blue.
  4. k=3k = 3: P3, P2, P1 are blue, red, red. Prediction: red.
  5. k=5k = 5: all five points, with blue P3, P4, P5 and red P1, P2. Prediction: blue.
  6. Interpretation: the same query has three different answers depending on how many neighbours it consults. Choosing k is a real decision, usually made with Cross-Validation.
Example
3. A realistic house price with feature scaling

A house is described by two features: area in square metres and number of rooms. The task is to predict price in thousands of dollars. The query house is 80 square metres with 3 rooms. Three sold houses are:

  • C: 80 square metres, 4 rooms, price 300
  • A: 82 square metres, 1 room, price 250
  • B: 120 square metres, 3 rooms, price 420

Use k = 1 for the first two steps.

  1. Without scaling, the distances are: C differs by 1 room, so 1. A differs by 2 square metres and 2 rooms, so 22+22≈2.83\sqrt{2^2 + 2^2} \approx 2.83. B differs by 40 square metres, so 40. The nearest is C, and the prediction is 300.
  2. Scaling puts both features on a 0 to 1 range. Divide area by 200 (its rough range) and rooms by 4 (from 1 to 5). The query becomes (0.40,0.75)(0.40, 0.75). C becomes (0.40,1.00)(0.40, 1.00), A becomes (0.41,0.25)(0.41, 0.25), B becomes (0.60,0.75)(0.60, 0.75).
  3. Scaled distances: C is 0.25, A is about 0.50, B is 0.20. Now B is the nearest, and the prediction is 420.
  4. Interpretation: without scaling, the area column dominates the distance because its numbers are larger. The rooms column was barely counted. Scaling changed which house is the nearest neighbour, and so changed the prediction.

Try it: keep the scaled distances and use k = 3 with the average of the labels as the prediction. What is it? Answer: (420+300+250)/3=970/3≈323.3(420 + 300 + 250) / 3 = 970 / 3 \approx 323.3, so about 323 thousand dollars.

Common mistakes and tradeoffs

It is tempting to think KNN learns from the data during training, as a neural network does. In fact it only stores the examples, so all the cost moves to prediction: each new query is compared with every stored point. For large datasets this is slow and needs approximate search structures.

It is tempting to think a larger k is always safer. In fact a large k blurs the boundary between classes, and the classifier starts to ignore local structure. A very small k follows each noisy point and behaves like an overfit model. The right k is found by trying values on held-out data.

It is tempting to feed the raw features straight in. In fact distances are dominated by whichever feature has the largest numbers, as the house example shows. Put features on comparable scales first, as in Feature Scaling.

It is tempting to add more features when accuracy is poor. In fact in high dimensions almost all points end up roughly equally far apart, so the "nearest" neighbours stop meaning much. This is the Curse of Dimensionality.

When to use it: small to medium datasets with few features, a clear notion of distance, and a need for a model that needs no training. When not to use it: very large datasets with many features, or when prediction must be fast; a Decision Tree or a linear model is often better there.

History

Evelyn Fix and Joseph Hodges described the nearest-neighbour rule in a 1951 report on discriminant analysis. It was a rule without a clear error guarantee for many years. In 1967 Thomas Cover and Peter Hart showed that, as the data grows, the error of the one-nearest-neighbour rule is at most twice the best error any classifier can reach. The rule then became a standard baseline in pattern recognition, and its simplicity kept it in use as data grew.

Recap

  • KNN stores the labelled examples and predicts from the k closest ones.
  • Closeness is measured with a distance, usually Euclidean, which needs comparable feature scales.
  • The vote (or average) over k neighbours is the prediction; k controls how local the decision is.
  • Its cost is paid at prediction time, and it weakens as the number of features grows.
  • Read next: Curse of Dimensionality, which explains why distances lose meaning, and Bias-Variance Tradeoff, which explains how k trades bias against variance.

Check yourself

QuestionWhat does KNN store during training?Show answer
The labelled training examples. It fits no parameters; prediction compares a new point with the stored examples.
QuestionUsing the five points in the standard example, what is the prediction for query (2, 3) with k = 2?Show answer
The two closest are P3 (blue, distance 1) and P2 (red, distance 2). They disagree, so a tie breaks the vote. This is why odd values of k are often used for two-class problems: the vote cannot tie.
QuestionWhy does an unscaled feature with large numbers dominate KNN distances?Show answer
Distances are built from differences of coordinates. A feature whose values range over hundreds contributes differences of hundreds, which swamp differences of one or two in a feature with a small range.
QuestionA dataset has 100 features, and the nearest neighbours of a query are all at nearly the same distance. What problem is this, and what does it imply for KNN?Show answer
This is the curse of dimensionality. In high dimensions the nearest and farthest points are almost equally far away, so the neighbour vote carries little information and KNN accuracy falls.

Sources