k-Nearest Neighbours
The k-NN algorithm for classification and regression, distance metrics (Euclidean, Manhattan, Minkowski, cosine, Hamming), why feature scaling matters, choosing k and its bias–variance effect, distance-weighted voting, computational cost and speed-ups (k-d trees, approximate search), the curse of dimensionality, and the 1-NN error guarantee.
The algorithm
k-NN makes predictions directly from the stored training data:
- Compute the distance from the query to every training point.
- Take the nearest.
- Classification: majority vote of their labels. Regression: average (or median) of their targets.
import numpy as np
from collections import Counter
def knn_predict(X_train, y_train, x, k=3):
d = np.linalg.norm(X_train - x, axis=1) # Euclidean distances
idx = np.argsort(d)[:k] # k nearest
return Counter(y_train[idx]).most_common(1)[0][0]
k-NN is non-parametric (no fixed set of parameters), instance-based and lazy (all work happens at prediction time).
Distance metrics
| Metric | Formula | Use |
|---|---|---|
| Euclidean (L2) | default for continuous features | |
| Manhattan (L1) | grid-like movement, robust to outliers | |
| Minkowski () | special cases; : Chebyshev | |
| Cosine distance | text, embeddings (direction matters, not length) | |
| Hamming | number of differing positions | categorical/binary features |
Choosing k
| Boundary | Bias | Variance | |
|---|---|---|---|
| 1 | very jagged, follows noise | low | high |
| moderate | smoother | moderate | moderate |
| constant (majority class everywhere) | high | low |
Choose by cross-validation; a common heuristic starting point is . Use odd for binary problems.
Distance-weighted voting gives closer neighbours more say (weights or ), reducing sensitivity to .
Cost and speed-ups
- Training: (store the data) — but memory .
- Prediction: distances plus selecting the smallest.
- Speed-ups: k-d trees and ball trees (effective in low dimensions), locality-sensitive hashing and graph-based approximate nearest neighbour search (high dimensions, used in vector databases).
The curse of dimensionality
In high dimensions, data becomes sparse and distances concentrate — the nearest and farthest points are almost equally distant, so neighbourhoods are no longer "local". To keep the same density of samples, the data needed grows exponentially with . Mitigate with PCA, feature selection or learned embeddings.
A theoretical guarantee
As , the error rate of 1-NN is at most twice the Bayes error (the lowest achievable error) — a remarkable result for such a simple method (Cover and Hart, 1967). With and , k-NN converges to the Bayes classifier itself.
Quick revision
Practice questions
GATE-style questions: 4 one-mark and 5 two-mark. Wrong MCQs cost ⅓ of their marks in the real exam; MSQ and NAT have no negative marking. Attempt each before opening the solution.
Training points: class + at and ; class − at , and . Using Euclidean distance and , the query point is classified as
k-NN regression with uses training data with targets . The prediction at is ______ (round to two decimals).
How does increasing in k-NN affect the model?
Which statements about k-NN are true?
One or more options are correct.
The Manhattan (L1) distance between and is ______.
For a training set with no two identical points carrying different labels, the training error of the 1-nearest-neighbour classifier (each training point classified using the full training set) is ______.
The "curse of dimensionality" hurts k-NN in high dimensions mainly because
Distance-weighted k-NN uses weight for each neighbour. With neighbours at distances 1 (class A), 3 (class B) and 3 (class B), the total weight for class B is ______ (round to two decimals).
For a binary classification problem, why is an odd usually chosen?