Chapter 8 // Classification

Nearest Neighbours.

Can you classify something without ever fitting a model?

Reading time
16 min
Data
Read first
Generalization

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 kk, and the method is , or k-NN.

Figure

A vote among the closest points

Filled kind at (5.64, 1.45)Filled kind at (3.58, 3.48)Filled kind at (4.8, 4.44)Filled kind at (9.57, 3.32)Filled kind at (7, 1.18)Filled kind at (3.57, 3.62)Filled kind at (6.68, 5.38)Filled kind at (7.43, 0.87)Filled kind at (7.7, 2.6)Filled kind at (9.69, 2.64)Filled kind at (9.03, 5.39)Filled kind at (8.5, 4.31)Filled kind at (7.48, 0.2)Filled kind at (8.21, 3.47)Filled kind at (5.41, 0.62)Filled kind at (5.29, 1.79)Filled kind at (7.14, 0.35)Filled kind at (4.23, 2.79)Filled kind at (7.49, 2.73)Filled kind at (3.76, 3.11)Filled kind at (9.07, 4.87)Filled kind at (6.71, 1.58)Filled kind at (7.74, 1.69)Filled kind at (9.77, 2.05)Filled kind at (9.63, 5.26)Filled kind at (4.38, 0.2)Filled kind at (6.07, 0.2)Filled kind at (8.49, 1.75)Filled kind at (6.1, 4.35)Filled kind at (4.41, 4.1)Hollow kind at (8.9, 3.6)Hollow kind at (5.69, 7.83)Hollow kind at (5.77, 8.54)Hollow kind at (2.76, 8.31)Hollow kind at (6.9, 7.92)Hollow kind at (6.04, 9.8)Hollow kind at (1.78, 7.51)Hollow kind at (0.48, 5.18)Hollow kind at (1.98, 7.35)Hollow kind at (7.01, 9.8)Hollow kind at (1.97, 7.53)Hollow kind at (4.23, 8.94)Hollow kind at (3.6, 8.5)Hollow kind at (4.38, 6.87)Hollow kind at (6.75, 6.95)Hollow kind at (1.83, 7.3)Hollow kind at (7.1, 5.52)Hollow kind at (3.31, 8.33)Hollow kind at (3.17, 7.27)Hollow kind at (0.98, 7.37)Hollow kind at (6.76, 8.7)Hollow kind at (4.4, 7.69)Hollow kind at (2.21, 5.63)Hollow kind at (4.48, 6.96)Hollow kind at (1.35, 6.71)Hollow kind at (8.28, 4.22)Hollow kind at (3.12, 5.01)Hollow kind at (4.79, 8.24)Hollow kind at (2.09, 5.3)Hollow kind at (1, 8.83)
  • Known: filled kind
  • Known: hollow kind
  • New point and its neighbours
Neighbours asked (k)
5
Votes
4 filled · 1 hollow
The new point is called
filled
5
Drag the orange point.
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.

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

distance(a,b)=(a1−b1)2+(a2−b2)2+⋯+(ad−bd)2\text{distance}(a, b) = \sqrt{(a_1 - b_1)^2 + (a_2 - b_2)^2 + \dots + (a_d - b_d)^2}

distance = square root of the summed squared differences, feature by feature

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.

Figure

What k-NN would say everywhere

5.64, 1.453.58, 3.484.8, 4.449.57, 3.327, 1.183.57, 3.626.68, 5.387.43, 0.877.7, 2.69.69, 2.649.03, 5.398.5, 4.317.48, 0.28.21, 3.475.41, 0.625.29, 1.797.14, 0.354.23, 2.797.49, 2.733.76, 3.119.07, 4.876.71, 1.587.74, 1.699.77, 2.059.63, 5.264.38, 0.26.07, 0.28.49, 1.756.1, 4.354.41, 4.18.9, 3.65.69, 7.835.77, 8.542.76, 8.316.9, 7.926.04, 9.81.78, 7.510.48, 5.181.98, 7.357.01, 9.81.97, 7.534.23, 8.943.6, 8.54.38, 6.876.75, 6.951.83, 7.37.1, 5.523.31, 8.333.17, 7.270.98, 7.376.76, 8.74.4, 7.692.21, 5.634.48, 6.961.35, 6.718.28, 4.223.12, 5.014.79, 8.242.09, 5.31, 8.83
  • Shaded: would be called filled
  • Unshaded: would be called hollow
Neighbours asked (k)
1
Known points
60
Right on 300 new points
86.0%
1

Click or tap anywhere on the plot to add a point of the selected kind.

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.

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 , 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.

Checkpoint

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

Choosing k

