Foundations to Frontier
Tests
D. Classical Machine Learning › D4 Instance-Based Methods

k-Nearest Neighbors Classification

k-nearest-neighbour classification needs no training: it stores the labelled examples and classifies a new point by a majority vote among the k closest ones. It can represent any decision boundary, its error approaches at most twice the Bayes error with enough data (Cover–Hart), and k controls the bias–variance trade-off. Its weaknesses are just as instructive: it depends entirely on the distance metric and feature scaling, it is slow at prediction time, and it collapses in high dimensions where all points look equally far away. This page covers the algorithm, ties, choosing k by cross-validation, scaling, the Cover–Hart bound, and the curse of dimensionality. In the exercises you implement vectorised k-NN with cross-validated k; then you classify rover terrain with a curved class boundary and measure how irrelevant features destroy k-NN as distances concentrate.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

You are who your neighbours are

To decide whether a patch of ground is soft sand or firm soil, look up the most similar patches you have already labelled and go with the majority. That is the whole of k-nearest-neighbour (k-NN) classification. There is no training and no formula. It can follow any boundary shape, however curved, as long as “similar” is measured sensibly and there are enough examples nearby.

k-nearest neighbours: let the neighbours vote
probe: 3 of 5 neighbours are orange → predicted orange (soft sand) · training accuracy 88%
The true boundary is a ring (orange between radius 0.9 and 1.8). With k = 1 every training point is classified correctly, mislabelled ones included, so the regions are full of islands: overfitting. With very large k the vote is dominated by whichever class is more common nearby, and the ring blurs: underfitting. Training accuracy is a poor guide to k; use cross-validation.
Why engineers care

k-NN is the simplest non-parametric classifier: a strong baseline, easy to explain (“these five past cases looked like this one”), and trivially updated by adding examples. It is the basis of case-based reasoning in diagnostics and of retrieval in modern embedding systems. Its failure modes (scaling, irrelevant features, high dimensions) teach what every distance-based method must respect.

📝 Quick check (Level 0)
0/3 answered
  1. 1. k-NN classifies a point by…
  2. 2. Training a k-NN classifier consists of…
  3. 3. In the demo, k = 1 produces…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

k-NN by hand

The training points are

  • class 0: (0, 0), (1, 0), (0, 1);
  • class 1: (5, 5), (6, 5), (5, 6).

Classify (0.5, 0.5) with k = 3:

  • the squared distances to the class-0 points are 0.5, 0.5 and 0.5;
  • the class-1 points are about 40 away;
  • all 3 neighbours are class 0, so the prediction is class 0.

Ties. With k = 2 and the two training points 0 (class 0) and 2 (class 1), the query 1.1 has one neighbour of each class. Break the tie by the nearest neighbour, which is 2: class 1. Choosing odd k avoids ties for two classes.

Scaling. If one feature is measured in metres and another in millimetres, the millimetre feature dominates every distance. In exercise 1, standardising the features raised accuracy from 0.715 to 0.840.

The steps in plain English:

  1. Standardise the features using the training mean and standard deviation.
  2. For a query, compute its distance to every training point.
  3. Take the k closest and count their labels.
  4. Predict the majority label (break ties by the nearest).
  5. Choose k by cross-validation. Small k fits noise; large k blurs boundaries.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Distance from (0, 0) to (3, 4)?
  2. 2. Why use odd k for two classes?
  3. 3. Standardisation uses the mean and SD of…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 30 minUndergraduate students and practising engineers.

The algorithm

Prediction: ŷ(x) = the most frequent label among the k nearest training points. P̂(y = c | x) = (number of neighbours in class c)/k gives (coarse) probability estimates.

Distances. Euclidean on standardised features is the default. For all queries at once, use ‖a − b‖² = ‖a‖² − 2a·b + ‖b‖². Other metrics and weighting schemes are covered in D4.41.

Cost:

  • training is O(1);
  • naive prediction is O(np) per query, plus selection;
  • k-d trees and ball trees (D4.43) speed up low-dimensional search;
  • approximate nearest-neighbour indexes (HNSW, FAISS) handle large, high-dimensional data.

Choosing k.

  • k = 1 has zero training error and high variance.
  • Large k has low variance and high bias, approaching the majority class as k → n.
  • Pick k by cross-validation (exercise 1: CV picks k = 5, CV error 0.135 against 0.200 for 1-NN).
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import GridSearchCV
knn = GridSearchCV(make_pipeline(StandardScaler(), KNeighborsClassifier()), {"kneighborsclassifier__n_neighbors": [1, 3, 5, 9, 15, 25]}, cv=5).fit(X, y)

Use it when there are few features that are all relevant, plenty of labelled data in the regions that matter, a boundary of any shape, and you need a quick, explainable baseline. Avoid it with many or irrelevant features, unscaled mixed units, or tight prediction-latency budgets on large datasets.

