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 = 1: the closest dot knows best
- The biggest k
- Somewhere in between
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…
- still about 98.7%: it's useless, so it's ignored
- much worse, about 84%
- about 10%: chance
Why k = 1 is wrong at most twice as often as the best possible model
- 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.
- 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\).
- 1-NN is wrong when the point and its neighbor disagree: chance \(p(1-p) + (1-p)p = 2p(1-p)\).
- 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).
- 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
- Units and useless columns. Scale every column, and drop or down-weight columns that shouldn't define similarity. But scaling is an opinion too: on the bank calls, unscaled kNN leans almost entirely on
pdays(days since the last contact, spread 187), which happens to be the most telling column, so it scores the same as scaled (AUC 0.77 at k = 25 both ways). The right distance is a modeling decision, not a formality. - Many columns. Distances concentrate, as the slider shows. Reduce the columns first (PCA, lesson L2), or learn a distance where similar things are close: that's what embeddings are (stage 6).
- Prediction cost. Every prediction scans the stored data: measured, 1,000 predictions took 2 ms against 1,000 stored rows and 27 ms against 100,000. The model is the data (3.8 MB on the bank calls, against 4 kB for logistic regression). Trees and indexes (
KDTree, FAISS, HNSW) cut the search to a fraction, approximately in high dimensions. - Imbalance. With 1% red, red points are rarely among the k nearest, so kNN rarely says red. Use the vote share as a score and choose the threshold, or weight votes by distance.
- No extrapolation. Like trees, it can only predict values it has seen: kNN regression past the data returns the average of the edge points.
5. The knobs that matter
| Knob | In scikit-learn | What it does |
|---|---|---|
| k | n_neighbors | Small: detailed, noisy. Large: smooth, biased toward the majority. Pick on validation data; odd k avoids ties for two classes. |
| Scaling | StandardScaler in a pipeline | Decides how much each column counts. The most important knob, and the easiest to forget. |
| Distance | metric (Euclidean, Manhattan, cosine…) | Cosine for text and embeddings (direction, not length); Manhattan is less swayed by one big difference. |
| Vote weights | weights="distance" | Closer neighbors count more; helps when k is large or near the edges. |
| Search structure | algorithm (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