The number of neighbours is a hyperparameter, and it sets how flexible the model is. This is the lesson of in a new setting.

With k=1k = 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 kk, the vote is taken over such a wide area that local detail is lost, and the model underfits.

Predict firstCommit to a guess, then use the figure below to check it.

With k = 1, how many mistakes will the model make on the sixty points it has stored?

Figure

Mistakes against k

1, 01, 14new pointsknown points
  • Mistakes on the 60 known points
  • Mistakes on 300 new points
k
1
Mistakes on known points
0.0%
Mistakes on new points
14.0%
1
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.

At k=1k = 1 the model makes no mistakes on its own points and 14% on new ones, the largest gap on the chart. Around k=25k = 25 mistakes on new points fall to about 9%, and by k=41k = 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 kk 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 , with one change: sleep is now recorded in minutes, not hours.

Figure

Hours against minutes

5.5 h study, 474 min sleep, passed5.3 h study, 498.00000000000006 min sleep, passed6 h study, 432 min sleep, passed5.6 h study, 552 min sleep, passed5.9 h study, 491.99999999999994 min sleep, passed2.3 h study, 528 min sleep, passed7.2 h study, 252 min sleep, passed8.6 h study, 558 min sleep, passed5.1 h study, 288 min sleep, passed7.9 h study, 245.99999999999997 min sleep, passed6.2 h study, 360 min sleep, passed6.4 h study, 240 min sleep, passed4.8 h study, 528 min sleep, passed6.4 h study, 456 min sleep, passed3.8 h study, 480 min sleep, passed3.1 h study, 240 min sleep, failed1.9 h study, 216 min sleep, failed3.4 h study, 396 min sleep, failed3.2 h study, 534 min sleep, failed2.6 h study, 258 min sleep, failed2.9 h study, 318 min sleep, failed3.6 h study, 300 min sleep, failed2 h study, 216 min sleep, failed1.8 h study, 245.99999999999997 min sleep, failed1.8 h study, 348 min sleep, failed1.1 h study, 474 min sleep, failed4.2 h study, 234 min sleep, failed0.8 h study, 426 min sleep, failed4.3 h study, 276 min sleep, failed1.1 h study, 300 min sleep, failed4.9 h study, 318 min sleep, failed5.1 h study, 288 min sleep, failed1 h study, 342 min sleep, failed2.1 h study, 468 min sleep, failed1.7 h study, 420 min sleep, failed2.2 h study, 282 min sleep, failed1.5 h study, 240 min sleep, failed1.1 h study, 210 min sleep, failed3.4 h study, 354 min sleep, failed1.3 h study, 366 min sleep, failed
  • Passed (filled)
  • Failed (hollow)
  • New student and the 5 "nearest"
Farthest neighbour, in study hours
6.0 h
Farthest neighbour, in sleep
24 min
Neighbours who passed
0 of 5
Prediction
fail
Drag the orange point.
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.

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.

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.

Figure

When everything is far away

1, 02, 0.033, 0.075, 0.218, 0.312, 0.420, 0.4930, 0.5750, 0.6675, 0.71100, 0.742, 0.03
Features
2
Nearest neighbour is
3% as far as the farthest
2
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.

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 . 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.

Checkpoint

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?

In code

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.
You can now
  • 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

Try each one before opening its solution. Getting stuck for a few minutes is where most of the learning happens.

Exerciseby 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 2≈1.41\sqrt{2} \approx 1.41. E is also 2≈1.41\sqrt{2} \approx 1.41. C is 5≈2.24\sqrt{5} \approx 2.24. D is 13≈3.61\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.

Exerciseby 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: 5002+352≈501\sqrt{500^2 + 35^2} \approx 501. P to R: 20002+12≈2000\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≈2.3335 / 15 \approx 2.33, giving 0.52+2.332≈2.39\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.

Exercisethink

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.

Exercisein 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
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.

Exercisewith 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 and further reading

Last updated Spotted a mistake? Suggest an editWhat changed

In this chapter
  1. Top of the chapter
  2. 8.1Ask the neighbours
  3. 8.2The whole map
  4. 8.3Choosing k
  5. 8.4Scale decides who is near
  6. 8.5Too many features
  7. 8.6In code
  8. Exercises
Search

    The Book of Machine Learning
    Search
    Reading settings
    Text size
    Colours

    Saved in this browser only.

    Keyboard shortcuts
    /
    Search the book
    ← →
    Previous and next chapter
    g
    Glossary
    c
    Table of contents
    e
    Jump to the exercises
    t
    Reading settings
    ?
    Show this list
    Esc
    Close a window or pop-in