Overview
K-nearest neighbours rests on one assumption: rows that are close together tend to have the same answer. The model does no training in the usual sense. It simply stores the training rows. To predict for a new row, it measures the distance to every stored row, picks the k closest ones, and lets them decide: a vote for classification or an average for regression. Closer neighbours can be given a larger say. The whole method depends on the distance being meaningful, so the choice of distance and the scaling of the features matter more than anything else.
A short history
Evelyn Fix and Joseph Hodges described the nearest neighbour rule in a 1951 technical report on non-parametric discrimination. Thomas Cover and Peter Hart proved in 1967 that, with enough data, the error of the single nearest neighbour rule is at most twice the best achievable error. The method needs no training step, which made it a standard baseline, and the same idea drives modern vector search.
How it works
- Store the training rows and their targets. Nothing else is learned.
- For a query row, compute the distance to every stored row with the chosen
metric. - Sort the distances and keep the nearest rows.
- Give each neighbour a weight: 1 for
uniform, or 1 over its distance fordistance. An exact match, at distance 0, decides alone. - Classification: add up the weights per class and predict the class with the largest total.
- Regression: predict the weighted mean of the neighbours' targets.
Watch out for
- A feature measured in large units dominates the distance and the others are ignored. Scale the features to comparable ranges first.
- In high dimensions all points become almost equally far apart, so the nearest neighbours are barely nearer than the rest and the vote loses meaning.
- Every prediction compares the query with all stored rows, so cost grows with the size of the training set. For millions of rows an approximate index is needed.
- A small follows noise in single rows and a large blurs real boundaries and favours the majority class. Choose with held-out data.
Use cases
When to use it
A strong baseline with few assumptions on small and medium data with a meaningful distance. It is also the direct answer to: find similar items.
In industry
- Recommendation
- Item-to-item suggestions: showing products whose feature or embedding vectors are closest to the one being viewed.
- Search and retrieval
- Finding the stored documents or images whose embeddings are nearest to a query, usually with an approximate index at scale.
- Data preparation
- Filling in missing values in a row from the values of its most similar complete rows.
Choosing it: what must hold
- A distance between rows that reflects real similarity for the task.
- Numeric features scaled to comparable ranges, so that no single column dominates the distance.
- A modest number of features; distances lose meaning as dimensions grow.
- A training set small enough to search at prediction time, or an approximate nearest neighbour index.
When to choose something else
| If | Use instead |
|---|---|
| Predictions must be fast on a very large training set | A trained model such as logistic regression or gradient boosted trees |
| There are many irrelevant or mixed-type features | A random forest |
| The raw inputs are images or text | Embed them with a trained network first, for example a Siamese network, then search neighbours |
Math foundations
Euclidean distance
The straight-line distance. Squaring makes large differences in one feature count heavily.
Manhattan and cosine distance
Manhattan adds the absolute differences and is less sensitive to one large gap. Cosine distance compares direction only and ignores length, which suits text counts and embeddings.
Weighted vote
Each of the neighbours adds its weight to its own class and the class with the largest total wins. Dividing the totals by their sum gives the class shares returned by
predict_proba.Weighted mean, for regression
The prediction is an average of the neighbours' targets, so it can never leave the range of the training targets.
Cost of one query
Brute force computes one distance per stored row, each over features. There is no training cost, and all of the work happens at prediction time.
Symbols
- two rows being compared
- number of features
- the query row
- the set of the k training rows nearest to x
- distance from the query to neighbour i
- vote weight of neighbour i
- class or target of neighbour i
- 1 if neighbour i has class c, otherwise 0
- number of stored training rows
Worked by hand
A query with . Its nearest neighbours are one row of class A at distance 1 and two rows of class B at distances 2 and 4.
With one vote each, class B wins two to one. With distance weights the single close neighbour outweighs the two farther ones and class A wins with a share of 0.57. The choice of weights changes the answer.
Visual example
Loading the example.
Try this
- Set k to 1 and add one stray point: it gets its own island.
- Raise k and watch the islands dissolve.
Code sample
import numpy as np
from impl import KNN
from config import KNNConfig
rng = np.random.default_rng(0)
X = np.vstack([rng.normal(-2, 1, size=(100, 2)), rng.normal(2, 1, size=(100, 2))])
y = np.array(["left"] * 100 + ["right"] * 100)
model = KNN(KNNConfig(k=5, weights="distance")).fit(X, y)
print(model.predict(np.array([[-1.5, -2.0], [2.5, 1.0]]))) # ['left' 'right']
dist, idx = model.kneighbors(np.array([[0.0, 0.0]])) # the 5 nearest training rowsRead the implementation (101 lines)
"""KNN: k-nearest-neighbours classifier and regressor.
NumPy only. `fit` stores the training set; `predict` finds the k closest stored rows by brute force and lets
them vote (classification) or averages their targets (regression).
"""
from __future__ import annotations
import numpy as np
try:
from .config import KNNConfig
except ImportError: # run from the template's own folder
from config import KNNConfig
def pairwise_distances(A: np.ndarray, B: np.ndarray, metric: str = "euclidean") -> np.ndarray:
"""Distances between every row of A (m, d) and every row of B (n, d). Returns (m, n).
metric: "euclidean", "manhattan" or "cosine" (1 - cosine similarity; a zero vector is at distance 1).
"""
A = np.asarray(A, dtype=float)
B = np.asarray(B, dtype=float)
if metric == "euclidean":
sq = np.sum(A**2, axis=1)[:, None] - 2.0 * (A @ B.T) + np.sum(B**2, axis=1)[None, :]
return np.sqrt(np.maximum(sq, 0.0))
if metric == "manhattan":
return np.abs(A[:, None, :] - B[None, :, :]).sum(axis=2)
if metric == "cosine":
na = np.linalg.norm(A, axis=1)[:, None]
nb = np.linalg.norm(B, axis=1)[None, :]
denom = na * nb
sim = np.divide(A @ B.T, denom, out=np.zeros((len(A), len(B))), where=denom > 0)
return 1.0 - np.clip(sim, -1.0, 1.0)
raise ValueError(f"unknown metric {metric!r}")
class KNN:
"""Nearest-neighbour model. `task` chooses between majority vote and averaging."""
def __init__(self, config: KNNConfig | None = None) -> None:
self.config = config or KNNConfig()
self.X_: np.ndarray | None = None
self.y_: np.ndarray | None = None # class indices (classification) or values (regression)
self.classes_: np.ndarray | None = None
def fit(self, X: np.ndarray, y: np.ndarray) -> "KNN":
"""Store the training set. X: (n, d). y: (n,) labels or values."""
X = np.asarray(X, dtype=float)
if len(X) < self.config.k:
raise ValueError(f"k={self.config.k} needs at least that many training rows, got {len(X)}")
self.X_ = X
if self.config.task == "classification":
self.classes_, self.y_ = np.unique(np.asarray(y), return_inverse=True)
else:
self.y_ = np.asarray(y, dtype=float)
return self
def kneighbors(self, X: np.ndarray, chunk: int = 512) -> tuple[np.ndarray, np.ndarray]:
"""The k nearest training rows of each query, nearest first.
X: (m, d). Returns (distances (m, k), indices (m, k)). Queries are processed `chunk` at a time to bound
memory. Ties are broken by the lower training index.
"""
X = np.asarray(X, dtype=float)
k = self.config.k
dist_out = np.empty((len(X), k))
idx_out = np.empty((len(X), k), dtype=int)
for start in range(0, len(X), chunk):
D = pairwise_distances(X[start:start + chunk], self.X_, self.config.metric)
idx = np.argsort(D, axis=1, kind="stable")[:, :k]
idx_out[start:start + chunk] = idx
dist_out[start:start + chunk] = np.take_along_axis(D, idx, axis=1)
return dist_out, idx_out
def _weights(self, dist: np.ndarray) -> np.ndarray:
"""Vote weight of each neighbour. dist: (m, k) -> (m, k)."""
if self.config.weights == "uniform":
return np.ones_like(dist)
exact = dist == 0
w = 1.0 / np.where(exact, 1.0, dist)
has_exact = exact.any(axis=1)
w[has_exact] = exact[has_exact].astype(float) # an exact match decides alone
return w
def predict_proba(self, X: np.ndarray) -> np.ndarray:
"""Weighted share of each class among the neighbours. X: (m, d) -> (m, n_classes)."""
if self.config.task != "classification":
raise ValueError("predict_proba is only defined for task='classification'")
dist, idx = self.kneighbors(X)
w = self._weights(dist)
votes = np.zeros((len(dist), len(self.classes_)))
np.add.at(votes, (np.arange(len(dist))[:, None], self.y_[idx]), w)
return votes / votes.sum(axis=1, keepdims=True)
def predict(self, X: np.ndarray) -> np.ndarray:
"""Majority class or weighted mean target of the neighbours. X: (m, d) -> (m,)."""
if self.config.task == "classification":
return self.classes_[self.predict_proba(X).argmax(axis=1)]
dist, idx = self.kneighbors(X)
w = self._weights(dist)
return np.sum(w * self.y_[idx], axis=1) / w.sum(axis=1)- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 7, run with
python3 -m unittest -v
Practice
Make two Gaussian clouds as in the README, then multiply the second feature by 1000. Fit KNN with k=5 on the raw data and on standardised data and compare the accuracy on held-out rows. Use kneighbors on one query to see which rows were chosen in each case, and repeat for k equal to 1, 5 and 50.
Check on learning
- With
k=1the training accuracy is always 100 percent. Why, and what does that tell you about using training accuracy to choose k?A way to think about it
Ask which stored row is nearest to a query that is itself a stored row.
- One feature is income in euros and another is age in years. What does the Euclidean distance mostly measure, and how does that affect the neighbours?
A way to think about it
Compare a typical difference in income with a typical difference in age after squaring both.
- Why does KNN regression give poor predictions for a query far outside the range of the training data?
A way to think about it
The prediction is an average of stored targets. Think about what it can and cannot produce when a trend continues beyond the data.
- In 1000 dimensions with random features, the nearest and the farthest neighbour are at nearly the same distance. What does that do to the idea of a nearest neighbour?
A way to think about it
A distance in many dimensions is a sum of many small independent terms. Consider how much such sums vary relative to their size.
- When would cosine distance choose different neighbours from Euclidean distance on the same data?
A way to think about it
Take two vectors pointing the same way with very different lengths, and a third nearby in space but pointing elsewhere.