A new flat comes up for rent in Koramangala. How much should the owner ask? The simplest sensible answer is to look at the 5 most similar flats nearby (same size, same number of rooms, same distance from the metro) and take their average rent. That's the whole idea of k-nearest neighbours (KNN): to predict something about a new example, find the k most similar examples you already know and let them decide.
KNN is the easiest algorithm in machine learning to build yourself, because it has almost no maths: it measures distances, sorts them and counts votes. Here you'll write KNN from scratch in Python, starting with one prediction worked out by hand, then a class that matches scikit-learn's KNeighborsClassifier prediction for prediction. You'll speed it up with NumPy, add distance-weighted voting and regression, write your own cross-validation to choose k, and see why KNN stops working when there are too many features.
What you need first: K-nearest neighbours (KNN) explained and feature scaling. Comfort with NumPy arrays helps.
Key terms
- Distance: a number that says how different two examples are. 0 means identical.
- Euclidean distance: the straight-line distance, √((x₁ − y₁)² + (x₂ − y₂)² + …).
- Manhattan distance: the distance along a grid, like walking city blocks: |x₁ − y₁| + |x₂ − y₂| + ….
- Majority vote: predicting the class that appears most often among the k neighbours.
- Lazy learner: a model that does no work when trained (it just stores the data) and all its work when predicting. KNN is the classic example.
- Vectorise: replace a Python loop with one NumPy operation on whole arrays, which runs much faster.
Step 1: measure distance
Two flats described by area (in hundreds of square feet) and number of rooms: flat A = (8, 2) and flat B = (11, 3).
| Distance | Working | Result |
|---|---|---|
| Euclidean | √((8 − 11)² + (2 − 3)²) = √(9 + 1) = √10 | 3.162 |
| Manhattan | |8 − 11| + |2 − 3| = 3 + 1 | 4 |
Euclidean is the "as the crow flies" distance; Manhattan adds up the differences in each feature separately. Both are 0 for identical points and grow as points differ more. In NumPy, each is one line for any number of features:
import numpy as np
def euclidean(a, b):
return np.sqrt(np.sum((a - b) ** 2))
def manhattan(a, b):
return np.sum(np.abs(a - b))
flat_a = np.array([8, 2])
flat_b = np.array([11, 3])
print(f"Euclidean: {euclidean(flat_a, flat_b):.3f}")
print(f"Manhattan: {manhattan(flat_a, flat_b)}")
Euclidean: 3.162
Manhattan: 4
Step 2: one prediction by hand
Eight flats, each with area, rooms and whether it rented within a week (1) or not (0). A new flat of area 9.5 (950 sq ft) with 2 rooms comes in. Predict with k = 3.
flats = np.array([[6, 1], [7, 2], [8, 2], [9, 3], [11, 3], [12, 3], [13, 4], [15, 4]])
rented_fast = np.array([1, 1, 1, 0, 0, 1, 0, 0])
new_flat = np.array([9.5, 2])
distances = np.array([euclidean(flat, new_flat) for flat in flats])
order = np.argsort(distances, kind="stable") # positions of the flats, nearest first
for i in order:
print(f"flat {i}: {flats[i]} distance {distances[i]:.3f} rented fast: {rented_fast[i]}")
flat 3: [9 3] distance 1.118 rented fast: 0
flat 2: [8 2] distance 1.500 rented fast: 1
flat 4: [11 3] distance 1.803 rented fast: 0
flat 1: [7 2] distance 2.500 rented fast: 1
flat 5: [12 3] distance 2.693 rented fast: 1
flat 0: [6 1] distance 3.640 rented fast: 1
flat 6: [13 4] distance 4.031 rented fast: 0
flat 7: [15 4] distance 5.852 rented fast: 0
np.argsort returns the positions that would sort the array, nearest first; kind="stable" keeps ties in their original order, so results are repeatable. The three nearest flats are the first three rows printed. Predict first: from the list above, what will k = 3 predict? Then count their labels:
from collections import Counter
k = 3
nearest_labels = rented_fast[order[:k]]
votes = Counter(nearest_labels)
print("labels of the 3 nearest:", nearest_labels)
print("votes:", {int(label): count for label, count in votes.items()})
print("prediction:", votes.most_common(1)[0][0])
labels of the 3 nearest: [0 1 0]
votes: {0: 2, 1: 1}
prediction: 0
Two of the three nearest flats took longer than a week to rent (label 0), so the vote is 2 to 1 and the prediction is 0: "won't rent within a week". Notice the order: flat 3 has one more room than the new flat but is only 50 sq ft bigger, so it's nearer than flat 2, which has the same number of rooms but is 150 sq ft smaller.
Experiment: move the new flat to 12.5 (1,250 sq ft) with 3 rooms. Predict which flats become its three nearest and how they'll vote, then run it:
other_flat = np.array([12.5, 3])
other_distances = np.array([euclidean(flat, other_flat) for flat in flats])
other_nearest = np.argsort(other_distances, kind="stable")[:3]
print("nearest flats:", other_nearest, "labels:", rented_fast[other_nearest])
nearest flats: [5 6 4] labels: [1 0 0]
The single closest flat, flat 5 (1,200 sq ft, 3 rooms, only 0.5 away), rented fast. But flats 6 and 4, a little further off, didn't, so the vote is 2 to 1 for "won't rent within a week". With k = 1, the answer would flip. Plain voting ignores how close each neighbour is; Step 5 adds weighted votes for exactly this situation.
Here's the original example as a picture: the new flat, a circle through its third-nearest neighbour, and lines to the three neighbours that vote.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(7, 5.5))
colours = np.where(rented_fast == 1, "#c2410c", "#1f5fbf")
ax.scatter(flats[:, 0], flats[:, 1], c=colours, s=90, edgecolor="k", zorder=3)
ax.scatter(*new_flat, marker="*", s=350, color="gold", edgecolor="k", zorder=4, label="New flat")
for i in order[:k]:
ax.plot([new_flat[0], flats[i, 0]], [new_flat[1], flats[i, 1]], "k--", linewidth=1)
radius = distances[order[k - 1]]
ax.add_patch(plt.Circle(new_flat, radius, fill=False, color="grey", linestyle=":"))
ax.scatter([], [], c="#c2410c", edgecolor="k", label="Rented within a week")
ax.scatter([], [], c="#1f5fbf", edgecolor="k", label="Took longer")
ax.set_xlim(4, 17)
ax.set_ylim(0, 5)
ax.set_aspect("equal")
ax.set_xlabel("Area (hundreds of sq ft)")
ax.set_ylabel("Rooms")
ax.set_title("k = 3: the three nearest flats vote")
ax.legend(loc="upper left")
plt.show()
Step 3: a KNN class
Put those steps into a class with the same methods as scikit-learn: fit stores the data, predict does the work.
class KNNClassifier:
"""K-nearest neighbours with a majority vote, one prediction at a time."""
def __init__(self, k=5):
self.k = k
def fit(self, X, y):
self.X_train = np.asarray(X)
self.y_train = np.asarray(y)
return self
def predict_one(self, x):
distances = np.sqrt(((self.X_train - x) ** 2).sum(axis=1))
nearest = np.argsort(distances, kind="stable")[:self.k]
votes = Counter(self.y_train[nearest])
return votes.most_common(1)[0][0]
def predict(self, X):
return np.array([self.predict_one(x) for x in np.asarray(X)])
def score(self, X, y):
return np.mean(self.predict(X) == np.asarray(y))
Two details:
self.X_train - xsubtracts the new point from every training row at once (NumPy broadcasting), so one line gives all the distances.kind="stable"makesargsortkeep the original order of tied distances, so results are repeatable.
Test it on the wine dataset
178 wines from three growers, with 13 chemical measurements. Scale with the training statistics, then compare with scikit-learn:
Download the data: wine.csv (12 KB), or from the original source, the UCI Machine Learning Repository. The code below loads it for you, so you only need the file to open it in a spreadsheet or work offline: load it with
pd.read_csv("wine.csv").
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
mean, std = X_train.mean(axis=0), X_train.std(axis=0)
X_train_s, X_test_s = (X_train - mean) / std, (X_test - mean) / std
ours = KNNClassifier(k=5).fit(X_train_s, y_train)
theirs = KNeighborsClassifier(n_neighbors=5).fit(X_train_s, y_train)
our_predictions = ours.predict(X_test_s)
print(f"our accuracy: {ours.score(X_test_s, y_test):.3f}")
print(f"scikit-learn accuracy: {theirs.score(X_test_s, y_test):.3f}")
print(f"same predictions: {np.mean(our_predictions == theirs.predict(X_test_s)):.0%}")
our accuracy: 0.963
scikit-learn accuracy: 0.963
same predictions: 100%
Same accuracy, 0.963, and the same prediction for every one of the 54 test wines. Your 20-line class is KNN.
What if you forget to scale?
unscaled = KNNClassifier(k=5).fit(X_train, y_train)
print(f"accuracy without scaling: {unscaled.score(X_test, y_test):.3f}")
print("feature ranges:", np.ptp(X_train, axis=0).round(1).tolist())
accuracy without scaling: 0.685
feature ranges: [3.4, 5.1, 1.5, 18.6, 81.0, 2.9, 4.7, 0.5, 3.2, 11.3, 0.9, 2.7, 1402.0]
Accuracy falls from 0.963 to 0.685. Look at the ranges: the last feature, proline, spans about 1,400 units, while most others span less than 20. Without scaling, distances are almost entirely proline differences, and the other 12 measurements are ignored.
Step 4: make it fast with vectorised distances
predict loops over test points in Python. For thousands of points, compute every test-to-train distance in one go. It uses this identity:
‖a − b‖² = ‖a‖² + ‖b‖² − 2 × (a · b)
"The squared distance equals a's squared length plus b's squared length minus twice their dot product." With matrices, the dot products of every test row with every training row are one multiplication, X_test @ X_train.T.
def distance_matrix(A, B):
"""Euclidean distance from every row of A to every row of B."""
squared = (A ** 2).sum(axis=1)[:, None] + (B ** 2).sum(axis=1)[None, :] - 2 * A @ B.T
return np.sqrt(np.maximum(squared, 0)) # tiny negatives from rounding become 0
class FastKNNClassifier(KNNClassifier):
def predict(self, X):
distances = distance_matrix(np.asarray(X), self.X_train)
nearest = np.argsort(distances, axis=1, kind="stable")[:, :self.k]
neighbour_labels = self.y_train[nearest] # shape: (test rows, k)
return np.array([Counter(row).most_common(1)[0][0] for row in neighbour_labels])
fast = FastKNNClassifier(k=5).fit(X_train_s, y_train)
print("distance table shape:", distance_matrix(X_test_s, X_train_s).shape)
print("same predictions as the loop version:", np.array_equal(fast.predict(X_test_s), our_predictions))
distance table shape: (54, 124)
same predictions as the loop version: True
The table has one row per test wine and one column per training wine. On large data this is many times faster than the loop. It also uses a lot of memory (rows × columns numbers), which is one reason scikit-learn processes it in chunks and uses search trees.
Step 5: weighted votes and KNN regression
With a plain vote, a neighbour that's almost touching counts the same as one that's far away. Distance weighting gives each neighbour a vote of 1 ÷ distance, so closer neighbours count more:
def weighted_vote(labels, distances):
weights = 1 / np.maximum(distances, 1e-12) # avoid dividing by zero
totals = {}
for label, weight in zip(labels, weights):
totals[label] = totals.get(label, 0) + weight
return max(totals, key=totals.get)
k = 5
nearest = order[:k]
print("labels: ", rented_fast[nearest])
print("distances:", distances[nearest].round(3))
print("plain vote: ", Counter(rented_fast[nearest]).most_common(1)[0][0])
print("weighted vote:", weighted_vote(rented_fast[nearest], distances[nearest]))
labels: [0 1 0 1 1]
distances: [1.118 1.5 1.803 2.5 2.693]
plain vote: 1
weighted vote: 0
With k = 5, the plain vote is 3 to 2 for "rented fast" (1). But the two flats labelled 0 are the two nearest, so with weights of 1 ÷ distance their votes count for more: 1/1.118 + 1/1.803 = 1.45 for label 0, against 1/1.5 + 1/2.5 + 1/2.693 = 1.44 for label 1. The weighted vote flips to 0, by a very small margin. Close calls like this are where weighting matters.
KNN regression predicts a number: the average of the neighbours' values. Back to the opening example, predicting a flat's rent:
from sklearn.neighbors import KNeighborsRegressor
rent = np.array([14000, 17000, 19000, 23000, 26000, 30000, 33000, 38000]) # ₹ per month
def knn_regress(X_train, y_train, x, k=3):
distances = np.sqrt(((X_train - x) ** 2).sum(axis=1))
nearest = np.argsort(distances, kind="stable")[:k]
return y_train[nearest].mean()
ours = knn_regress(flats, rent, new_flat, k=3)
theirs = KNeighborsRegressor(n_neighbors=3).fit(flats, rent).predict([new_flat])[0]
print(f"our prediction: ₹{ours:,.0f}, scikit-learn: ₹{theirs:,.0f}")
our prediction: ₹22,667, scikit-learn: ₹22,667
The three nearest flats rent for ₹23,000, ₹19,000 and ₹26,000, and their average, ₹22,667, is the prediction.
Step 6: choose k with your own cross-validation
k-fold cross-validation splits the training data into k parts (folds), trains on all but one, scores on the one left out, and repeats so every fold is left out once. (This k is the number of folds, not KNN's k.) It's a few lines from scratch:
def cross_val_accuracy(model, X, y, folds=5, seed=0):
rng = np.random.default_rng(seed)
order = rng.permutation(len(X))
parts = np.array_split(order, folds)
scores = []
for i in range(folds):
test_rows = parts[i]
train_rows = np.concatenate([parts[j] for j in range(folds) if j != i])
model.fit(X[train_rows], y[train_rows])
scores.append(model.score(X[test_rows], y[test_rows]))
return np.mean(scores)
k_values = list(range(1, 40, 2))
cv_scores = [cross_val_accuracy(FastKNNClassifier(k=k), X_train_s, y_train) for k in k_values]
best_k = k_values[int(np.argmax(cv_scores))]
print(f"best k: {best_k}, cross-validated accuracy {max(cv_scores):.3f}")
print(f"k = 1: {cv_scores[0]:.3f}, k = 39: {cv_scores[-1]:.3f}")
best k: 23, cross-validated accuracy 0.967
k = 1: 0.935, k = 39: 0.926
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(k_values, cv_scores, "o-", color="#c2410c")
ax.axvline(best_k, color="grey", linestyle="--")
ax.set_xlabel("k (number of neighbours)")
ax.set_ylabel("Cross-validated accuracy")
ax.set_title("Choosing k for the wine data")
plt.show()
k = 23 scores best at 0.967, against 0.935 for k = 1. With 124 training wines, differences of a point or two are partly noise, so any k from the middle of the range would be a sensible choice. Check it against scikit-learn's cross_val_score if you like: the folds are split differently, so the numbers won't match exactly, but the pattern will.
Only odd values of k were tried, so two-class votes can't tie. With three classes ties are still possible; Counter.most_common then picks the label it met first, which is the closer neighbour's because of the stable sort.
Step 7: the curse of dimensionality
KNN relies on "nearest" meaning something. With many features, it stops meaning much. Take 1,000 random points and a random query point, and compare the distance to the nearest point with the distance to the farthest:
rng = np.random.default_rng(0)
dimensions = [2, 10, 100, 1000]
ratios = []
for d in dimensions:
points = rng.random((1000, d))
query = rng.random(d)
dist = np.sqrt(((points - query) ** 2).sum(axis=1))
ratios.append(dist.min() / dist.max())
print(f"{d:5} features: nearest {dist.min():6.3f}, farthest {dist.max():6.3f}, ratio {dist.min() / dist.max():.2f}")
2 features: nearest 0.010, farthest 1.334, ratio 0.01
10 features: nearest 0.471, farthest 2.111, ratio 0.22
100 features: nearest 3.349, farthest 4.653, ratio 0.72
1000 features: nearest 12.166, farthest 13.553, ratio 0.90
With 2 features, the nearest point is 0.010 away and the farthest 1.334: a huge difference, so "nearest" is meaningful. With 1,000 features, the nearest is 12.2 away and the farthest only 13.6, a ratio of 0.90. Every point is almost the same distance from the query, so the "nearest" neighbours are hardly nearer than any others.
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(dimensions, ratios, "o-", color="#c2410c")
ax.set_xscale("log")
ax.set_ylim(0, 1)
ax.set_xlabel("Number of features (log scale)")
ax.set_ylabel("Nearest ÷ farthest distance")
ax.set_title("With many features, every point is about equally far away")
plt.show()
That's the curse of dimensionality. It's why KNN needs a modest number of useful features, why irrelevant features hurt it, and why people often reduce dimensions with PCA before using KNN on wide data.
Common mistakes
- Not scaling the features. The feature with the biggest range decides the distance. Standardise first.
- Scaling with all the data. Fit the mean and standard deviation on the training rows only.
- An even k with two classes. Votes can tie 2–2. Use an odd k, or distance weighting.
- Testing on the training data with k = 1. Every point's nearest neighbour is itself, so training accuracy is a perfect 100% and tells you nothing.
- Running a distance matrix on huge data. 100,000 test rows × 1,000,000 training rows is 10¹¹ numbers: far too much memory. Use scikit-learn, which uses search trees and works in chunks.
When to use KNN
KNN suits small to medium datasets with a modest number of scaled, meaningful numeric features, where similar examples really do have similar labels. It needs no training, adapts to curved boundaries, and its predictions are easy to explain ("these 5 past cases were most similar"). It's used for recommendations ("customers like you"), filling in missing values (KNNImputer) and as a quick baseline.
Avoid it when you have hundreds of thousands of rows and need fast predictions, when there are many features or many irrelevant ones, or when features are mostly categories. Tree ensembles usually do better on large, messy tables.
Practice
- Work out the Manhattan and Euclidean distances between (1, 5, 2) and (4, 1, 2) by hand, then check with the two functions.
Show the answer
Differences: 3, 4 and 0. Manhattan: 3 + 4 + 0 = 7. Euclidean: √(9 + 16 + 0) = √25 = 5.
p, q = np.array([1, 5, 2]), np.array([4, 1, 2])
print(manhattan(p, q), euclidean(p, q))
7 5.0
- In the flat example, what does k = 1 predict for the new flat, and what does k = 7 predict?
Show the answer
for k in [1, 7]:
print(k, Counter(rented_fast[order[:k]]).most_common(1)[0][0])
1 0
7 1
k = 1 uses only flat 3, which took longer, so it predicts 0. k = 7 includes four flats that rented fast and three that didn't, so it predicts 1. The prediction depends on k, which is why you choose k with cross-validation.
- Add a
metricoption toKNNClassifierso it can use Manhattan distance. Does Manhattan distance change the test accuracy on the scaled wine data with k = 5?
Show the answer
class KNNClassifierMetric(KNNClassifier):
def __init__(self, k=5, metric="euclidean"):
super().__init__(k)
self.metric = metric
def predict_one(self, x):
if self.metric == "manhattan":
distances = np.abs(self.X_train - x).sum(axis=1)
else:
distances = np.sqrt(((self.X_train - x) ** 2).sum(axis=1))
nearest = np.argsort(distances, kind="stable")[:self.k]
return Counter(self.y_train[nearest]).most_common(1)[0][0]
manhattan_knn = KNNClassifierMetric(k=5, metric="manhattan").fit(X_train_s, y_train)
print(f"Manhattan accuracy: {manhattan_knn.score(X_test_s, y_test):.3f}")
Manhattan accuracy: 0.981
Yes, slightly: 0.981 against 0.963, one more wine correct out of 54. With so few test wines that's too small a difference to trust. Treat the metric as a setting to choose with cross-validation, like k.
- Add columns of pure random noise to the scaled wine features (0, 20, 50 and 200 of them) and check the accuracy of
FastKNNClassifier(k=5)each time. What does this show?
Show the answer
for n_noise in [0, 20, 50, 200]:
rng = np.random.default_rng(1)
noisy_train = np.hstack([X_train_s, rng.standard_normal((len(X_train_s), n_noise))])
noisy_test = np.hstack([X_test_s, rng.standard_normal((len(X_test_s), n_noise))])
noisy = FastKNNClassifier(k=5).fit(noisy_train, y_train)
print(f"{n_noise:3} noise features: accuracy {noisy.score(noisy_test, y_test):.3f}")
0 noise features: accuracy 0.963
20 noise features: accuracy 0.963
50 noise features: accuracy 0.815
200 noise features: accuracy 0.704
20 noise columns make no difference here, but 50 drop accuracy to 0.815 and 200 to 0.704. Every useless column adds random amounts to every distance, until the real differences between wines are drowned out. KNN can't tell useful features from useless ones, so remove irrelevant features before using it.
Interview questions
What is the time complexity of KNN?
Training is O(1) apart from storing the data. A brute-force prediction is O(n × d) for n training rows and d features, because it computes the distance to every training row, plus the cost of selecting the k smallest. Tree structures such as KD-trees and ball trees reduce this for low-dimensional data.
Why is KNN called a lazy learner?
Because it does no generalisation at training time: it only stores the training data. All the computation happens at prediction time, when it searches for the nearest neighbours. Eager learners such as logistic regression do their work during training and predict quickly.
How would you choose k?
With cross-validation on the training data: try a range of values (often odd numbers for binary problems), pick the one with the best validation score, and prefer larger k when scores are close because it gives smoother, more stable boundaries. A common starting point is around the square root of the number of training rows.
Key takeaways
- KNN predicts by finding the k nearest training examples and taking a majority vote (classification) or an average (regression).
- From scratch it's a distance calculation, an
argsortand aCounter; the class matched scikit-learn on every test wine. - Vectorised distances with ‖a − b‖² = ‖a‖² + ‖b‖² − 2a·b remove the Python loop.
- Scale the features, choose k with cross-validation, and consider distance-weighted votes.
- With many features all points become about equally far apart, so KNN needs a modest number of useful features.
Frequently asked questions
Is KNN supervised or unsupervised?
KNN classification and regression are supervised: they need labelled training data. Don't confuse it with K-means, an unsupervised clustering algorithm that also has a "k" but finds groups without labels.
Does KNN need training?
Not in the usual sense. fit just stores the data (and, in scikit-learn, may build a search tree to speed up later searches). All the real work happens in predict.
What is a good value of k?
It depends on the data, so choose it with cross-validation. Small k (1 to 3) follows noise; very large k blurs real patterns. Values between about 5 and 25 work well on many small datasets.
What to learn next
- Use KNN on a real dataset in the penguin species classification project, or revise the theory in KNN explained.
- Learn the scaling step properly in feature scaling.
- Compare KNN with other algorithms in how to choose a machine learning algorithm.