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.
| Point | Coordinates | Label |
|---|---|---|
| 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).
- Store the examples. Training means keeping the five points and their labels. Nothing is fitted.
- 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: .
- Repeat for the others. P2 is at distance 2, P1 at about 2.24, P4 at about 2.83, P5 at about 3.16.
- Keep the k closest. With k = 3 these are P3, P2 and P1. Check: the other two are farther away than 2.24.
- 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
Let the training set be pairs for , where each is a vector of features and is its label. For a new point , let be the set of the training points with the smallest Euclidean distance to . The classification rule is the most common label in ; the regression rule is their average, .
Step 2 in symbols
For the query and , the difference is , so 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 is therefore P3, P2 and P1.
Step 5 in symbols
The labels in are blue, red, red. Counting gives red 2 and blue 1, so the prediction is red.
Changing k changes the answer. With only P3 counts, so the label is blue. With 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
A red point sits at and a blue point at . Use and classify .
- Distance from 3 to the red point: .
- Distance from 3 to the blue point: .
- The closest point is the red one, so the nearest neighbour is red.
- Interpretation: the query sits closer to the red point, so it inherits the red label. Nothing else is needed to make the prediction.
Use the table from How it works with query , and compare , and .
- Squared distances (no square roots needed for ranking): P1 gives , P2 gives , P3 gives , P4 gives , P5 gives .
- Ranking by squared distance, from closest: P3 (1), P2 (4), P1 (5), P4 (8), P5 (10).
- : the closest is P3, blue. Prediction: blue.
- : P3, P2, P1 are blue, red, red. Prediction: red.
- : all five points, with blue P3, P4, P5 and red P1, P2. Prediction: blue.
- 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.
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.
- Without scaling, the distances are: C differs by 1 room, so 1. A differs by 2 square metres and 2 rooms, so . B differs by 40 square metres, so 40. The nearest is C, and the prediction is 300.
- 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 . C becomes , A becomes , B becomes .
- 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.
- 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: , 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.