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

k = 3ABCDEFNew rowClass redClass blue
A new row (triangle) and six labelled rows. The dashed circle holds its three nearest neighbours: two red and one blue, so with k = 3 the prediction is red.

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 pp columns,

d(x,x′)=∑j=1p(xj−xj′)2d(x, x') = \sqrt{\sum_{j=1}^{p} (x_j - x'_j)^2}

The Manhattan distance sums absolute differences instead, ∑j∣xj−xj′∣\sum_j |x_j - x'_j|, and both are special cases of the Minkowski distance. For a query row, find the kk closest training rows Nk(x)N_k(x). The class prediction is the most common label among them. For regression it is the average:

y^(x)=1k∑i∈Nk(x)yi\hat{y}(x) = \frac{1}{k}\sum_{i \in N_k(x)} y_i

With distance weighting, closer neighbours count more, for example with weight 1/d1/d, 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):

RowPositionClassDistance to (3, 3)
B(2, 3)red1.00
F(2, 2.5)red1.12
C(4, 4)blue1.41
E(3, 5)blue2.00
D(5, 2)blue2.24
A(1, 1)red2.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):

kWithout scalingWith a standard scaler
10.6800.704
50.6980.728
150.7520.749
310.7420.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

  1. Open Pipelines and pick a classification pipeline and, in the Columns part, choose Standardise for its numeric columns.
  2. Open the Models part and add K Neighbors Classifier in Automatic mode.
  3. Add it again, switch that card to Manual and set n_neighbors to 25.
  4. Click Train and compare the cross-validated scores of the two cards.
Open in mlflow

Read in the docs

Check your understanding

  1. 1. What does k-nearest neighbours do when it trains?
  2. 2. k is set to 1. What is the typical risk?
  3. 3. One column is income in dollars (tens of thousands) and another is age in years. Without scaling, which column mostly decides who is nearest?