AI from scratch · Model zoo 3 of 10 · k-nearest neighbors

k-nearest neighbors

A model with no weights and no training. To label something new, find the k most similar examples you've already seen and let them vote. It's how you'd guess a neighborhood's rent, and it's the idea under every "more like this" button and every vector search in stage 6. The clusters lesson used it on a map of rail stations; this page is about what decides whether it works: k, the distance, and the number of columns.

1. The idea in one picture: tap a spot, the neighbors vote

Tap anywhere on the map. Lines join the spot to its k nearest training dots, and the spot's color is their vote (the share of red). The shading is that vote at every spot.

On two overlapping blobs, slide k from 1 to 75. Where is validation accuracy best?

k is chapter 11's complexity knob, turned backwards: k = 1 makes an island around every noisy dot (100% on training, worse on new data); a huge k averages over so much of the plane that the vote turns into "whatever's more common nearby". A middle k averages away the noise and keeps the shape. Choose it on validation data.

kNN labels a point by the vote of its k closest examples, so everything depends on what "close" means.

2. How it "learns": by remembering

Fitting stores the training rows. Predicting computes the distance from the new point to every stored row, usually the straight-line (Euclidean) distance, and votes among the k smallest:

\[ d(a, b) = \sqrt{\textstyle\sum_j (a_j - b_j)^2}, \qquad \hat p(\text{red}) = \frac{\#\text{red among the } k \text{ nearest}}{k} \]

That sum is the catch. Every column adds its squared difference, so a column whose numbers are big dominates the distance whatever it means. Tick x measured in hundredths: nothing about the dots changed, only the units, yet the neighbors (tap a spot) line up in a thin vertical strip, because a hundredth-step in x now costs as much as a full step in y. The map turns into vertical stripes. Scale both columns (subtract each column's mean, divide by its spread) and the map comes back.

Handwritten digits, 64 pixel columns from 0 to 16, kNN at 98.7%. Someone adds one more column: the scanner's serial number, from 0 to 1000. Accuracy becomes…

Measured: 83.8%. The serial number's differences (hundreds) swamp the pixels' (up to 16), so "nearest" mostly means "scanned by a machine with a similar serial". Scaled, it's 97.3%. kNN has no weights to learn that a column is useless: every column counts, in proportion to its numbers.
Why k = 1 is wrong at most twice as often as the best possible model
  1. Some error can't be avoided: where red and blue overlap, even a model that knows the true chance \(p\) of red at a spot is wrong \(\min(p, 1 - p)\) of the time. That's the Bayes error, the floor.
  2. With lots of data, a point's nearest neighbor sits almost on top of it, so the neighbor's label is a fresh draw from the same chance \(p\).
  3. 1-NN is wrong when the point and its neighbor disagree: chance \(p(1-p) + (1-p)p = 2p(1-p)\).
  4. Since \(1 - p \le 1\) and \(p \le 1\), \(2p(1-p) \le 2\min(p, 1-p)\): at most twice the floor (Cover and Hart, 1967).
  5. Where the classes don't overlap (\(p\) is 0 or 1), both are 0: that's why 1-NN is so good on clean data like digits. Larger k averages more draws, and as k grows (but stays a tiny share of the data) kNN closes in on the floor itself.

3. Build it: kNN in ten lines of NumPy

Handwritten digits, 8 × 8 pixels: the distance is literally how different two pictures look, pixel by pixel.

Ties in the vote go to the smaller digit here (that's what argmax does); scikit-learn breaks them its own way, so a test row or two can differ. "Training" took no time; all the work is in predicting, which is the opposite of every other model in the zoo.

4. Where it shines, where it breaks

Shines: no assumptions about the shape of the boundary (it bends around moons and rings as easily as a straight edge), nothing to train, new data is added by appending a row, and every prediction comes with its evidence: "these five past cases". On digits it gets 98.7%, ahead of logistic regression's 96.9%. It's also the backbone of retrieval: when stage 6 finds the passages nearest a question, that's kNN on embeddings, with a smart index instead of a full scan.

Its weak spot is the distance, and it gets worse with every column. Here are 1,000 random points in a cube; how much farther is the farthest point from a query than the nearest?

In 2 columns the nearest point is 60 times closer than the farthest (measured: a ratio of 0.017). In 1,000 columns the ratio is 0.90: every point is about equally far, and "nearest" stops meaning anything. This is the curse of dimensionality. On digits plus 640 columns of random noise, kNN falls from 98.7% to 48%, while logistic regression, which can learn to give noise a weight near zero, still gets 86%.

kNN is the right first model when similarity is meaningful and columns are few; with many or unscaled columns, distance stops telling similar from different.

Where it breaks, and what people do

5. The knobs that matter

KnobIn scikit-learnWhat it does
kn_neighborsSmall: detailed, noisy. Large: smooth, biased toward the majority. Pick on validation data; odd k avoids ties for two classes.
ScalingStandardScaler in a pipelineDecides how much each column counts. The most important knob, and the easiest to forget.
Distancemetric (Euclidean, Manhattan, cosine…)Cosine for text and embeddings (direction, not length); Manhattan is less swayed by one big difference.
Vote weightsweights="distance"Closer neighbors count more; helps when k is large or near the edges.
Search structurealgorithm (brute, KD-tree, ball tree)Same answers, different speed; for millions of vectors, approximate indexes (FAISS, HNSW).

Next in the zoo: a model that counts instead of measuring distances.

All chapters: AI from scratch. Digits: UCI optical recognition of handwritten digits, via scikit-learn.

Last updated