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

Weighted k-NN and Distance Metrics

Nearest-neighbour methods are only as good as their notion of distance. This page compares the common metrics: Euclidean, Manhattan and the Minkowski family, Chebyshev, Mahalanobis (which accounts for scale and correlation), cosine (which ignores magnitude), and Hamming (for binary or categorical codes). It also covers distance-weighted voting, metric properties, and when each metric matches the structure of the data. In the exercises you implement all the metrics, their vectorised pairwise versions and weighted k-NN; then you build three telemetry scenarios (common-mode sensor noise, spectra with varying brightness, and glitch-prone readings) and show that a different metric wins each one.

Level 0: Foundation

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

Close in what sense?

Two spectra with the same shape but different brightness: close or far? Two sensor readings that differ only by noise that all sensors share: close or far? The answer depends on the distance metric. Euclidean distance measures straight-line gaps. Manhattan adds up gaps along each axis. Mahalanobis rescales by how the data naturally vary. Cosine looks only at direction. Hamming counts mismatched bits. Pick the metric that matches what “similar” means for your data, and k-NN works. Pick the wrong one, and it fails.

Distance metrics: who is your nearest neighbour?
AB
metricd(probe, A)d(probe, B)nearer
Minkowski p = 21.7031.552B
Euclidean (p = 2)1.7031.552B
Manhattan (p = 1)2.4001.900B
Mahalanobis ρ = 0.81.3043.060A
cosine (from (1, 0.15))0.1490.083B
Unit balls: a diamond for p = 1, a circle for p = 2, a square as p → ∞; Mahalanobis gives an ellipse stretched along the correlated direction, so a point along the 'cloud' is closer than one across it. Cosine ignores length entirely (wedges show angles within cosine distance 0.05 and 0.2 of the x-axis). Change the metric and watch A and B swap places.
Why engineers care

Similarity search over spectra, telemetry snapshots, fault signatures and image descriptors underlies diagnostics, anomaly detection and place recognition. Choosing (or learning) the right metric is often worth more than any amount of model tuning.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Which metric ignores the length (brightness) of vectors?
  2. 2. Which metric accounts for correlated features?
  3. 3. The Manhattan unit ball in 2-D is a…

Level 1: Beginner

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

Distances by hand

Take a = (0, 0) and b = (3, 4).

Metric Formula Value
Manhattan (p = 1) 3 + 4 7
Euclidean (p = 2) √(9 + 16) 5
Chebyshev (p = ∞) max(3, 4) 4

Mahalanobis with Σ = diag(4, 1):

  • (2, 0) is at distance √(4/4) = 1;
  • (0, 2) is at distance √(4/1) = 2.

The first feature varies twice as much naturally, so a difference of 2 along it counts as only 1 unit.

Cosine distance 1 − cos θ:

  • (1, 2) and (10, 20) are at distance 0 (same direction);
  • (1, 0) and (−1, 0) are at distance 2 (opposite directions).

Hamming between 10110 and 10011: 2 of 5 positions differ, so 0.4.

Distance-weighted vote. Neighbours of the query 0.1 are at 0 (class 0, d = 0.1), 1 (class 1, d = 0.9) and 1.1 (class 1, d = 1.0). The plain vote is 2–1 for class 1. Weighting by 1/d gives 10 against 2.1, so the very close point wins for class 0.

The steps in plain English:

  1. Ask what similarity means physically: same shape (cosine), same values with correlated noise (Mahalanobis), robust to spikes (Manhattan), same codes (Hamming).
  2. Scale features appropriately (standardise for Euclidean and Manhattan; Mahalanobis scales itself).
  3. Compute distances and take the k nearest.
  4. Vote, optionally weighting by 1/distance.
  5. Compare metrics by cross-validation.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Chebyshev distance from (0, 0) to (3, 4)?
  2. 2. Cosine distance between (1, 2) and (10, 20)?
  3. 3. Hamming distance between 10110 and 10011?

Level 2: Intermediate

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

The metrics

Minkowski: d_p(a, b) = (Σ|aⱼ − bⱼ|^p)^(1/p). p = 1 is Manhattan, p = 2 Euclidean, p → ∞ Chebyshev. Below p = 1 the triangle inequality fails.

Mahalanobis: d(a, b) = √((a − b)ᵀΣ⁻¹(a − b)). This equals Euclidean distance after whitening with L = chol(Σ⁻¹), so it can reuse the fast Euclidean code. Σ is usually the pooled within-class covariance (as in LDA).

Cosine distance: 1 − aᵀb/(‖a‖‖b‖). It is not a true metric (the triangle inequality fails), but on unit-normalised vectors it is a monotone function of Euclidean distance: ‖â − b̂‖² = 2(1 − cos θ).

Hamming: the fraction of positions that differ. For binary vectors it is proportional to both Manhattan and squared Euclidean distance.

Other useful distances:

  • Jaccard (sets);
  • Gower (mixed types);
  • dynamic time warping (sequences);
  • earth mover’s distance (histograms).

Weighting: uniform votes, or wᵢ = 1/dᵢ (or a kernel such as e^(−dᵢ²/h²)).

from sklearn.neighbors import KNeighborsClassifier
KNeighborsClassifier(n_neighbors=5, metric="manhattan", weights="distance")
KNeighborsClassifier(n_neighbors=5, metric="mahalanobis", metric_params={"VI": np.linalg.inv(S)}, algorithm="brute")
KNeighborsClassifier(n_neighbors=5, metric="cosine", algorithm="brute")

