Learning path: Choose and Tune a Model: Classic Algorithms to a Saved Pipeline · Step 1 of 10
K-Nearest Neighbours (KNN): Distance, k and Why Scaling Is a Must
Price a house from its three most similar neighbours, by hand and with KNeighborsRegressor, see scaling swap Pine for Birch, then pick k on the wine data with cross-validation: best k is 17 and the test accuracy is 1.0.
What you will learn
- Compute the Euclidean distance from a new row to every training row by hand
- Predict a number by averaging the k nearest neighbours, and a class by letting them vote
- Show how unscaled columns pick the wrong neighbours
- Choose k with cross-validation on the train rows, then test once
Before you start
- Feature Scaling: StandardScaler and MinMaxScaler
- Cross-Validation with StratifiedKFold
A new house comes on the market on your street: 82 square metres, 4 bedrooms. What is it worth? You'd look at the three most similar houses nearby and average their prices. Pine sold for 250 thousand, Fir for 330 and Ash for 260. (250 + 330 + 260) / 3 = 280 thousand.
That's the whole idea of K-Nearest Neighbours (KNN): find the most similar rows, and let them decide. Here k = 3. There's no formula to learn and no weights to fit. The model simply remembers the training rows.
The houses
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_wine
from sklearn.model_selection import (
cross_val_score, train_test_split)
from sklearn.neighbors import (
KNeighborsClassifier, KNeighborsRegressor)
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
houses = pd.read_csv("houses.csv")
houses
house size_m2 bedrooms price_k
0 Oak 50 1 180
1 Elm 65 2 220
2 Ash 70 3 260
3 Pine 80 2 250
4 Fir 85 4 330
5 Birch 95 3 300
6 Cedar 110 4 360
7 Maple 120 5 410
How far is each house? Distance
A computer decides "similar" by measuring a distance. Take the new house and Pine. The size gap is 82 - 80 = 2 and the bedroom gap is 4 - 2 = 2. Those two gaps are the sides of a right triangle, and the distance is the long side:
distance = sqrt(2² + 2²) = sqrt(8) = 2.83
That's the Euclidean distance, the straight-line gap between two rows. With more columns you just add more squared gaps under the root. In code we do it for every house at once:
new = np.array([82, 4])
X = houses[["size_m2", "bedrooms"]].to_numpy()
gap = X - new
houses["dist"] = np.sqrt((gap ** 2).sum(axis=1))
near = houses.sort_values("dist").head(3)
near.round(2)
house size_m2 bedrooms price_k dist
3 Pine 80 2 250 2.83
4 Fir 85 4 330 3.00
2 Ash 70 3 260 12.04
print(near["price_k"].mean())
280.0
Subtract the new house from every row, square the gaps, add them up, take the root. Sort, keep the three nearest, average their prices: 280 thousand, the same as our hand maths.
The trap: big numbers shout
Look at the ranges. Size runs from 50 to 120, bedrooms only from 1 to 5. Pine is 2 square metres away and 2 bedrooms away, and the raw distance counts both gaps as 2. But 2 square metres is a sliver, and 2 bedrooms is half the whole bedroom range.
So we scale both columns first, then measure again:
scaler = StandardScaler().fit(X)
Xs = scaler.transform(X)
news = scaler.transform([new])
gap = Xs - news
houses["dist_s"] = np.sqrt((gap ** 2).sum(axis=1))
near_s = houses.sort_values("dist_s").head(3)
near_s[["house", "price_k", "dist_s"]].round(2)
house price_k dist_s
4 Fir 330 0.14
2 Ash 260 0.98
5 Birch 300 1.01
print(near_s["price_k"].mean().round(1))
296.7
Once both columns have the same spread, the bedroom gap counts properly. Pine drops out, Birch comes in, and the guess moves from 280 to 296.7. KNN always needs scaling. Feature Scaling explains StandardScaler itself and shows which other models care.
KNN regression in scikit-learn
KNeighborsRegressor does the same steps for you. fit just stores the rows. Put a StandardScaler in front with a pipeline, so new rows are scaled with the same numbers.
X = houses[["size_m2", "bedrooms"]]
y = houses["price_k"]
new_house = pd.DataFrame(
{"size_m2": [82], "bedrooms": [4]})
raw = KNeighborsRegressor(n_neighbors=3)
raw.fit(X, y)
scaled = make_pipeline(StandardScaler(),
KNeighborsRegressor(n_neighbors=3))
scaled.fit(X, y)
print(raw.predict(new_house).round(1))
print(scaled.predict(new_house).round(1))
[280.]
[296.7]
The same two answers as the hand maths.
For a class, the neighbours vote
To predict a class instead of a number, the k nearest neighbours vote and the majority wins. That makes k matter:
- k = 1 trusts a single neighbour. One odd point can fool it.
- A medium k, like 5, lets several neighbours vote. Calmer.
- A very big k lets almost everyone vote, so the answer drifts towards the biggest class.
So k is a setting you choose, and you choose it with cross-validation on the train rows.
Pick k on the wine data
The wine data ships with scikit-learn: 178 wines, 13 measurements, 3 growers. Split first, 80/20, stratified:
X, y = load_wine(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42)
print(X.shape, X_train.shape, X_test.shape)
print(X["proline"].max(), X["hue"].max())
(178, 13) (142, 13) (36, 13)
1680.0 1.71
Proline goes up to 1680 while hue stays below 2. Proline will shout, just like house size. Now cross-validate a raw KNN and a scaled pipeline for a few values of k, on the 142 train wines only:
for k in [1, 5, 11, 21]:
knn = KNeighborsClassifier(n_neighbors=k)
pipe = make_pipeline(StandardScaler(), knn)
a = cross_val_score(knn, X_train, y_train, cv=5)
b = cross_val_score(pipe, X_train, y_train, cv=5)
print(k, a.mean().round(3), b.mean().round(3))
1 0.726 0.937
5 0.711 0.965
11 0.705 0.972
21 0.705 0.972
These are 5-fold CV accuracies on the train rows. Raw KNN stays around 0.71 whatever k is. Scaled climbs to 0.972. Now try every odd k from 1 to 31 and draw both lines:
ks = list(range(1, 32, 2))
raw_scores, scaled_scores = [], []
for k in ks:
knn = KNeighborsClassifier(n_neighbors=k)
pipe = make_pipeline(StandardScaler(), knn)
a = cross_val_score(knn, X_train, y_train, cv=5)
b = cross_val_score(pipe, X_train, y_train, cv=5)
raw_scores.append(a.mean())
scaled_scores.append(b.mean())
plt.plot(ks, raw_scores, label="raw")
plt.plot(ks, scaled_scores, label="scaled")
plt.xlabel("k")
plt.ylabel("5-fold CV accuracy")
plt.legend()
plt.show()

