C · Classic ML
Distance & Similarity
Many models only ask how close two points are; Euclidean distance, Manhattan distance and cosine similarity answer it differently.
Try it: C1 · k-Nearest Neighbours, C2 · k-Means, D2 · Embeddings
Intuition
Many methods never learn weights at all. k-nearest neighbours labels a point by the points closest to it; k-means groups points that are close together; search engines and embeddings find the items most similar to a query. All of them rest on one choice: what "close" means.
Once data is a list of numbers, every example is a point in space, and a distance is a rule for measuring the gap between two points. The everyday straight-line distance is only one option. Walking a city grid, you count blocks instead; comparing documents, you might care about which direction two vectors point rather than how long they are. Different rules give different neighbours, and so different predictions.
The math
For points \(\mathbf{a}, \mathbf{b}\) with \(n\) coordinates:
Minkowski family
\[ d_p(\mathbf{a}, \mathbf{b}) = \Big(\sum_{i=1}^{n} |a_i - b_i|^p\Big)^{1/p} \]- \(p = 1\), Manhattan: \(\sum_i |a_i - b_i|\). Every coordinate's difference counts in full; one large difference is not worse than several small ones adding up to the same.
- \(p = 2\), Euclidean: \(\sqrt{\sum_i (a_i - b_i)^2}\). The ruler distance, and the only one in the family that does not change when the axes are rotated.
- \(p \to \infty\), Chebyshev: \(\max_i |a_i - b_i|\). Only the largest difference counts.
Every \(d_p\) with \(p \ge 1\) is a true metric: it is zero only for identical points, symmetric, and obeys the triangle inequality \(d(\mathbf{a}, \mathbf{c}) \le d(\mathbf{a}, \mathbf{b}) + d(\mathbf{b}, \mathbf{c})\), which fast neighbour-search structures rely on.
Cosine similarity
\[ \cos(\mathbf{a}, \mathbf{b}) = \frac{\mathbf{a}\cdot\mathbf{b}}{\lVert\mathbf{a}\rVert\,\lVert\mathbf{b}\rVert} \]The cosine of the angle between the vectors: 1 for the same direction, 0 for perpendicular, −1 for opposite. It ignores length entirely, which suits word counts (a long document is not a different topic from a short one) and embeddings. For vectors scaled to length 1, \(\lVert\mathbf{a} - \mathbf{b}\rVert^2 = 2 - 2\cos(\mathbf{a}, \mathbf{b})\), so Euclidean distance and cosine rank neighbours the same way.
Other distances
- Hamming: the number of positions where two strings or bit vectors differ.
- Jaccard: \(1 - |A \cap B| / |A \cup B|\) for sets, such as the tags on two items.
- Mahalanobis: \(\sqrt{(\mathbf{a}-\mathbf{b})^\top \Sigma^{-1} (\mathbf{a}-\mathbf{b})}\), Euclidean distance after undoing the data's scale and correlations (\(\Sigma\) is the data's covariance).
- Edit distance: the fewest insertions, deletions and substitutions turning one word into another.
Worked example. \(\mathbf{a} = (1, 1)\), \(\mathbf{b} = (3, 4)\), so the differences are \((2, 3)\).
Manhattan: \(2 + 3 = 5\). Euclidean: \(\sqrt{4 + 9} = 3.61\). Chebyshev: \(\max(2, 3) = 3\). Always \(d_\infty \le d_2 \le d_1\).
Cosine: \(\mathbf{a}\cdot\mathbf{b} = 7\), \(\lVert\mathbf{a}\rVert = 1.414\), \(\lVert\mathbf{b}\rVert = 5\), so \(\cos = 7/7.07 = 0.990\). Far apart, but pointing almost the same way.
Scaling matters
A distance adds up differences across features, so features measured on large scales dominate. Compare houses by floor area in square metres (differences of 50) and number of rooms (differences of 1): rooms barely count. Standardize each feature first, subtracting its mean and dividing by its standard deviation, so every feature contributes on the same scale; or choose the scales on purpose, to say which features should matter more.
Pitfalls
- The curse of dimensionality. In hundreds of dimensions, random points are all nearly the same distance apart, so "nearest" carries little information. Distance methods work best in few dimensions, or on learned representations such as embeddings where the dimensions are meaningful.
- Unscaled features. See above: the most common reason a k-NN or k-means result looks wrong.
- Mixed types. Categories have no natural numeric distance. One-hot encode them, or use a distance designed for mixed data (such as Gower's).
- Cosine on non-negative counts. It ranges only from 0 to 1 there, and an all-zero vector has no direction at all.
History
Hermann Minkowski generalized Euclidean distance to the \(p\)-family around 1900. Prasanta Chandra Mahalanobis introduced his distance in 1936 to compare populations from skull measurements. Richard Hamming defined his in 1950 for error-correcting codes, and Vladimir Levenshtein the edit distance in 1965. Cosine similarity became central to search with Gerard Salton's vector space model of documents in the 1970s.
Connections
Leads to
- k-Nearest Neighboursk-NN is only as good as its distance: which points count as neighbours is decided entirely by it.
- k-Means ClusteringBoth steps are about distance: each point joins its nearest centre, and the mean is the point with the smallest squared distance to the group.
- EmbeddingsSimilarity between embeddings is measured by cosine similarity: the angle, not the length.
Further reading
- Distance metrics, scikit-learn's DistanceMetric referenceEvery common metric with its formula in one table, as the library you would use implements them.
- Cosine similarity (Wikipedia)Why the angle between vectors ignores their length, and its link to correlation.
- On the Surprising Behavior of Distance Metrics in High Dimensional Space (Aggarwal, Hinneburg, Keim, 2001)The paper behind the curse of dimensionality for distances: in many dimensions, nearest and farthest neighbours look alike.