Level 3 In-Depth AI · Classical Machine Learning
k-Nearest Neighbours
The simplest learning algorithm there is. To label something new, find the k most similar examples you have already seen and let them vote.
- Level
- ●●●●● Beginner
- Reading
- 12 min
- To learn it well
- 45 minutes to read, an hour to practise
- Builds on
- 6 concepts →
- Quiz
- 5 questions ↓
This leads to
—The full path from zero — 6 concepts before this one
- What Is AI?
- Vectors
- How Machines Learn
- Dot Product, Norms and Similarity
- Supervised, Unsupervised and Reinforcement Learning
- Supervised Learning
- k-Nearest Neighbours
Read them roughly in this order. See it on the concept map →
Why it matters
Most machine-learning methods work hard during training. They squeeze the data into a compact set of numbers (the weights of a line, the splits of a tree) and then throw the data away. k-nearest neighbours (kNN) does the opposite. It keeps every training example and does all its thinking at prediction time: find the examples most like this one, and copy their answer.
That makes kNN the easiest algorithm in this guide to understand, and a surprisingly strong baseline. It also introduces three ideas you will meet again and again:
- Similarity as distance. Turning "how alike are these two things?" into a number is the core of Embeddings and Semantic Search, Vector Databases, Recommender Systems and retrieval-augmented generation. A modern RAG system that fetches "the 5 most relevant passages" is doing nearest-neighbour search on embeddings.
- The choice of k as a dial between overfitting and underfitting. This is your first concrete taste of the bias–variance tradeoff.
- The curse of dimensionality. Distances behave strangely when there are hundreds of features, and that shapes how all of AI handles high-dimensional data.
The intuition
You move to a new town and want to know whether a house is fairly priced. You don't build an equation. You look at the three or four houses most like it (same street, similar size, similar age) and see what they sold for. That is kNN.
Or take fruit. You have measured the width and height of some lemons and oranges. Lemons tend to be taller than they are wide; oranges are round. A new fruit arrives, 6.5 cm wide and 7.5 cm tall. Plot it among the others and look at its closest neighbours.
The picture shows the whole algorithm, and its main weakness. With the answer is "orange", because the single closest fruit happens to be an orange. With the answer flips to "lemon". Neither is obviously right. Small trusts individual examples, including odd ones. Large smooths over them, but if is too large, it drags in examples from far away that have little to do with the question.
Key idea kNN predicts by analogy: find the stored examples closest to the new one and let them vote (classification) or average their values (regression). There is no training step. The data is the model.
How it works
Step 1: measure distance
Each example is a vector of features, such as . To find the "closest" examples you need a distance metric: a rule that turns two vectors into one non-negative number, zero when they are identical.
The default is Euclidean distance, the straight-line distance you would measure with a ruler. For two points and with features:
In words: subtract feature by feature, square each difference, add them up, take the square root. This is Pythagoras' theorem extended to any number of dimensions, and it is the length (norm) of from Dot Product, Norms and Similarity.
Two other common choices:
- Manhattan distance adds the absolute differences, . It is like walking a city grid: you can only move along the streets. It is less dominated by one big difference.
- Cosine distance, , ignores length and compares only direction. It is the usual choice for text and embeddings, where a long document and a short one about the same topic should count as close.
Step 2: find the k nearest
Compute the distance from the new point to every stored example, sort, and keep the smallest.
Step 3: vote or average
- Classification: the majority vote of the neighbours' labels. You can also report the vote shares as rough probabilities: 2 lemons out of 3 means "lemon, 67%".
- Regression: the average of the neighbours' target values. Predict a house price as the mean price of the 5 most similar houses.
A common refinement is distance weighting: closer neighbours get a bigger say, often with weight . This softens the jumpiness when changes.
A worked example by hand
Here are the six fruits from the figure, measured in centimetres, and the new fruit :
| Fruit | Width | Height | Distance to | Rank |
|---|---|---|---|---|
| Orange A | 7.0 | 7.0 | 1 | |
| Lemon A | 5.5 | 8.0 | 2 | |
| Lemon B | 6.0 | 8.6 | 3 | |
| Lemon C | 5.2 | 7.2 | 4 | |
| Orange B | 8.0 | 7.5 | 5 | |
| Orange C | 8.2 | 8.4 | 6 |
Take Lemon B as an example: the width difference is , the height difference is , so the distance is .
- : the nearest is Orange A. Prediction: orange.
- : Orange A, Lemon A, Lemon B. Two lemons to one. Prediction: lemon (67%).
- : add Lemon C and Orange B. Three lemons to two. Prediction: lemon (60%).
Always pick an odd for two classes, so the vote can't tie.
Choosing k
is a hyperparameter: a setting you choose rather than one the algorithm learns. It controls how smooth the decision boundary is.
- Small (1 or 3) gives a jagged boundary that wraps around every noisy point. Training accuracy with is always 100%, because every training point's nearest neighbour is itself. That is Overfitting and the Bias–Variance Tradeoff: low bias, high variance.
- Large gives a smooth boundary that may miss real detail. In the limit (all the data), every prediction is the most common class. That is underfitting: high bias, low variance.
The right is found by trying several values and measuring accuracy on held-out data, ideally with Cross-Validation. Typical good values are somewhere between 3 and 30. A rough rule of thumb you may see quoted is , but cross-validation beats any rule.
Scaling the features
Distance adds up differences across features, so a feature with large numbers dominates. Suppose one feature is income in dollars (differences of thousands) and another is age in years (differences of tens). The distance is then essentially the income difference, and age is ignored, not because it is unimportant but because of its units.
The fix is feature scaling: put every feature on a comparable scale before computing distances. The usual way is standardisation: subtract each feature's mean and divide by its standard deviation, so every feature has mean 0 and spread 1. On the wine dataset in the code below, this one step lifts kNN's accuracy from 69% to 95%.
The curse of dimensionality
kNN rests on an assumption: that "nearby" means "similar". In two or three dimensions that is true. In hundreds of dimensions it starts to fail, for a strange geometric reason.
In high dimensions, random points are all roughly the same distance from each other. The "nearest" neighbour is barely nearer than the farthest one, so "nearest" carries little information. Covering the space densely enough to always have a truly close neighbour would need exponentially many examples. This is the curse of dimensionality.
Real data is kinder than random points, because it usually lies on a lower-dimensional surface inside the big space (faces vary in a few dozen ways, not in a million independent pixel values). That is why nearest-neighbour search on good learned embeddings works so well, and why raw pixels make a poor distance. It is also why you often reduce dimensions with PCA and Dimensionality Reduction before running kNN.
Speed
kNN has no training cost, which is why it is called lazy learning: storing the data is the training. But prediction is expensive. A brute-force search compares the new point to all stored examples, each with features, so it costs about operations per prediction. For 10,000 examples that is instant; for a billion embeddings it is far too slow.
Two remedies exist:
- Space-partitioning trees (k-d trees, ball trees) prune whole regions of space that can't contain the nearest neighbour. They help a lot in low dimensions and little above about 20.
- Approximate nearest-neighbour (ANN) search trades a little accuracy for huge speed-ups. Libraries such as FAISS and the indexes inside Vector Databases (graph-based HNSW, for example) find almost the nearest neighbours among billions of vectors in milliseconds.
In code
Here is kNN from scratch in NumPy, on the classic iris flower dataset (150 flowers, 4 measurements, 3 species):
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
def knn_predict(X_train, y_train, X_new, k=5):
preds = []
for x in X_new:
dists = np.sqrt(((X_train - x) ** 2).sum(axis=1)) # Euclidean distance to every training point
nearest = np.argsort(dists)[:k] # indices of the k closest
votes = np.bincount(y_train[nearest]) # count labels among them
preds.append(votes.argmax()) # majority wins
return np.array(preds)
X, y = load_iris(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
for k in (1, 5, 15):
acc = (knn_predict(X_tr, y_tr, X_te, k) == y_te).mean()
print(f"k={k:2d} test accuracy {acc:.3f}")
# k= 1 test accuracy 0.978
# k= 5 test accuracy 1.000
# k=15 test accuracy 0.978
The whole algorithm is the four lines inside the loop. Now the scikit-learn version, on the wine dataset (178 wines, 13 chemical measurements on very different scales). It shows how much scaling matters, and uses cross-validation to pick :
from sklearn.datasets import load_wine
from sklearn.model_selection import cross_val_score, GridSearchCV
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_wine(return_X_y=True) # 178 wines, 13 chemical measurements
raw = KNeighborsClassifier(n_neighbors=5)
scaled = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5))
print("raw features :", cross_val_score(raw, X, y, cv=5).mean().round(3))
print("scaled features:", cross_val_score(scaled, X, y, cv=5).mean().round(3))
search = GridSearchCV(scaled, {"kneighborsclassifier__n_neighbors": [1, 3, 5, 7, 11, 15, 25]}, cv=5)
search.fit(X, y)
print("best k:", search.best_params_["kneighborsclassifier__n_neighbors"],
" cv accuracy:", round(search.best_score_, 3))
# raw features : 0.691
# scaled features: 0.949
# best k: 7 cv accuracy: 0.967
The pipeline matters: it fits the scaler only on the training folds inside each cross-validation split, so no information from the validation fold leaks into the scaling. For regression, swap in KNeighborsRegressor. To weight neighbours by distance, pass weights="distance".
Common pitfalls
- Forgetting to scale. The single most common kNN bug. One feature in large units silently decides every prediction.
- Using k = 1 because training accuracy is perfect. It is always perfect. Judge only on held-out data.
- Irrelevant features. Every feature counts equally in the distance, including useless ones. Ten noise columns can drown out two good ones. Select features, or use a model that learns which features matter.
- Too many dimensions. On raw high-dimensional data (pixels, word counts), distances become uninformative. Reduce dimensions first, or use learned embeddings.
- Categorical features. Euclidean distance on arbitrary codes (red = 1, green = 2, blue = 3) makes red "closer" to green than to blue, which is meaningless. One-hot encode them, or use a distance designed for categories.
- Slow predictions in production. Brute-force kNN on millions of rows is too slow for real-time use. Use an approximate index.
- Imbalanced classes. If 95% of examples are one class, the majority vote leans towards it. Distance weighting or rebalancing helps.
Watch out kNN has no idea which features matter. It trusts the distance completely, so the distance must reflect real similarity. Scale your features and drop junk ones, or the "nearest" neighbours will be near in the wrong ways.
Where it leads
- Nearest-neighbour search at scale is the engine of Embeddings and Semantic Search, Vector Databases and Retrieval-Augmented Generation. There the vectors are embeddings learned by neural networks, and the metric is usually cosine similarity.
- kNN regression and imputation. Filling a missing value with the average of the nearest rows is a standard Data Cleaning and Preparation trick (
KNNImputerin scikit-learn). - Anomaly detection. A point far from all its neighbours is unusual. See Anomaly Detection.
- Collaborative filtering. "Users like you also bought…" was originally neighbour-based. See Recommender Systems.
- Clustering. k-Means Clustering also groups points by distance, but without labels.
- Kernel methods. Support vector machines also compare a new point to stored examples, but they learn which few examples matter and how much.
A bit of history
The nearest-neighbour rule was first written up by Evelyn Fix and Joseph Hodges in a 1951 technical report for the US Air Force School of Aviation Medicine, as a "nonparametric" way to classify without assuming any particular distribution. In 1967 Thomas Cover and Peter Hart proved its most famous property: with unlimited data, the error rate of the 1-nearest-neighbour rule is at most twice the lowest error any classifier could achieve. That is a remarkable guarantee for something so simple.
kNN fell out of fashion for big problems because it is slow and suffers in high dimensions. It came back in a new form in the 2010s and 2020s, when neural networks learned embeddings in which distance really does mean similarity, and approximate search libraries made it fast. Today billions of nearest-neighbour lookups a day power search engines, recommendation feeds and LLM retrieval.
Try it
- Redo the fruit example by hand with Manhattan distance. Does the ranking change? Does any prediction change?
- In the from-scratch code, add a
weightsoption where each neighbour's vote counts . Compare accuracy with plain voting for .- Harder: add 20 columns of random noise to the wine data (
np.random.normal(size=(178, 20))) and re-run the scaled pipeline. How much does accuracy fall? What does that tell you about irrelevant features?Hint for 3:
np.hstack([X, noise])joins the columns. Remember to scale the noise too. The pipeline does this for you.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
StatQuest
Short, cheerful, very clear videos on statistics and nearly every ML algorithm.
An Introduction to Statistical Learning (with Python)
The friendliest rigorous introduction to classical ML, with Python labs. Free PDF.
scikit-learn: Nearest Neighbors
The official guide to kNN classification and regression, distance metrics and the tree structures that make neighbour search fast.
Machine Learning Crash Course
Short, practical lessons with interactive visualisations covering regression, classification, embeddings and neural nets.
Nearest Neighbor Pattern Classification
Proved that the 1-nearest-neighbour rule's error is at most twice the best possible error, given enough data.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/k-nearest-neighbors.md