🐍 Exercise 1: k-NN with scaling and cross-validated k
Implement vectorised squared distances, k-NN prediction with nearest-neighbour tie-breaking, standardisation fitted on training data and cross-validated choice of k; show that standardisation matters when units differ, and that 1-NN overfits compared with the CV-chosen k.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Training error of 1-NN (no duplicate points) is…
  2. 2. As k → n, k-NN predicts…
  3. 3. Which speeds up exact search in low dimensions?

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

Theory

Cover–Hart theorem (1967). As n → ∞ the 1-NN error rate R satisfies R* ≤ R ≤ R*(2 − K R*/(K − 1)) ≤ 2R*, where R* is the Bayes error and K the number of classes. Even one neighbour uses at least half the information available. With k → ∞ and k/n → 0, k-NN is universally consistent: its error tends to R* for any distribution (Stone, 1977).

Rates and dimension. The neighbourhood holding k points has radius about (k/n)^(1/p). For smooth problems the excess error decays like n^(−2/(p+4)), very slowly for large p.

The curse of dimensionality.

  • In high dimensions, distances concentrate: the relative contrast (d_max − d_min)/d_min → 0 for many distributions (Beyer et al., 1999).
  • In exercise 2 it fell from 75 with 2 features to 0.9 with 34.
  • Irrelevant features add noise to every distance, so “nearest” neighbours become essentially random. Accuracy fell from 0.87 to chance (0.50) with 32 irrelevant channels, while k-NN on the 2 relevant features stayed at 0.87.

Remedies:

  • feature selection, or learned metrics (Mahalanobis or LMNN, D4.41);
  • dimensionality reduction (PCA, autoencoders);
  • learned embeddings, which make “similar” meaningful.

Interview questions.

  • Why is k-NN called a lazy learner? All the work happens at prediction time. There is no training phase that builds a model.
  • How does k relate to bias and variance? Small k means low bias and high variance; large k the reverse. The effective number of parameters is about n/k.
📝 Quick check (Level 3)
0/3 answered
  1. 1. Cover–Hart: asymptotic 1-NN error is at most…
  2. 2. In high dimensions, distances to the nearest and farthest points…
  3. 3. Effective number of parameters of k-NN is about…

Level 4: Expert

★★★★★ Expert⏱ 25 minResearchers: original papers and open problems.

Terrain classification and the curse of dimensionality

History.

  • Fix and Hodges (1951) introduced nearest-neighbour discrimination in a US Air Force technical report.
  • Cover and Hart (1967) proved the factor-of-two bound.
  • Stone (1977) proved universal consistency.
  • Beyer et al. (1999) asked “When is nearest neighbor meaningful?” and showed distance concentration.
  • Nearest-neighbour search over learned embeddings now powers retrieval-augmented systems and place recognition in robotics.

Exercise 1. With one feature in millimetres, k = 15 reaches accuracy 0.715 unscaled and 0.840 standardised. Five-fold CV chooses k = 5 (CV error 0.135, against 0.200 for 1-NN).

Exercise 2: soft sand forms a ring. Setup: 2 informative features with a ring-shaped class boundary and 5% label noise, plus d irrelevant channels; 400 training points, k by CV, 6 repetitions. The last column is the relative contrast of distances.

Irrelevant channels d k-NN (all features) k-NN (2 informative only) Logistic regression Relative contrast
0 0.872 0.872 0.513 74.6
2 0.703 0.863 0.503 9.7
8 0.534 0.872 0.498 2.5
32 0.503 0.869 0.512 0.92
  • A curved boundary defeats the linear model (chance level), while k-NN finds it easily.
  • Just 2 irrelevant channels cost 17 points; 8 make k-NN nearly useless. The informative distance is drowned in noise distances.
  • The relative contrast collapses from 75 to 0.9: every training point is almost equally far away.
  • Feature selection restores everything. k-NN is only as good as its notion of distance.
🐍 Exercise 2 (research): irrelevant features and distance concentration
Simulate rover terrain with a ring-shaped class boundary in 2 informative features plus 0–32 irrelevant channels; compare k-NN on all features (k by CV), k-NN on the informative features only, and logistic regression, and measure the relative contrast of distances.

k-NN in AI, robotics and aerospace

  • Case-based diagnosis: retrieve past anomalies most similar to the current telemetry.
  • Place recognition and loop closure: nearest neighbours of image descriptors in SLAM.
  • Retrieval over embeddings: vector search for documents, images and trajectories.
  • Baselines: a sanity check before training complex classifiers.

References

  1. E. Fix, J. L. Hodges (1951). “Discriminatory analysis, nonparametric discrimination: consistency properties.” USAF School of Aviation Medicine, Report 4.
  2. T. M. Cover, P. E. Hart (1967). “Nearest neighbor pattern classification.” IEEE Transactions on Information Theory 13(1).
  3. C. J. Stone (1977). “Consistent nonparametric regression.” Annals of Statistics 5(4).
  4. K. Beyer, J. Goldstein, R. Ramakrishnan, U. Shaft (1999). “When is ‘nearest neighbor’ meaningful?” ICDT.
  5. T. Hastie, R. Tibshirani, J. Friedman (2009). The Elements of Statistical Learning, 2nd ed., chapter 13. Springer.