Distance Measures
Clustering algorithms need a way to quantify how similar or different two data points are. That's exactly what distance measures do - they turn the notion of "similarity" into a concrete number that an algorithm can work with.
Euclidean Distance
The most commonly used distance measure - it's simply the straight-line distance between two points, calculated using the Pythagorean theorem extended to multiple dimensions.
from scipy.spatial import distance
point_a = (2, 4)
point_b = (5, 8)
euclidean = distance.euclidean(point_a, point_b)
print("Euclidean Distance:", euclidean)
Manhattan Distance
Also called "city block" distance, it sums the absolute differences between coordinates, as if you could only move along grid lines (like navigating city blocks) rather than diagonally.
manhattan = distance.cityblock(point_a, point_b)
print("Manhattan Distance:", manhattan)
Minkowski Distance
A generalized form that includes both Euclidean and Manhattan distance as special cases, controlled by a parameter p. When p=1, it becomes Manhattan distance; when p=2, it becomes Euclidean distance.
Cosine Distance
Rather than measuring straight-line distance, cosine distance measures the angle between two vectors - making it especially useful for text data and high-dimensional data where the direction matters more than the magnitude.
Coming Up Next
With a solid grasp of distance measures, you're ready to see how they're combined to merge clusters together through linkage functions.
Working Out the Numbers by Hand
Using the same points, A = (2, 4) and B = (5, 8), the differences are 3 on the first axis and 4 on the second.
- Euclidean: the square root of (3² + 4²) = the square root of 25 = 5.
- Manhattan: 3 + 4 = 7.
- Chebyshev (the largest single difference): 4.
Euclidean is always less than or equal to Manhattan, because a straight line is never longer than a path along the grid. Chebyshev is the limit of Minkowski distance as p grows very large.
from scipy.spatial import distance
a, b = (2, 4), (5, 8)
print(distance.minkowski(a, b, p=1)) # 7.0 (Manhattan)
print(distance.minkowski(a, b, p=2)) # 5.0 (Euclidean)
print(distance.chebyshev(a, b)) # 4
doc1 = [3, 0, 1] # word counts in two short documents
doc2 = [6, 0, 2]
print(distance.cosine(doc1, doc2)) # 0.0: same direction, different length
The cosine result is worth noticing. The second document is simply twice as long, so Euclidean distance would call them far apart, while cosine distance says they talk about the same thing in the same proportions.
Why Scaling Changes Everything
Distance measures add up differences across features, so a feature with large numbers dominates. Compare two customers using age (25 and 35) and annual income (300000 and 310000). The income gap of 10000 swamps the age gap of 10, even if age is the more meaningful difference.
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import pairwise_distances
X = [[25, 300000], [35, 310000], [26, 900000]]
X_scaled = StandardScaler().fit_transform(X)
print(pairwise_distances(X_scaled, metric="euclidean").round(2))
After standardising, each feature contributes on a comparable scale. Do this before k-means, k-nearest neighbours or hierarchical clustering whenever features use different units.
Picking a Measure for Your Data
| Data type | Common choice |
|---|---|
| Continuous, scaled numeric features | Euclidean |
| Grid-like movement or features with outliers | Manhattan |
| Text, embeddings, sparse vectors | Cosine |
| Binary yes/no attributes | Jaccard or Hamming |
| Mixed numeric and categorical | Gower distance (from a separate library) |
Common Mistakes
- Running distance-based algorithms on unscaled data.
- Using Euclidean distance on one-hot encoded categories without thinking about what it means.
- Assuming every algorithm accepts every metric; standard k-means in scikit-learn works with Euclidean distance only.
- Forgetting that in very high dimensions, distances between points become similar, so feature reduction may help.
Seeing the Effect in a Real Model
A useful experiment is to train a k-nearest neighbours classifier twice on the same dataset, once with metric="euclidean" and once with metric="manhattan", using cross-validation for both. Then repeat the test with and without scaling. You will often see that scaling changes accuracy far more than the choice of metric, which is a practical reminder of where to spend effort first.