k-nearest neighbours
Predict from the most similar training examples: no training, one knob, and a lesson about distance.
Animated explanation
The idea
"Tell me who your neighbours are and I'll tell you who you are." To classify a new point, find the training points closest to it and take a majority vote; for regression, average their values.
There is no training phase: the model is the stored data. That makes k-NN wonderfully flexible (it can carve any boundary shape) but also slow at prediction time and completely dependent on what "close" means. Choosing the distance and scaling the features is most of the work.
k controls bias and variance
With the boundary hugs every training point, outliers included: zero training error, high variance. Larger averages over more neighbours, smoothing the boundary and lowering variance, until it blurs real structure (high bias). Odd avoids ties in binary problems. Choose by cross-validation; distance-weighted voting makes the choice less sensitive.
Distance is everything
Features on large scales dominate Euclidean distance: income in rupees would swamp age in years. Always standardise. Irrelevant features add noise to every distance, so feature selection helps a lot. Use Hamming or Jaccard distance for categorical data and cosine distance for text embeddings.
The curse of dimensionality
In high dimensions, points become nearly equidistant: the nearest and farthest neighbours are at almost the same distance, so "nearest" carries little information. To have neighbours close by, the data needed grows exponentially with the dimension. k-NN works best in low to moderate dimensions, or on learned embeddings where distance is meaningful. For speed, use KD-trees or ball trees in low dimensions and approximate nearest-neighbour indexes (HNSW) for large embedding collections.
The algorithm, step by step
- 1Standardise features; store the training set.
- 2For a query , compute distances to all training points.
- 3Take the smallest (e.g. with np.argpartition).
- 4Classification: majority vote among their labels. Regression: their (optionally distance-weighted) mean.
The maths
Majority vote
Euclidean distance
Fast squared distances (matrix form)
Asymptotics
Strengths and weaknesses
Strengths
- No training; trivially handles new data
- Any decision boundary shape; naturally multi-class
- Easy to explain with concrete similar examples
Weaknesses
- Prediction is slow: compares with every stored point
- Needs feature scaling and a meaningful distance
- Suffers badly in high dimensions
Reach for it when…
Check your understanding
Lambdian Lab
Vectorised k-NN
Implement k-NN without Python loops over training points.
- pairwise_sq_dists(A, B): an (len(A), len(B)) matrix of squared Euclidean distances using (clip tiny negatives to 0).
- knn_predict(X_train, y_train, X, k): majority vote; break ties towards the smallest class label (np.bincount + argmax does this).
- best_k(X_tr, y_tr, X_va, y_va, ks): the k with the highest validation accuracy (smallest k on ties).