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 , and the method is
A vote among the closest points
- 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
“Closest” needs a definition. The usual one is
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.
What k-NN would say everywhere
- Shaded: would be called filled
- Unshaded: would be called hollow
- Neighbours asked (k)
- 1
- Known points
- 60
- Right on 300 new points
- 86.0%
Click or tap anywhere on the plot to add a point of the selected kind.
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
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
With 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 , the vote is taken over such a wide area that local detail is lost, and the model underfits.
With k = 1, how many mistakes will the model make on the sixty points it has stored?
Mistakes against k
- 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%
At the model makes no mistakes on its own points and 14% on new ones, the largest gap on the chart. Around mistakes on new points fall to about 9%, and by 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 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
Hours against minutes
- 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
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.
When everything is far away
- Features
- 2
- Nearest neighbour is
- 3% as far as the farthest
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
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.
- 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.
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 . E is also . C is . D is .
- 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.
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: . P to R: . 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 , giving . 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.
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.
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, 0There is no training step. The whole method is the three lines inside the function.
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
- G. James, D. Witten, T. Hastie and R. Tibshirani, An Introduction to Statistical Learning, sections 2.2 and 4.7. Free at statlearning.com.
- A. Karpathy and others, CS231n notes: Image classification, cs231n.github.io/classification.
- scikit-learn user guide, Nearest Neighbors.