Use Mahalanobis for correlated or differently scaled continuous features, cosine for directional data (spectral shapes, text and embedding vectors), Manhattan for robustness to occasional large deviations, and Hamming for binary codes. Learn a metric (NCA, LMNN) when none of these fits.

🐍 Exercise 1: distance metrics and weighted k-NN
Implement Minkowski, Chebyshev, Mahalanobis, cosine and Hamming distances, their vectorised pairwise forms (Mahalanobis via whitening), and k-NN with a choice of metric and uniform or 1/distance weighting; check hand values, agreement between pairwise and scalar versions, and a vote that distance weighting reverses.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Mahalanobis distance equals Euclidean distance after…
  2. 2. For unit vectors, ‖â − b̂‖² equals…
  3. 3. Minkowski with p below 1 fails…

Level 3: Advanced

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

Theory

Metric axioms:

  • d(a, b) ≥ 0, with equality if and only if a = b;
  • symmetry;
  • the triangle inequality.

Search structures (k-d trees, ball trees, D4.43) rely on the triangle inequality for pruning. Cosine distance does not satisfy it, so use angular distance arccos(cos θ)/π or normalise and use Euclidean.

Robustness. In p = 1, a single coordinate’s deviation contributes linearly. In p = 2 it contributes quadratically, so a glitch in one feature can dominate. That is why Manhattan did better with spiky telemetry in exercise 2. In high dimensions, lower p also preserves more relative contrast (Aggarwal et al., 2001).

Metric learning. Learn a Mahalanobis matrix M = LᵀL so that same-class neighbours are close and different-class ones far:

  • NCA (Goldberger et al., 2005) maximises expected leave-one-out accuracy;
  • LMNN (Weinberger and Saul, 2009) uses large-margin triplet constraints;
  • Siamese and triplet networks (E15) learn non-linear embeddings.

Weighted voting reduces the sensitivity to k and gives smoother probability estimates. With 1/d weights, k-NN interpolates the training data (a training point is its own neighbour at distance 0).

Interview questions.

  • When should you prefer cosine to Euclidean? When magnitude is a nuisance (overall intensity, document length, embedding norms) and direction carries the information.
  • Why might Mahalanobis k-NN be worse than Euclidean? If Σ is poorly estimated (few samples, many features), its inverse amplifies noise directions. Shrink Σ (D2.28).
📝 Quick check (Level 3)
0/3 answered
  1. 1. Ball trees need the metric to satisfy…
  2. 2. LMNN learns…
  3. 3. In high dimensions, lower-p Minkowski metrics tend to…

Level 4: Expert

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

Three scenarios, three winners

History.

  • Mahalanobis (1936) introduced his distance for anthropometric data.
  • Minkowski (1910) defined the p-norms.
  • Hamming (1950) introduced his distance for error-correcting codes.
  • Salton’s vector-space model (1975) made cosine similarity the standard for text.
  • Aggarwal, Hinneburg and Keim (2001) studied metric behaviour in high dimensions.
  • Metric learning (Xing et al., 2002; NCA, 2005; LMNN, 2009) made the metric a learned component.

Exercise 1. Manhattan 7, Euclidean 5, Chebyshev 4 for (3, 4); Mahalanobis 1 and 2 under diag(4, 1); cosine 0 and 1 for parallel and perpendicular vectors; Hamming 0.5. The pairwise matrices match the scalar functions, and 1/d weighting reverses a 2–1 vote.

Exercise 2: three telemetry scenarios. Setup: 5-NN, 100 training samples, 5 repetitions. The table shows test accuracy.

Scenario Euclidean Manhattan Mahalanobis Cosine
Correlated noise (shared common-mode noise) 0.647 0.631 0.831 0.775
Brightness varies 25-fold (spectral shape) 0.937 0.965 0.810 1.000
Spiky glitches (10% of readings) 0.610 0.647 0.608 0.564
  • Common-mode noise: only Mahalanobis “subtracts” the shared noise, using the estimated covariance. It gains 18 points over Euclidean.
  • Varying brightness: cosine compares shapes and is perfect. Mahalanobis does worst, because its covariance is dominated by brightness variation.
  • Glitches: Manhattan’s linear penalty limits each glitch’s influence, so it is best, though all metrics struggle.
  • No metric wins everywhere. Match the metric to the physics, or validate several by CV.
🐍 Exercise 2 (research): matching the metric to the data
Simulate three classification scenarios — sensors with shared common-mode noise, spectra with 25-fold brightness variation, and glitch-prone readings — and compare 5-NN with Euclidean, Manhattan, Mahalanobis (pooled within-class covariance) and cosine distances.

Distance metrics in AI, robotics and aerospace

  • Spectral matching: mineral and material identification by spectral angle (cosine).
  • Telemetry anomaly detection: Mahalanobis distance to the nominal cluster.
  • Fault signatures: Hamming or Jaccard distances between alarm patterns.
  • Embedding search: cosine similarity between learned representations for retrieval and place recognition.

References

  1. P. C. Mahalanobis (1936). “On the generalized distance in statistics.” Proceedings of the National Institute of Sciences of India 2.
  2. C. C. Aggarwal, A. Hinneburg, D. A. Keim (2001). “On the surprising behavior of distance metrics in high dimensional space.” ICDT.
  3. J. Goldberger, S. Roweis, G. Hinton, R. Salakhutdinov (2005). “Neighbourhood components analysis.” NeurIPS.
  4. K. Q. Weinberger, L. K. Saul (2009). “Distance metric learning for large margin nearest neighbor classification.” JMLR 10.
  5. M.-M. Deza, E. Deza (2016). Encyclopedia of Distances, 4th ed. Springer.