k-nearest neighbours
Predict a new row from the rows most similar to it, and learn why scaling and the choice of k decide everything.
Lesson 31 of 6613 minIntermediate
You will learn to
- Explain how k-nearest neighbours predicts by looking at the closest training rows
- Describe how k and the distance weighting move the model between underfitting and overfitting
- Explain why the algorithm needs scaled inputs and where it struggles
Before this lesson
Intuition
When you want to know whether a house is expensive, you do not need a formula. You look at the prices of similar houses nearby. k-nearest neighbours (kNN) works the same way. To predict a new row, it finds the k training rows most similar to it and lets them decide: the majority class for classification, the average value for regression.
There is no training in the usual sense. The algorithm keeps the training rows and does its work when you ask for a prediction. Everything depends on two choices: what "similar" means (the distance) and how many neighbours to ask (k).
A small k follows the data closely, so it can chase noise. A large k averages over a wide area, so it can smooth away real structure. Choosing k is the bias-variance trade-off in its clearest form.
Picture it
The circle shows the neighbourhood for k = 3. If you widen k to 5, more blue points enter and the answer changes. The prediction depends on how far you look, and that is the parameter you tune.
The math
The usual distance is the Euclidean distance. For two rows with columns,
The Manhattan distance sums absolute differences instead, , and both are special cases of the Minkowski distance. For a query row, find the closest training rows . The class prediction is the most common label among them. For regression it is the average:
With distance weighting, closer neighbours count more, for example with weight , so a very close row can outvote several distant ones.
Distances become less informative as the number of columns grows: in many dimensions, almost all rows are far from each other and nearly equally far. This "curse of dimensionality" is why kNN works best with a modest number of meaningful columns.
Worked example
Six labelled rows with two features, and a new row at (3, 3):
| Row | Position | Class | Distance to (3, 3) |
|---|---|---|---|
| B | (2, 3) | red | 1.00 |
| F | (2, 2.5) | red | 1.12 |
| C | (4, 4) | blue | 1.41 |
| E | (3, 5) | blue | 2.00 |
| D | (5, 2) | blue | 2.24 |
| A | (1, 1) | red | 2.83 |
- k = 1: the nearest row is B (red), so the prediction is red.
- k = 3: B, F and C are the closest: red, red, blue, so the prediction is red.
- k = 5: add E and D: red, red, blue, blue, blue, so the prediction flips to blue.
The same row gets different answers depending on k, which is why k is chosen by cross-validation.
Now scaling. A new customer is 30 years old with an income of 50,000. Row B is 31 years old with an income of 52,000. Row C is 60 years old with an income of 50,500. In raw units, the distance to B is about 2,000 and to C about 501, so C looks much closer even though it is 30 years older. Suppose the standard deviations are 10 years and 10,000 in income (illustrative). After dividing each difference by its standard deviation, the distance to B is 0.22 and to C is 3.0: B is the real neighbour.
A computed comparison on a sample dataset with 768 rows, 5-fold stratified cross-validation in scikit-learn (seed 42, accuracy):
| k | Without scaling | With a standard scaler |
|---|---|---|
| 1 | 0.680 | 0.704 |
| 5 | 0.698 | 0.728 |
| 15 | 0.752 | 0.749 |
| 31 | 0.742 | 0.763 |
For a small k the score is lower and scaling matters most. Larger k smooths the noise, and the best value on this dataset is on the large side.
How mlflow does it
The algorithms are K Neighbors Classifier and K Neighbors Regressor (knn). The tunable parameters are n_neighbors (searched from 1 to 50), weights (uniform, or distance) and metric (minkowski, euclidean or manhattan). Add a scaler step before it and encode categorical columns, since distances need numbers. Each parameter has a tooltip describing what raising or lowering it does. The prediction time grows with the size of the training set, which matters for deployments that answer many requests.
Common mistakes
- Not scaling. The column with the largest numbers decides the neighbours. Add a scaler step and fit it inside each fold.
- Keeping k at 1 or at the default without checking. Tune k by cross-validation, and prefer odd values for two-class problems to avoid ties.
- Using many irrelevant columns. Every column adds to the distance, so noisy columns blur the neighbourhood. Select features or reduce dimensions first.
- Using it on very large tables for real-time predictions. Each prediction searches the stored rows. Measure the latency before choosing it.
- Ignoring class imbalance. With a rare class, most neighbours belong to the majority class. Use distance weighting or a different algorithm and check the recall of the rare class.
Try it in mlflow
Change k and see the score move
- Open Pipelines and pick a classification pipeline and, in the Columns part, choose Standardise for its numeric columns.
- Open the Models part and add K Neighbors Classifier in Automatic mode.
- Add it again, switch that card to Manual and set n_neighbors to 25.
- Click Train and compare the cross-validated scores of the two cards.