MLDay 15 of 50Supervised and Unsupervised Learning
Predict by Distance
k-Nearest Neighbours
A streaming service wants to know which customers will cancel next month. You could fit weights to a loss. Or you could find the past customers most like this one and see what they did.
The idea
k-nearest neighbours (k-NN) keeps every training row and learns nothing up front. To predict a new row, it takes three steps.
- Measure. Work out the distance from the new row to every training row: one number for how different two rows are.
- Pick. Keep the closest rows, its neighbours. You choose before training, so it's a hyperparameter.
- Vote. For a class, the neighbours vote and the majority wins. For a number, such as a price, k-NN averages the neighbours' values instead.
sets how local the answer is. With , one odd customer decides for everyone near it, so the boundary between the classes is jumpy. With a huge , the vote spans most of the data, so the boundary blurs.
Scale decides who is near. Distance adds up the gaps in each feature's own units. A gap of 100 days counts 100 times as much as a gap of one support ticket, so the feature with the biggest numbers decides alone. Standardizing each feature to a mean of 0 and a spread of 1, as in D09, lets every feature count.
Too many features hurt too. With hundreds of features, every row is far from every other one. The nearest row is barely nearer than the farthest, so "similar" stops meaning much. This is the curse of dimensionality, and the code below measures it.
A tiny example
A new customer joined 200 days ago and filed 4 support tickets last month. Here are four past customers, with :
| Customer | Days | Tickets | What they did | Distance, raw | Distance, days in 100s |
|---|---|---|---|---|---|
| A | 200 | 0 | stayed | 4.0 | 4.0 |
| B | 210 | 1 | stayed | 10.4 | 3.0 |
| C | 230 | 4 | cancelled | 30.0 | 0.3 |
| D | 160 | 4 | cancelled | 40.0 | 0.4 |
In raw units the three nearest are A, B and C. Two stayed, so k-NN predicts "stays". Yet A and B filed almost no tickets; only their join dates match.
Now count time in hundreds of days, so 100 days weighs the same as one ticket. The nearest are C, D and B. Two cancelled, so the answer flips to "cancels". The data didn't change, only the units.
The formula
The usual distance is the straight-line, or Euclidean, distance:
| Symbol | Meaning |
|---|---|
| two rows, each a list of feature values | |
| their values for feature | |
| the number of features | |
| the distance; 0 means the rows are identical |
Worked: from (0, 0) to (3, 4), . For customer B in raw units, . The 10-day gap supplies 100 of the 109.
Try it
Who cancels? Ask the nearest customers
Blue: cancelled. Yellow: stayed. Each spot is shaded by the class most of its k nearest training points have. Change k and watch the regions go from jumpy (small k) to smooth (large k).
k = 1training accuracy 100%test accuracy 38%
Circles are training points; squares are test points, which never vote. A red outline means the vote gets it wrong. Each training point counts itself as a neighbour, so k = 1 looks perfect on them: trust the test score instead.
In raw units the regions are vertical stripes, because only the days count, and test accuracy is 38%. Press Standardize the axes: the split turns sideways, along tickets, and accuracy jumps to 88%. Raise to 3 to erase the island around the one odd customer (300 days, 2 tickets, cancelled) and reach 100%. At the regions blur and accuracy slips back to 88%.
In code
scikit-learn's KNeighborsClassifier does the vote, with by default. This makes 1,000 seeded
customers, where newer customers give up after fewer tickets. It scores k-NN with and without a
StandardScaler in a pipeline (D11), then tries three
values of .
# script_id: day_015_k_nearest_neighbours/churn
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(42)
days = rng.integers(0, 1000, 1000) # days as a customer
tickets = rng.integers(0, 7, 1000) # support tickets last month
p_cancel = 1 / (1 + np.exp(-2 * (tickets - 1 - days / 200))) # newer customers give up sooner
cancelled = (rng.uniform(size=1000) < p_cancel).astype(int)
X = np.column_stack([days, tickets])
X_tr, X_te, y_tr, y_te = train_test_split(X, cancelled, test_size=0.25, random_state=42)
raw = KNeighborsClassifier().fit(X_tr, y_tr)
scaled = make_pipeline(StandardScaler(), KNeighborsClassifier()).fit(X_tr, y_tr)
print(f"raw units: test accuracy {raw.score(X_te, y_te):.2f}")
print(f"standardized: test accuracy {scaled.score(X_te, y_te):.2f}")
for k in [1, 25, 300]:
model = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=k)).fit(X_tr, y_tr)
print(f"k = {k:3} train {model.score(X_tr, y_tr):.2f} test {model.score(X_te, y_te):.2f}")
raw units: test accuracy 0.74
standardized: test accuracy 0.88
k = 1 train 0.99 test 0.88
k = 25 train 0.90 test 0.91
k = 300 train 0.90 test 0.87
Same data, same : scaling alone lifts test accuracy from 0.74 to 0.88. With the model scores 0.99 on its own training rows, since each row is its own nearest neighbour. That says nothing about new customers. does best here, and starts to blur. Choose by cross-validation, as D11 chose α.
Now the curse of dimensionality. This places 1,000 random rows and one query row in a space with features, then compares the nearest and farthest distances.
# script_id: day_015_k_nearest_neighbours/curse
import numpy as np
rng = np.random.default_rng(42)
for m in [2, 10, 100, 1000]:
rows = rng.uniform(size=(1000, m)) # 1,000 random rows, m features each
query = rng.uniform(size=m)
d = np.sqrt(((rows - query) ** 2).sum(axis=1))
print(f"{m:4} features: nearest {d.min():5.2f}, farthest {d.max():5.2f}, ratio {d.min() / d.max():.2f}")
2 features: nearest 0.01, farthest 0.96, ratio 0.01
10 features: nearest 0.54, farthest 2.15, ratio 0.25
100 features: nearest 3.45, farthest 4.85, ratio 0.71
1000 features: nearest 12.19, farthest 13.62, ratio 0.89
With 2 features, the nearest row is over 100 times closer than the farthest. With 1,000, it is only about 10% closer, so its vote means little. k-NN works best on a few features that matter.
Quick check
Quick check
1. Flats have floor area (30–300 m²) and bedrooms (1–5). Without scaling, which feature decides who is near?
2. With k = 1, k-NN scores 0.99 on its training rows but 0.88 on test rows. Why?
3. Why does k-NN struggle with 1,000 features?
Next
k-NN puts the boundary wherever the votes fall; D16 picks the boundary with the widest gap, or margin, between the classes.