Skip to content

MLDay 15 of 50Supervised and Unsupervised Learning

Predict by Distance

k-Nearest Neighbours

7 min read

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.

  1. Measure. Work out the distance from the new row to every training row: one number for how different two rows are.
  2. Pick. Keep the kk closest rows, its neighbours. You choose kk before training, so it's a hyperparameter.
  3. 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.

kk sets how local the answer is. With k=1k = 1, one odd customer decides for everyone near it, so the boundary between the classes is jumpy. With a huge kk, 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 k=3k = 3:

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:

d(a,b)=∑i=1m(ai−bi)2d(\mathbf{a}, \mathbf{b}) = \sqrt{\sum_{i=1}^{m} (a_i - b_i)^2}
Symbol Meaning
a,b\mathbf{a}, \mathbf{b} two rows, each a list of feature values
ai,bia_i, b_i their values for feature ii
mm the number of features
dd the distance; 0 means the rows are identical

Worked: from (0, 0) to (3, 4), d=32+42=25=5d = \sqrt{3^2 + 4^2} = \sqrt{25} = 5. For customer B in raw units, d=102+32=109≈10.4d = \sqrt{10^2 + 3^2} = \sqrt{109} \approx 10.4. 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).

02004006008000246Days as a customerSupport tickets last month(40, 0), stayed(130, 5), cancelled(210, 1), stayed(260, 4), cancelled(330, 0), stayed(380, 6), cancelled(450, 2), stayed(500, 5), cancelled(560, 1), stayed(610, 4), cancelled(690, 0), stayed(720, 3), stayed(780, 5), cancelled(840, 2), stayed(880, 6), cancelled(300, 2), cancelledtest point (100, 1), stayed, misclassifiedtest point (180, 4), cancelled, misclassifiedtest point (290, 2), stayed, misclassifiedtest point (420, 5), cancelled, misclassifiedtest point (540, 0), stayedtest point (650, 6), cancelledtest point (800, 1), stayed, misclassifiedtest point (870, 4), cancelled
Distances use raw units, so the axis with the bigger numbers decides who is near.

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 kk to 3 to erase the island around the one odd customer (300 days, 2 tickets, cancelled) and reach 100%. At k=15k = 15 the regions blur and accuracy slips back to 88%.

In code

scikit-learn's KNeighborsClassifier does the vote, with k=5k = 5 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 kk.

# 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 kk: scaling alone lifts test accuracy from 0.74 to 0.88. With k=1k = 1 the model scores 0.99 on its own training rows, since each row is its own nearest neighbour. That says nothing about new customers. k=25k = 25 does best here, and k=300k = 300 starts to blur. Choose kk 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 mm 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.

Next · Day 16 · 8 minSupport Vector Machines← Previous: Day 14 · Prepare Messy Tabular Data
Not tapped yet