Lesson 8 · Other ways to draw a boundary
Nearest neighbours
The problem
Back to the pizza shop's rush-hour data. Each delivery has two features: the distance in km and the time it was sent. Most of the evening, trips over about 6 km run late. Around 19:00 the roads jam, and even short trips run late.
Logistic regression draws one straight line through this picture, and it gets only 76% of new deliveries right. The line can't follow the dip at 19:00.
An experienced dispatcher would do something simpler. Faced with a new order, they'd remember similar past orders: "3 km, sent around 8 pm. The last few like that were mostly late." No formula, no line. Look at the most similar past cases, and go with what usually happened.
This lesson turns that habit into a model.
Ask the neighbours
Here's the recipe for a new delivery:
- Measure how far it is from every past delivery.
- Keep the closest. These are its neighbours.
- Let them vote. The new delivery gets the most common label among them.
This is k-nearest neighbours, or kNN. The number is a hyperparameter: you choose it.
"How far" means straight-line distance between the feature vectors, the length of their difference. For two deliveries with distances km, sent at hours :
Here one km counts the same as one hour. That works on this data because both features span a few units. The section on scaling shows what goes wrong when they don't.
Drag the new delivery (the filled dot) around the picture.
3.00 km at 20:00: 3 late · 2 on time → the vote says late (P(late) = 0.60)
○ on time · × late · dashed ring: as far as the k-th neighbour
Things to notice:
- The answer is a local majority. In the middle of a crowd of × the vote is unanimous. Near the edge between the two groups it's close, like 3 to 2.
- The ring is an oval, not a circle. The two axes are drawn at different scales, but the distance treats one hour like one km.
- With k = 1, one delivery decides. If that delivery's label was a fluke, the prediction is too.
Worked example
One vote, by hand
A new delivery: 3 km, sent at 20:00 (hour 20.0). Take .
Predict first
A new delivery: 5 km, sent at 20:30. Its nearest neighbour (gap 0.11) was late. The next four were on time, on time, on time and late. What do k = 1 and k = 5 predict?
To predict a number instead of a class, average the neighbours' labels. A new delivery whose 5 neighbours took 20, 22, 25, 25 and 28 minutes is predicted to take 24 minutes. That's kNN regression.
A model that keeps all its data
Logistic regression boils 200 deliveries down to three numbers: two weights and an intercept. After training, it could throw the data away.
kNN does the opposite. Training is nothing but storing the 200 deliveries. All the work happens at prediction time, when it measures the gap to every one of them.
A model that keeps its training data, or one whose size grows with the data, is a non-parametric model. "Non-parametric" doesn't mean it has no settings: is still there. It means there's no fixed set of parameters that summarises the data.
This has a cost and a benefit:
- Cost: predicting is slow and needs a lot of memory. With a million past deliveries, each new prediction measures a million gaps.
- Benefit: the boundary can take any shape the data has. No one had to tell kNN that the rush hour makes a dip.
Choosing k
Now draw the whole decision boundary: ask the neighbours at every point of the picture, and colour it by the vote.
k = 1 · training 100.0% · validation 87.5%
Predict first
With k = 1, what's the accuracy on the training deliveries themselves?
Things to notice:
- k = 1 is jagged. The boundary wraps around single deliveries, including the 5% whose labels were flipped at random. Training accuracy is 100%.
- k = 5 follows the dip and ignores most flukes. Validation accuracy is 95%, the best of any here.
- k = 25 is smooth, and starts to cut the corners off the dip. Validation accuracy falls to 87.5%.
- A huge k flattens everything. At the dip is mostly gone (82%). At , every prediction would be the overall majority.
This is the bias–variance trade-off again. Small means each prediction rests on a few deliveries, so it changes a lot with the luck of the data: high variance. Large averages over a wide area, so it blurs real detail: high bias. works like the polynomial degree in the generalisation lesson, in reverse: smaller is a more flexible model.
Pick the usual way: with a validation set or cross-validation, never with training accuracy. Odd values of avoid tied votes when there are two classes.
Scaling matters
The rush-hour data was kind: km and hours both span a few units. Real tables are rarely like that.
Take the 300 deliveries from earlier lessons. Use two features: distance in metres (500 to 5,900) and the traffic level (0 for clear to 3 for jammed). Both affect whether a delivery takes over 30 minutes. In the distance formula, a gap of one traffic level counts as 1. A gap of 100 metres counts as 100.
3,000 m, traffic 3: the 5 neighbours have traffic 2, 1, 1, 1, 0 → 1 late, 4 on time → on time
Validation accuracy with 5 neighbours: 71%
○ on time · × late · each traffic row is spread out a little so dots don't overlap
Things to notice:
- Unscaled, the neighbours form a vertical band. They're all at about the same distance, whatever their traffic. The traffic feature is almost ignored.
- A 3,000 m trip in jammed traffic gets neighbours with traffic 2, 1, 1, 1 and 0, all at exactly 3.0 km. Four were on time, so kNN says on time.
- Standardised, the neighbours share its traffic level. All five are at traffic 3, within a few hundred metres, and all were late.
- Validation accuracy rises from 71% to 80% with the same .
Worked example
Two neighbours, before and after scaling
The new delivery: 3,000 m, traffic 3. Candidate A: 3,000 m, traffic 0. Candidate B: 2,900 m, traffic 3.
Putting features on comparable scales before measuring distances is feature scaling. The usual way is standardising: for each feature, subtract its mean and divide by its standard deviation:
After this, every feature has mean 0 and standard deviation 1. A gap of 1 means "one typical spread" on any feature. Another option is min–max scaling, which squeezes each feature into the range 0 to 1.
Two rules:
- Fit the scaling on the training rows only. Then apply the same mean and standard deviation to validation, test and new rows. Using the validation rows to set the scale would let them leak into training (data leakage).
- Scaling doesn't decide what matters. It makes features count equally. If one feature is mostly noise, it now has as much say as the useful ones. Choosing features is still your job.
Scaling matters for any method built on distances or on the size of weights. That includes kNN, support vector machines, k-means, regularised linear models, and gradient descent's speed. It doesn't matter for decision trees, whose questions compare one feature at a time with a threshold.
DeeperThe curse of dimensionalityIn 1,000 dimensions, every point is about the same distance from every other, and 'nearest' stops meaning much. · 4 min
kNN rests on one idea: nearby points have similar labels. That works when "nearby" means something. With many features, it stops meaning much.
Scatter 500 points at random in a square, then in cubes in more and more dimensions. Measure the distance from one more random point to each of them, and compare the nearest with the farthest.
With 2 features, the nearest point is 2% as far away as the farthest.
- With 2 features, distances spread from almost 0 to the farthest. The nearest point is only 2% as far away as the farthest. "Nearest" is a real distinction.
- With 100 features, every distance is bunched near the top. The nearest point is about 70% as far as the farthest.
- With 1,000 features, it's about 90%. Every point is roughly equally far from every other.
Why? The squared distance is a sum of one term per feature. With many features, that sum behaves like any large sum of random terms: it lands close to its average every time. It's the same reason averages of many draws are steady. So all distances end up about the same.
This is the curse of dimensionality. A second side of it: to keep the same density of examples, you need more data for every feature you add. Ten points cover a line well. To space points as closely in 10 dimensions would take of them.
Real data is kinder than random cubes, because its features are related and it lies near a lower-dimensional shape. That's why kNN still works on images or text, after they're turned into good features. Methods for finding those shapes come later in the course, with principal component analysis.
DigressionFinding neighbours fastMeasuring every gap doesn't scale to millions of rows. Trees and approximate search do. · 2 min
Brute force measures the gap to every stored example: with examples and features, about steps per prediction. For 200 deliveries that's nothing. For 100 million product photos, it's far too slow.
Two families of tricks help:
- Space-partitioning trees (k-d trees, ball trees) split the data into nested boxes or balls. A search can skip whole boxes that are too far away to hold a nearer point. They work well in a few dimensions. In many dimensions they lose their edge, because of the curse above. scikit-learn picks brute force or a tree for you (
algorithm="auto"). - Approximate nearest-neighbour search gives up a guarantee to gain speed: it finds points that are almost surely among the nearest. This is how search engines and recommender systems look up similar items among millions of embeddings. The BERT and encoder models course uses it for retrieval.
DigressionWhere nearest neighbours come fromA 1951 report for the US Air Force, and a 1967 result about how good one neighbour can be. · 1 min
Evelyn Fix and Joseph Hodges described the nearest-neighbour rule in 1951. It appeared in a technical report for the US Air Force School of Aviation Medicine, on "nonparametric discrimination". They showed that, as the data grows and grows more slowly, the rule's predictions approach the best possible ones.
In 1967, Thomas Cover and Peter Hart published "Nearest neighbor pattern classification". They proved that, with enough data, even the one-neighbour rule makes at most twice as many mistakes as the best possible classifier. That's a strong promise for a method with no training at all, though "enough data" can mean a great deal of it.
In scikit-learn
KNeighborsClassifier is an estimator like the others. Its .fit stores the data, and .kneighbors shows the neighbours it found:
knn = KNeighborsClassifier(n_neighbors=5).fit(x_train, y_train) # "fit" only stores the data
query = np.array([[3.0, 20.0]]) # a 3 km trip sent at 20:00
distances, indices = knn.kneighbors(query) # the 5 nearest training rows, nearest first
for d, i in zip(distances[0], indices[0]):
km, hour = x_train[i]
print(f"row {i:3} {km:.2f} km at {hour:.2f}h distance {d:.2f} {'late' if y_train[i] else 'on time'}")
print("P(late) =", knn.predict_proba(query)[0, 1], "->", "late" if knn.predict(query)[0] else "on time")row 22 2.97 km at 19.77h distance 0.23 late
row 122 2.96 km at 20.34h distance 0.34 on time
row 5 3.13 km at 19.68h distance 0.35 late
row 35 2.93 km at 20.48h distance 0.49 on time
row 183 3.47 km at 19.76h distance 0.53 late
P(late) = 0.6 -> lateThese are the worked example's five neighbours. .predict_proba gives the share of votes for each class. For regression, KNeighborsRegressor averages instead of voting.
Training and validation accuracy for a few values of :
def k_sweep(ks: list[int]) -> list[tuple[int, float, float]]:
"""For each k: (k, training accuracy, validation accuracy), on raw km and hours."""
rows = []
for k in ks:
model = KNeighborsClassifier(n_neighbors=k).fit(x_train, y_train)
rows.append((k, model.score(x_train, y_train), model.score(x_val, y_val)))
return rows
for k, train_acc, val_acc in k_sweep([1, 5, 25, 101]):
print(f"k = {k:3} train {train_acc:.1%} validation {val_acc:.1%}")k = 1 train 100.0% validation 87.5%
k = 5 train 91.0% validation 95.0%
k = 25 train 84.0% validation 87.5%
k = 101 train 76.0% validation 76.0%At , kNN is no better than the straight line of logistic regression.
Scaling is a separate step, StandardScaler. Chain it to the model with make_pipeline, so that one object scales and then votes:
def deliveries_in_metres() -> tuple[np.ndarray, np.ndarray]:
"""The deliveries table: (distance in metres, traffic 0-3) and late (over 30 minutes)."""
rows = load("deliveries")["rows"]
x = np.array([[row["distance_km"] * 1000, row["traffic"]] for row in rows])
return x, np.array([row["late"] for row in rows])
x_d, y_d = deliveries_in_metres()
train, val = slice(0, 200), slice(200, 300) # first 200 to train, last 100 to validate
raw = KNeighborsClassifier(n_neighbors=5)
scaled = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5)) # scale, then vote
for name, model in [("metres, unscaled", raw), ("standardised", scaled)]:
model.fit(x_d[train], y_d[train])
print(f"{name:17} validation accuracy {model.score(x_d[val], y_d[val]):.1%}")metres, unscaled validation accuracy 71.0%
standardised validation accuracy 80.0%StandardScalerlearns each column's mean and standard deviation in.fit, and applies them in.transform. It uses the training rows only.- A pipeline's
.fitfits the scaler, transforms the training rows, then fits the model on them. Its.predictand.scoretransform new rows with the same numbers first. The lesson on features and the workflow covers pipelines in full.
Choosing by cross-validation, with scaling inside each fold:
search = GridSearchCV(
make_pipeline(StandardScaler(), KNeighborsClassifier()),
param_grid={"kneighborsclassifier__n_neighbors": list(range(1, 52, 2))}, # k = 1, 3, ..., 51
cv=5,
)
search.fit(x_train, y_train)
print(search.best_params_, f"cross-validation {search.best_score_:.1%}", f"validation {search.score(x_val, y_val):.1%}"){'kneighborsclassifier__n_neighbors': 9} cross-validation 86.0% validation 94.0%GridSearchCV tries with 5-fold cross-validation on the 200 training deliveries, and picks . Because the scaler is inside the pipeline, each fold fits its own scaler on its own training rows. The step names come from make_pipeline, so is kneighborsclassifier__n_neighbors.
Cross-validation picked 9 rather than 5. Each fold trains on only 160 deliveries, so the scores of nearby differ by a few deliveries. 9 and 5 are about equally good. The search also standardises km and hour, unlike the sweep above. On the validation set, the chosen pipeline scores 94%.
Putting it together
A dispatcher wants a prediction for a 3 km trip sent at 20:00.
- Scale. Here km and hours are already comparable. On most tables, standardise first, fitting the scaler on training rows only.
- Find the neighbours. With : gaps 0.23, 0.34, 0.35, 0.49 and 0.53.
- Vote. 3 late, 2 on time: predict late, with a late share of 0.6.
- Choose k with validation data. memorises (100% on training data, 87.5% on validation). gets 95% on validation, better than logistic regression's 76%.
- Watch the cost. Each prediction measures 200 gaps. With far more data or many features, use a faster search, or a model that summarises the data.
Common misconceptions
"kNN learns something during training." Training only stores the data. All the work, measuring gaps and voting, happens at prediction time. That's why it's fast to train and slow to predict.
"k = 1 is the most accurate, since it scores 100% on training data." Each training point is its own nearest neighbour. So 100% is guaranteed, and it says nothing. On validation data, (87.5%) loses to (95%).
"A bigger k is always safer." A bigger smooths more. Too big and it blurs away real structure, like the 19:00 dip, and in the end predicts the majority class everywhere.
"Units don't matter, the model will sort it out." kNN uses the raw distance formula. With distance in metres, a 100 m gap outweighs a jump from clear to jammed traffic. Standardise first: here that lifts validation accuracy from 71% to 80%.
"Scale using all the data before splitting." Fit the scaler on training rows only, and apply it to the rest. A pipeline does this for you, even inside cross-validation.
"More features always help kNN." Each useless feature adds noise to every distance, and with many features all distances look alike. Fewer, better features often help kNN more.
Recap
- k-nearest neighbours predicts for a new example from the closest training examples: their majority class, or the average of their values.
- It's a non-parametric model: it keeps all its training data, so it's quick to train, slow to predict, and its boundary can take any shape.
- sets the bias–variance trade-off: is jagged and memorises (100% training accuracy); a large is smooth and blurs detail. Choose it with validation data or cross-validation.
- Distances add up every feature's gap, so features must be on comparable scales. Standardise (subtract the mean, divide by the standard deviation), fitting on training rows only.
- With many features, all distances bunch together and "nearest" loses its meaning: the curse of dimensionality.
- scikit-learn names in this lesson:
KNeighborsClassifier(n_neighbors,.kneighbors,.predict_proba),KNeighborsRegressor,StandardScaler,make_pipelineandGridSearchCV(param_grid,best_params_).