best_k = ks[int(np.argmax(scaled_scores))]
print(best_k, round(max(scaled_scores), 3))
17 0.979
argmax picks the best scaled k: 17, with a CV accuracy of 0.979. The test rows are still untouched.
Only now, the test rows
final = make_pipeline(StandardScaler(),
KNeighborsClassifier(n_neighbors=best_k))
final.fit(X_train, y_train)
print(round(final.score(X_test, y_test), 3))
print(final.predict(X_test.iloc[[0]]), y_test.iloc[0])
1.0
[0] 0
Fit the winning pipeline on the train rows and score it once: 1.0 on 36 wines it has never seen. The first test wine is predicted as grower 0, and it really is grower 0.
Common mistakes
- Forgetting to scale. The column with the biggest numbers picks the neighbours on its own.
- Picking k on the test rows. Choose k with cross-validation on the train rows, then test once.
- k = 1 by default. One neighbour is easily fooled by a single odd row.
- Expecting fast predictions on big data. KNN does almost no work in
fit; the work happens at prediction time, when it searches the stored rows for neighbours.
Quick recap
| Idea | What it means | In this example |
|---|---|---|
| Distance | Straight-line gap between two rows | New house to Pine: 2.83 |
| k | How many neighbours get a say | k = 3 for the houses |
| Regression | Average the neighbours' values | 280 raw, 296.7 scaled |
| Classification | The neighbours vote | Wine growers 0, 1, 2 |
| Scale first | make_pipeline(StandardScaler(), ...) | CV about 0.71 raw, 0.972 scaled |
| Pick k by CV | On the train rows only | k = 17, CV 0.979, test 1.0 |
Try it yourself
Add weights="distance" to the classifier, so closer neighbours get a bigger say. Does the best k or the score change?
Next, a model that learns by counting instead of measuring: Naive Bayes.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Linear Regression and the Cost Function: Draw a Line, Score It
Draw a straight line through six kids' ages and weights, measure every miss, and turn the misses into one score, the mean squared error. Then let np.polyfit find the line with the lowest score.
Gradient Descent Explained: Feel the Slope, Step Downhill
Instead of handing over the best line, let the computer walk to it: measure the slope of the cost, step downhill with a learning rate, repeat. Shown step by step on six kids' ages and weights.
Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
Predict a yearly medical bill with scikit-learn's LinearRegression: first from age alone, then from every column inside a pipeline. Each coefficient reads like a price tag, and smoker_yes is by far the biggest.
Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
Score a regression model honestly: MAE, MSE and RMSE from four darts, then the insurance model on 268 test people, a DummyRegressor baseline to beat, R-squared and adjusted R-squared, and a residual plot.