# Chapter 8: Nearest Neighbours

> Classifying a point by looking at the points around it. Opening question: Can you classify something without ever fitting a model?

From *The Book of Machine Learning*, a free interactive machine learning textbook. Interactive version, with figures to use: https://thebookofml.com/nearest-neighbours/

Every model so far has had weights, and learning meant finding good values for them. This chapter's method has no weights and does no training at all. It is one of the oldest ideas in machine learning, it fits in a sentence, and it is a strong baseline for surprisingly many problems.

The sentence is: *to classify something new, find the most similar things you have already seen, and go with the majority.*

## Ask the neighbours

Suppose you already know the kind of sixty points: some filled, some hollow. A new point arrives. Look at the few known points closest to it and let them vote.

The number of neighbours asked is called $k$, and the method is k-nearest neighbours, or k-NN.

> **Interactive figure: A vote among the closest points.** Sixty known points of two kinds. The orange point is new, and the lines join it to the neighbours that get a vote.
> Try it: drag the orange point through the gap between the two groups and watch the vote change. Then set k to 1, and to 15.
> (Use it at https://thebookofml.com/nearest-neighbours/)

"Closest" needs a definition. The usual one is Euclidean distance, the straight-line distance you would measure with a ruler:

$$
\text{distance}(a, b) = \sqrt{(a_1 - b_1)^2 + (a_2 - b_2)^2 + \dots + (a_d - b_d)^2}
$$

The formula works for any number of features, which is what lets the same idea compare patients, houses or images as easily as points on a page.

## The whole map

Ask the same question at every spot in the plane and colour each spot by the answer. The result is a map of the model's decisions. Unlike logistic regression, whose boundary was always a straight line, this boundary can take any shape the data suggests.

> **Interactive figure: What k-NN would say everywhere.** Shaded areas would be called filled, unshaded areas hollow.
> Try it: start with k = 1 and look for small islands around single points. Raise k and watch them dissolve. Then click to add a few points of the wrong kind inside a region.
> (Use it at https://thebookofml.com/nearest-neighbours/)

Notice what happened when you added a point: the map changed at once, with no retraining. There is nothing to retrain. The "model" *is* the stored data. This style is called instance-based learning, and it has a price. All the work happens at prediction time: every new point must be compared with every stored one, so answers get slower as the data grows.

**Check your understanding:** A k-NN classifier holds a million stored examples. Compared with logistic regression, where does it spend its effort?

- Mostly in training — k-NN does no training at all. It only stores the examples.
- Mostly at prediction time **(correct)** — Each prediction compares the new point with the stored examples, a million distances here. Logistic regression does its work once, in training, and then predicts with one small calculation.
- Equally in both — Training is just storage. All of the computation is in answering questions.

## Choosing k

The number of neighbours is a hyperparameter, and it sets how flexible the model is. This is the lesson of [the generalization chapter](https://thebookofml.com/generalization/) in a new setting.

With $k = 1$ every stored point rules its own little territory, including the odd ones that sit in the wrong crowd. The model gets every known point right and has learned their noise. With a very large $k$, the vote is taken over such a wide area that local detail is lost, and the model underfits.

**Check your understanding:** With k = 1, how many mistakes will the model make on the sixty points it has stored?

- None **(correct)** — Each stored point is its own nearest neighbour, so it is always given its own label. That is memorising, and the figure shows what it costs on new points.
- About as many as on new points — A stored point is never judged by another point when k is 1. It only looks at itself.
- More than with a large k — On stored points a small k can only help. The trouble with k = 1 shows up on new points.

> **Interactive figure: Mistakes against k.** The dark line counts mistakes on the sixty stored points. The orange line counts mistakes on three hundred new ones.
> Try it: slide k from 1 upward. Find where the orange line is lowest, and notice how flat the bottom is.
> (Use it at https://thebookofml.com/nearest-neighbours/)

At $k = 1$ the model makes no mistakes on its own points and 14% on new ones, the largest gap on the chart. Around $k = 25$ mistakes on new points fall to about 9%, and by $k = 41$ they have crept back up to 12%. The bottom of the curve is wide, which is typical: k-NN is forgiving about the exact value. Choose $k$ by cross-validation, and use an odd number with two classes so that votes cannot tie.

## Scale decides who is near

Distance adds up differences across features, so the units of each feature matter a great deal. Here are the forty students from [the logistic regression chapter](https://thebookofml.com/logistic-regression/), with one change: sleep is now recorded in minutes, not hours.

> **Interactive figure: Hours against minutes.** The plot stretches each axis to fill the frame, so it looks balanced. The algorithm sees the raw numbers.
> Try it: with raw numbers, look at which five students are joined to the orange point. Then switch to rescaled and compare.
> (Use it at https://thebookofml.com/nearest-neighbours/)

A difference of two hours of study is 2. A difference of thirty minutes of sleep is 30. With raw numbers the sleep column drowns out the study column, and the "nearest" students are simply those who slept a similar number of minutes, however differently they studied.

The fix is to put every feature on the same footing before measuring distance: subtract its average and divide by its spread. After that, a typical difference counts the same in every feature. This step matters for any method based on distance, and as always the averages and spreads must come from the training data only.

**Note:** Rescaling is not always right. If you know one feature truly matters more, you may want it to count for more. But you should choose that, not let the units choose it for you.

## Too many features

One more weakness is less obvious. k-NN relies on nearby points being similar. In a space with many features, there are no nearby points.

Scatter 200 random points and compare, for one of them, the distance to its nearest neighbour with the distance to its farthest.

> **Interactive figure: When everything is far away.** Each dot is an average over several sets of 200 random points.
> Try it: move the slider from 2 features to 100 and watch the ratio climb.
> (Use it at https://thebookofml.com/nearest-neighbours/)

With 2 features the nearest neighbour is about 3% as far away as the farthest: near and far are very different things. With 100 features it is about 74% as far. Every point is roughly the same distance from every other, and a vote among the "nearest" is hardly better than a vote among random points.

This is the curse of dimensionality. Each added feature multiplies the amount of space the data has to fill, and no realistic dataset can keep up. It is why k-NN works best with a handful of meaningful features, and one reason later chapters put effort into reducing the number of features.

**Check your understanding:** A k-NN model on 5 well-chosen features works well. Someone adds 200 more features that are mostly irrelevant. What is the likely effect?

- It improves, since more information cannot hurt — Every feature contributes to the distance. Irrelevant ones add noise to it and dilute the features that matter.
- It gets worse **(correct)** — The distances become dominated by irrelevant differences, and in 205 dimensions all points are nearly equally far apart. The neighbours stop being meaningfully similar.
- Nothing changes, because k is the same — The same number of neighbours is asked, but they are now a different and less relevant set.

**Common mistake: Leaving in a column that means nothing**

Distance treats every column as if it mattered. A customer number, a row index or a timestamp of when the record was typed in will be compared just like a real feature, and with large values it can dominate the distance entirely. The model then calls two customers similar because their account numbers are close. Before using any distance-based method, go through the columns and remove the ones that are labels for the row and not facts about it.

## In code

```python
from sklearn.model_selection import GridSearchCV
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

# Scaling lives inside the pipeline, so it is learned from the training folds only.
model = make_pipeline(StandardScaler(), KNeighborsClassifier())

# Try odd values of k and keep the one with the best cross-validated accuracy.
search = GridSearchCV(model, {"kneighborsclassifier__n_neighbors": range(1, 42, 2)}, cv=5)
search.fit(X_train, y_train)

print(search.best_params_)              # the chosen k
print(search.score(X_test, y_test))     # accuracy on the held-out test set
```

`fit` here does little more than store the scaled training data. The real work happens inside `score`, when each test point looks for its neighbours.

## Key takeaways

- k-NN classifies a new point by a **vote among the k closest known points**. It has no weights and no training.
- Its boundary can take **any shape**, and adding data changes it immediately.
- **k sets the flexibility**: 1 memorises noise, very large values blur everything. Choose it by cross-validation.
- Distance depends on units, so **rescale features first**.
- With many features all points are far apart, and nearness stops being informative.

## What you should now be able to do

- Classify a new point by hand with k nearest neighbours.
- Say what small and large values of k do to the boundary.
- Explain why features must be rescaled before measuring distance.
- Explain why nearness stops meaning much when there are many features.

## Exercises

### Exercise (by hand)

Five known points: A (1, 1) filled, B (2, 1) filled, C (4, 3) hollow, D (5, 4) hollow and E (3, 3) hollow. Classify the new point (2, 2) with k = 1, with k = 3 and with k = 5.

**Hint:**

Work out the five distances from (2, 2) and sort them. Then let the nearest k vote.

**Solution:**

Distances from (2, 2): B is 1 away. A is $\sqrt{2} \approx 1.41$. E is also $\sqrt{2} \approx 1.41$. C is $\sqrt{5} \approx 2.24$. D is $\sqrt{13} \approx 3.61$.

- **k = 1:** the nearest is B, so **filled**.
- **k = 3:** B, A and E vote: two filled, one hollow. **Filled**.
- **k = 5:** all five vote: two filled, three hollow. **Hollow**.

With k equal to the number of known points, every prediction is simply the more common class. The neighbourhood has grown until it is the whole dataset.

### Exercise (by hand)

Three people, described by income in dollars and age in years: P (30,000 and 25), Q (30,500 and 60) and R (32,000 and 26). Using the raw numbers, who is nearer to P? Now divide incomes by 1,000 and ages by 15, roughly their typical spreads, and answer again.

**Hint:**

Distance is the square root of the summed squared differences. Notice which column dominates before rescaling.

**Solution:**

**Raw numbers.** P to Q: $\sqrt{500^2 + 35^2} \approx 501$. P to R: $\sqrt{2000^2 + 1^2} \approx 2000$. Q looks four times nearer, although Q is 35 years older than P and R is almost the same age.

**Rescaled.** P to Q: the differences are 0.5 and $35 / 15 \approx 2.33$, giving $\sqrt{0.5^2 + 2.33^2} \approx 2.39$. P to R: the differences are 2 and 0.07, giving about 2.00. Now R is nearer.

With raw numbers the age column was invisible, only because dollars are small units and years are large ones.

### Exercise (think)

Why does k-NN with k = 1 always make zero mistakes on the points it has stored? Why is that not good news?

**Hint:**

Ask which stored point is nearest to a stored point.

**Solution:**

Ask it about a stored point and the nearest stored point is that point itself, at distance zero. It answers with that point's own label, which is correct by definition.

It is not good news because it says nothing about new points. A stored point that sits in the wrong crowd, through noise or a labelling mistake, gets its own little territory, and new points landing there will be misclassified. Zero training error with a large gap to the error on new data is the signature of overfitting.

### Exercise (in code)

Write k-NN in NumPy: a function that takes the known points, their labels, a new point and k, and returns the predicted label. Check it against your answers to the first exercise.

**Hint:**

`np.argsort(distances)[:k]` gives the positions of the k nearest points.

**Solution:**

```python
import numpy as np

def knn_predict(X, y, new, k):
    distances = np.sqrt(((X - new) ** 2).sum(axis=1))   # one distance per known point
    nearest = np.argsort(distances)[:k]                 # positions of the k smallest
    return np.bincount(y[nearest]).argmax()             # the most common label among them

X = np.array([[1, 1], [2, 1], [4, 3], [5, 4], [3, 3]])
y = np.array([1, 1, 0, 0, 0])                           # 1 = filled, 0 = hollow

for k in (1, 3, 5):
    print(k, knn_predict(X, y, np.array([2, 2]), k))    # 1, 1, 0
```

There is no training step. The whole method is the three lines inside the function.

### Exercise (with the figure)

In the figure "Mistakes against k", read the two curves at k = 1, at about k = 25 and at k = 41. At which of the three is the gap between the curves largest, and what does the gap tell you?

**Hint:**

The dark curve is mistakes on the stored points, the orange one on new points.

**Solution:**

At k = 1 the model makes no mistakes on its stored points and 14% on new ones. Around k = 25 the error on new points is lowest, about 9%. By k = 41 it has crept back up to about 12%.

The gap is largest at k = 1. A big gap between error on stored and new points is the sign of overfitting: the model is treating noise in its own data as if it were pattern. At large k the two curves are close and both are getting worse, which is underfitting.

## Going further

### Predicting numbers

The same idea does regression. Find the k nearest known points and average their values instead of voting. The prediction is a staircase rather than a smooth curve, but it follows any shape without being told what shape to expect.

### Weighted votes

A neighbour right beside the new point arguably deserves more say than one at the edge of the group. Weighting each vote by one over its distance does this, and makes the choice of k less critical.

### Making it fast

Comparing against every stored point is too slow for large datasets. Tree structures and approximate search methods find the nearest neighbours without checking them all. The same machinery is what lets modern systems search millions of documents or images by similarity.

## References

- G. James, D. Witten, T. Hastie and R. Tibshirani, *An Introduction to Statistical Learning*, sections 2.2 and 4.7. Free at [statlearning.com](https://www.statlearning.com).
- A. Karpathy and others, *CS231n notes: Image classification*, [cs231n.github.io/classification](https://cs231n.github.io/classification/).
- scikit-learn user guide, [Nearest Neighbors](https://scikit-learn.org/stable/modules/neighbors.html).

## Next

k-NN lets the data answer directly, with no model in between. The next classifier does the opposite. It builds a small model of how each class produces its data, and then reasons backwards from what it sees to which class is the likelier cause.
