Distance measures and distance-based classifiers
Distance measures quantify how different two feature vectors are; distance-based classifiers (nearest neighbour, k-NN) use these measures to assign class labels based on nearby examples.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Distance measures and distance-based classifiers are used whenever decisions are made by comparing feature vectors: similarity search, anomaly detection, biometric matching, k-NN classification in supervised learning, and clustering initialization. Engineers use them to build simple, interpretable classifiers and as building blocks inside more complex systems (feature selection, metric learning, clustering).
Key ideas
- Non-negativity: D(x,y) ≥ 0.
- Identity of indiscernibles: D(x,y) = 0 if and only if x = y.
- Symmetry: D(x,y) = D(y,x).
- Triangle inequality: D(x,z) ≤ D(x,y) + D(y,z). If a distance does not satisfy one of these (for example, cosine similarity fails identity of indiscernibles; and the common 1 - cosine 'distance' fails the triangle inequality) then it is not a metric.
- Minkowski family: general L_p distances. Special cases include Euclidean distance (L_2), Manhattan distance (L_1), and Chebyshev distance (L_∞). These are metrics on R^d.
- Cosine similarity measures the cosine of angle between vectors: it is a similarity, not a distance. To use it as a distance you convert: D_cos(x,y) = 1 - cosine(x,y) or D_angle(x,y) = arccos(cosine(x,y)). The latter is a proper metric (angular distance) on the unit sphere (i.e., when vectors are non-zero and normalized to unit length).
- Mahalanobis distance accounts for feature scaling and correlation using a positive-definite covariance matrix S: D_M(x,y) = sqrt((x-y)^T S^{-1} (x-y)). It is scale-invariant and is useful when features are correlated or have different variances.
- Nearest neighbour classifier (1-NN): given a labelled training set { (x_i, y_i) }, classify a query x_q by finding training example x_i with smallest distance to x_q and assign its label y_i. This is non-parametric: no explicit training of parameters other than storing examples.
- k-Nearest Neighbour (k-NN): look at the k closest training examples and choose the majority label among them. Common variants: distance-weighted voting (closer neighbours get higher weight), tie-breaking rules (use smaller k, random among tied classes, or use weighted vote).
- Asymptotic consistency of k-NN (statement often asked in exams): If data are i.i.d., and as n → ∞ we choose k = k(n) with k → ∞ and k/n → 0, then k-NN classifier risk converges to the Bayes risk (k-NN is Bayes-consistent). Assumptions: feature space finite-dimensional, class-conditional distributions fixed, and ties handled in a measurable way.
- Curse of dimensionality: in high d, distances concentrate (relative differences shrink). Consequences: nearest neighbours become less meaningful, need more data, or use dimensionality reduction/metric learning.
- Feature scaling / normalization: important before applying distance measures. Common methods: min-max scaling to [0,1], and z-score standardization (subtract mean, divide by standard deviation). If using Mahalanobis with covariance S, scaling is implicit in S.
Diagram to draw (for exam answers): draw 2D plane, plot three training points labelled A, B, B, and a query point Q. Draw circles of increasing radius around Q until the first neighbour, then the three nearest neighbours for k=3; label distances and show majority vote result.
Formulas
Euclidean: D_2(x,y) = sqrt( sum_{i=1..d} (x_i - y_i)^2 ) — x_i, y_i are feature i; unit = same as feature units (m, s etc.); applies to real-valued features.
Manhattan (L1): D_1(x,y) = sum_{i=1..d} |x_i - y_i| — units same as features; useful when axis-aligned differences matter.
Chebyshev (L_infty): D_inf(x,y) = max_{i=1..d} |x_i - y_i| — unit = feature units; measures largest coordinate difference.
Minkowski (general): D_p(x,y) = ( sum_{i=1..d} |x_i - y_i|^p )^(1/p), p >= 1 — recovers L1, L2, L_infty as special cases.
Hamming (binary/categorical): D_H(x,y) = sum_{i=1..d} I(x_i != y_i) — counts mismatched coordinates; metric on binary vectors.
Cosine similarity: cos(x,y) = (x · y) / (||x||_2 ||y||_2) — unitless; range [-1,1]; measures angle, not magnitude.
Cosine distance (common): D_cos(x,y) = 1 - cos(x,y) — unitless; small = similar; not a metric in general (triangle inequality can fail).
Mahalanobis: D_M(x,y) = sqrt( (x - y)^T S^{-1} (x - y) ) — S is positive-definite covariance matrix (units squared); interpretable as distance in standard-deviation units.
Z-score (standardization): z_i = (x_i - mu_i) / sigma_i — mu_i mean of feature i, sigma_i its standard deviation; unitless after transform.
Min-max scaling to [0,1]: x'_i = (x_i - min_i) / (max_i - min_i) — unitless; preserves ordering.
For classifiers:
1-NN decision: y_hat(x_q) = y_j where j = argmin_i D(x_q, x_i) — assign label of nearest neighbour.
k-NN (majority): collect K = {indices of k smallest distances}; y_hat(x_q) = argmax_c sum_{i in K} I(y_i = c) — I is indicator.
Worked examples
Example 1 — Euclidean and Manhattan distances (2D, units metres)
Problem: Points A = (1 m, 2 m), B = (4 m, 6 m), C = (2 m, 1 m). Compute D_2(A,B), D_1(A,B), and D_2(A,C).
Step 1 formula: D_2(x,y) = sqrt((x1-y1)^2 + (x2-y2)^2)
Numbers: (x=A, y=B): (1-4)^2 + (2-6)^2 = (-3)^2 + (-4)^2 = 9 + 16 = 25.
So D_2(A,B) = sqrt(25) = 5 m.
Step 2 formula: D_1(x,y) = |x1-y1| + |x2-y2|
Numbers: |1-4| + |2-6| = 3 + 4 = 7 m.
Step 3 D_2(A,C): (1-2)^2 + (2-1)^2 = (-1)^2 + 1^2 = 1 + 1 = 2 → D_2(A,C) = sqrt(2) = 1.414 m.
Example 2 — Mahalanobis distance (2D)
Problem: Let x = [2, 3]^T, mu = [0,0]^T, and covariance matrix S = [[2, 0.5], [0.5, 1]] (units m^2). Compute Mahalanobis distance D_M(x, mu).
Step 1 formula: D_M(x,mu) = sqrt( (x-mu)^T S^{-1} (x-mu) ).
Step 2 invert S. Determinant det(S) = 21 - 0.50.5 = 2 - 0.25 = 1.75.
S^{-1} = (1/det) * [[1, -0.5],[-0.5, 2]] = (4/7) * [[1, -1/2],[-1/2, 2]].
Step 3 compute quadratic form: S^{-1} (x-mu) = S^{-1} [2,3]^T = [2/7, 20/7]^T ≈ [0.285714, 2.857143]^T.
Dot with (x-mu) gives (2)(2/7) + (3)(20/7) = 64/7 ≈ 9.142857.
Step 4 sqrt: D_M = sqrt(64/7) = 8 / sqrt(7) ≈ 3.024 (interpretable as ~3.024 standard-deviation units).
Note: Mahalanobis here is unitless after scaling; interpret as number of standard deviations.
Example 3 — k-NN classification (Euclidean) Training set (labels): A1 = (1,1) label A A2 = (2,1) label A B1 = (4,4) label B B2 = (5,5) label B Query q = (3,2). Use k = 3. Step 1 compute Euclidean distances to q: D(q,A1) = sqrt((3-1)^2 + (2-1)^2) = sqrt(4 + 1) = sqrt(5) = 2.236. D(q,A2) = sqrt((3-2)^2 + (2-1)^2) = sqrt(1 + 1) = sqrt(2) = 1.414. D(q,B1) = sqrt((3-4)^2 + (2-4)^2) = sqrt(1 + 4) = sqrt(5) = 2.236. D(q,B2) = sqrt((3-5)^2 + (2-5)^2) = sqrt(4 + 9) = sqrt(13) = 3.606. Step 2 pick k=3 smallest distances: A2 (1.414, A), A1 (2.236, A), B1 (2.236, B). Majority: A appears twice, B once → classify q as A. If there were a tie, state tie-breaking rule (choose smallest total distance among tied classes or break randomly).
Common mistakes
- Inverting a singular covariance matrix for Mahalanobis (S must be positive-definite); regularize by adding small λI if needed.
- Using odd/even k carelessly: with even k in two-class problems ties are likely — explain tie-breaking.
- Ignoring curse of dimensionality: reporting nearest-neighbour results without commenting on high-d effects.
- Misapplying Manhattan vs Euclidean: Manhattan is L1; do not square terms or take sqrt.
For your exam
Types of questions you will see:
- Definitions: define metric, Euclidean distance, Mahalanobis distance, k-NN, and state metric axioms.
- Short notes: compare L1 vs L2, explain feature scaling, describe Mahalanobis advantages.
- Derivations: show that Minkowski with p ≥ 1 satisfies triangle inequality (outline Minkowski inequality), derive Mahalanobis distance from whitening transform.
- Numericals: compute distances (Euclidean, Manhattan, Mahalanobis) for small vectors; invert 2x2 covariance matrix by hand.
- Programs: implement k-NN on small dataset; remember to include normalization and distance function.
- Diagrams: draw 2D example with nearest neighbours and decision boundary sketch for 1-NN. What full-marks answers include:
- Clear definitions with bold naming, units and assumptions stated.
- Correct formula written explicitly and applied step-by-step with units kept.
- For numericals: show matrix inversion steps (2x2), list intermediate numbers, final answer bolded with units.
- For theory: state assumptions (i.i.d., positive-definite covariance), and mention limitations (curse of dimensionality).
Quick check
- State the four axioms of a metric in one line each.
- Given x = (1,0), y = (0,1) compute Euclidean and Manhattan distances.
- In k-NN, what happens if k increases to n (number of training samples)? Answers: 1) Non-negativity; identity of indiscernibles; symmetry; triangle inequality. 2) Euclidean = sqrt(2) ≈ 1.414, Manhattan = 2. 3) As k → n, classifier tends to predict the majority class in the training set (high bias, low variance).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?