◆ AI All-in-One

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
↗ Plan a path here

Read first

Supervised LearningDot Product, Norms and Similarity

This leads to

—
The full path from zero — 6 concepts before this one
  1. What Is AI?
  2. Vectors
  3. How Machines Learn
  4. Dot Product, Norms and Similarity
  5. Supervised, Unsupervised and Reinforcement Learning
  6. Supervised Learning
  7. 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:

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.

new fruit ? width (cm) height (cm) k = 1 k = 3 lemon orange to classify k = 1: orange the single closest fruit is an orange (0.71 cm) k = 3: lemon 2 lemons beat 1 orange k = 5: lemon 3 lemons vs 2 oranges the answer depends on k
Fig. 1 Classifying a new fruit by its nearest neighbours. With k = 1 the single closest fruit is an orange. With k = 3 the circle widens to take in two lemons, which outvote it. The answer depends on k.

The picture shows the whole algorithm, and its main weakness. With k=1k = 1 the answer is "orange", because the single closest fruit happens to be an orange. With k=3k = 3 the answer flips to "lemon". Neither is obviously right. Small kk trusts individual examples, including odd ones. Large kk smooths over them, but if kk 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 kk 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 x=(width,height)\mathbf{x} = (\text{width}, \text{height}). 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 a\mathbf{a} and b\mathbf{b} with nn features:

d(a,b)=∑j=1n(aj−bj)2d(\mathbf{a}, \mathbf{b}) = \sqrt{\sum_{j=1}^{n} (a_j - b_j)^2}

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 a−b\mathbf{a} - \mathbf{b} from Dot Product, Norms and Similarity.

Two other common choices:

  • Manhattan distance adds the absolute differences, ∑j∣aj−bj∣\sum_j |a_j - b_j|. It is like walking a city grid: you can only move along the streets. It is less dominated by one big difference.
  • Cosine distance, 1−cos⁡(a,b)1 - \cos(\mathbf{a}, \mathbf{b}), 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 kk smallest.

Step 3: vote or average

  • Classification: the majority vote of the kk 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 1/d1/d. This softens the jumpiness when kk changes.

A worked example by hand

Here are the six fruits from the figure, measured in centimetres, and the new fruit q=(6.5,7.5)\mathbf{q} = (6.5, 7.5):

Fruit Width Height Distance to q\mathbf{q} Rank
Orange A 7.0 7.0 0.52+0.52=0.707\sqrt{0.5^2 + 0.5^2} = 0.707 1
Lemon A 5.5 8.0 1.02+0.52=1.118\sqrt{1.0^2 + 0.5^2} = 1.118 2
Lemon B 6.0 8.6 0.52+1.12=1.208\sqrt{0.5^2 + 1.1^2} = 1.208 3
Lemon C 5.2 7.2 1.32+0.32=1.334\sqrt{1.3^2 + 0.3^2} = 1.334 4
Orange B 8.0 7.5 1.52+02=1.500\sqrt{1.5^2 + 0^2} = 1.500 5
Orange C 8.2 8.4 1.72+0.92=1.924\sqrt{1.7^2 + 0.9^2} = 1.924 6

Take Lemon B as an example: the width difference is 6.0−6.5=−0.56.0 - 6.5 = -0.5, the height difference is 8.6−7.5=1.18.6 - 7.5 = 1.1, so the distance is 0.25+1.21=1.46=1.208\sqrt{0.25 + 1.21} = \sqrt{1.46} = 1.208.

  • k=1k = 1: the nearest is Orange A. Prediction: orange.
  • k=3k = 3: Orange A, Lemon A, Lemon B. Two lemons to one. Prediction: lemon (67%).
  • k=5k = 5: add Lemon C and Orange B. Three lemons to two. Prediction: lemon (60%).

Always pick an odd kk for two classes, so the vote can't tie.

Choosing k

kk is a hyperparameter: a setting you choose rather than one the algorithm learns. It controls how smooth the decision boundary is.

k = 1 jagged: follows every noisy point training accuracy 100% k = 15 smooth: averages over neighbourhoods training accuracy 94%
Fig. 2 The same noisy two-class data classified with k = 1 (left) and k = 15 (right). With k = 1 the regions bend around every stray point, and training accuracy is a perfect but meaningless 100%. With k = 15 the boundary is smoother and closer to the true shape of the two half-moons.
  • Small kk (1 or 3) gives a jagged boundary that wraps around every noisy point. Training accuracy with k=1k = 1 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 kk gives a smooth boundary that may miss real detail. In the limit k=Nk = N (all the data), every prediction is the most common class. That is underfitting: high bias, low variance.

The right kk 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 k≈Nk \approx \sqrt{N}, 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.

1 10 100 1000 0 0.5 1 number of dimensions (log scale) nearest distance ÷ farthest distance 2 dimensions: 0.01 nearest is far closer than farthest 1,000 dimensions: 0.89 everything is about equally far away 1,000 random points in a unit cube, averaged over 20 random queries
Fig. 3 How distances change as dimensions are added. For 1,000 random points, the ratio of the nearest distance to the farthest is about 0.01 in two dimensions but about 0.9 in a thousand dimensions. Almost every point is about equally far away.

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 NN stored examples, each with nn features, so it costs about N×nN \times n 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 kk:

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 kk 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

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

  1. Redo the fruit example by hand with Manhattan distance. Does the ranking change? Does any prediction change?
  2. In the from-scratch code, add a weights option where each neighbour's vote counts 1/d1/d. Compare accuracy with plain voting for k=15k = 15.
  3. 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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Your kNN model uses income in dollars and age in years, unscaled. What happens?

  2. With k = 1, kNN scores 100% on its training data. What does that tell you?

  3. A new fruit's three nearest neighbours are an orange (closest), then two lemons. What does kNN predict with k = 1 and with k = 3?

  4. You run kNN on raw images with thousands of pixel features, and the nearest neighbours seem almost random. Why?

  5. Why is kNN called lazy learning?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Video

StatQuest

Josh Starmer · Beginner · Free

Short, cheerful, very clear videos on statistics and nearly every ML algorithm.

Docs

scikit-learn: Nearest Neighbors

scikit-learn · Intermediate · Free

The official guide to kNN classification and regression, distance metrics and the tree structures that make neighbour search fast.

Course

Machine Learning Crash Course

Google · Beginner · Free

Short, practical lessons with interactive visualisations covering regression, classification, embeddings and neural nets.

Paper

Nearest Neighbor Pattern Classification

Cover & Hart · 1967 · Advanced · Paid

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