Sub topic 2
Measuring distance between points
What this chapter assumes
You should know basic Python and NumPy, and you should be comfortable with Euclidean distance between two points. You should also recognize scikit-learn's fit and fit_predict style. The previous chapter defined clustering as grouping unlabeled points so that members of a group are closer to each other than to other groups. This chapter makes "closer" precise.
Why distance comes first
Hierarchical clustering and DBSCAN never look at your raw features directly. Both methods only ask questions about distances:
- Agglomerative clustering asks which two clusters are closest, and merges them.
- DBSCAN asks how many points lie within a radius
epsof a given point.
If you change the distance function, you change the answers to both questions, and the clusters change with them. Choosing a metric is therefore a modeling decision, not a detail to leave at the default.
Distance versus dissimilarity
A distance metric d satisfies four rules for all points x, y, z:
d(x, y) >= 0d(x, y) = 0only whenx = yd(x, y) = d(y, x)d(x, z) <= d(x, y) + d(y, z)(the triangle inequality)
A dissimilarity is looser. It only needs to be non-negative and symmetric, and it is larger for less similar objects. Cosine distance is a common example of a dissimilarity that breaks the triangle inequality. Most clustering code accepts dissimilarities, but a few algorithms assume a true metric, as the "Which metric works with which method" section explains.
Common metrics
| Metric | Formula for vectors `x`, `y` | Typical use |
|---|---|---|
| Euclidean | `sqrt(sum((x_i - y_i)^2))` | Continuous features on comparable scales |
| Manhattan (`cityblock`) | `sum(abs(x_i - y_i))` | Grid-like movement, less sensitive to one large difference |
| Chebyshev | `max(abs(x_i - y_i))` | Worst single-feature difference matters |
| Minkowski | `(sum(abs(x_i - y_i)^p))^(1/p)` | Generalizes the three above (p=1, 2, infinity) |
| Cosine | `1 - (x . y) / (norm(x) * norm(y))` | Direction matters, length does not (text vectors) |
| Hamming | fraction of positions that differ | Binary or categorical codes |
Euclidean distance squares each difference, so one feature with a large gap dominates the sum. Manhattan distance grows linearly with each gap, so it tolerates one large gap better. Cosine distance ignores vector length entirely, so a document and a copy of it repeated ten times are at distance 0.
Computing distances in Python
scipy.spatial.distance.cdist computes distances between every pair drawn from two sets of points. The example below compares four metrics on one pair of points.
import numpy as np
from scipy.spatial.distance import cdist
a = np.array([[1.0, 0.0]])
b = np.array([[4.0, 4.0]])
# The coordinate differences are (3, 4).
for metric in ["euclidean", "cityblock", "chebyshev", "cosine"]:
d = cdist(a, b, metric=metric)[0, 0]
print(f"{metric:10s} {d:.4f}")The output is 5.0000 for Euclidean, 7.0000 for cityblock, 4.0000 for Chebyshev and 0.2929 for cosine. The first three measure the same gap three ways. Cosine measures only the angle between the two vectors, so it answers a different question.
Distance matrices
For n points there are n * (n - 1) / 2 distinct pairs. SciPy stores them in two forms:
- The condensed form is a 1-D array of length
n * (n - 1) / 2, produced bypdist. - The square form is an
nbynsymmetric matrix with zeros on the diagonal, produced bysquareform.
import numpy as np
from scipy.spatial.distance import pdist, squareform
from scipy.cluster.hierarchy import linkage
rng = np.random.default_rng(0)
X = rng.normal(size=(6, 2))
condensed = pdist(X, metric="euclidean")
print(condensed.shape) # (15,)
D = squareform(condensed)
print(D.shape) # (6, 6)
print(np.allclose(D, D.T), np.allclose(np.diag(D), 0)) # True True
Z = linkage(condensed, method="average")
print(Z.shape) # (5, 4)Notice that linkage accepted the condensed array. When linkage receives a 1-D array it treats it as precomputed distances. When it receives a 2-D array it treats it as raw observations.
Which metric works with which method
The metric you can use depends on the algorithm and the linkage.
- SciPy
linkagewith raw data. Passmetric="..."for single, complete, average and other linkages. Ward, centroid and median linkage are defined only for Euclidean distance. SciPy applies them to Euclidean geometry regardless of what you intended. - scikit-learn
AgglomerativeClustering. The metric argument ismetricin scikit-learn 1.2 and later, andaffinityin older versions. Withlinkage="ward"only Euclidean is allowed. With other linkages you can use any metric, including"precomputed". - scikit-learn
DBSCAN. Themetricargument accepts any metric that the neighbor search supports, including"precomputed".epsis then expressed in that metric's units. Anepsof 0.5 means something very different for Euclidean and cosine distance.
The following example clusters the same precomputed matrix with both methods.
import numpy as np
from scipy.spatial.distance import pdist, squareform
from sklearn.cluster import AgglomerativeClustering, DBSCAN
rng = np.random.default_rng(1)
X = np.vstack([
rng.normal(loc=0.0, scale=0.3, size=(10, 2)),
rng.normal(loc=5.0, scale=0.3, size=(10, 2)),
])
D = squareform(pdist(X, metric="cityblock"))
agg = AgglomerativeClustering(
n_clusters=2, metric="precomputed", linkage="average"
).fit(D)
db = DBSCAN(eps=1.5, min_samples=3, metric="precomputed").fit(D)
print(agg.labels_)
print(db.labels_)Here both estimators receive the square matrix, which is what scikit-learn expects for "precomputed". The two blobs are about 10 units apart in Manhattan distance, so with this seed both methods should separate them. The eps of 1.5 is in Manhattan units.
Common errors and gotchas
Features on different scales. Suppose one column is age (about 20 to 70) and another is income (about 20,000 to 200,000). Euclidean distance is then almost entirely income, and age has no effect. The next chapter covers scaling. For now, remember that any metric built from raw differences inherits this problem.
Distances lose contrast in high dimensions. As the number of features grows, the nearest and farthest neighbors of a point become almost equally far away. This is called distance concentration. The following code shows it for random data.
import numpy as np
from scipy.spatial.distance import pdist
rng = np.random.default_rng(0)
for d in [2, 10, 100, 1000]:
X = rng.uniform(size=(200, d))
dist = pdist(X)
print(d, round(dist.max() / dist.min(), 2))The printed ratio of the largest to the smallest distance falls toward 1 as d increases. When all pairs look equally far apart, "closest cluster" and "points within eps" lose their meaning. Reducing dimensionality first, for example with PCA, often helps.
Mixing categorical and numeric columns. Euclidean distance on one-hot encoded columns treats a category change as a distance of about 1.4 (sqrt(2)), which may not match your intent. Gower distance or a hand-built dissimilarity matrix is usually a better fit. Pass the result with metric="precomputed".
Missing values. Neither SciPy nor scikit-learn distance functions accept nan in the input in general. Impute or drop rows before computing distances.
Memory. The full distance matrix for n points holds about n^2 floats. For 50,000 points in 64-bit floats that is about 20 GB. Precomputing is practical for a few thousand points. For more, let the estimator compute distances itself.
Exercise
You have 1,000 points. (a) How many entries does the condensed distance array from pdist have? (b) A colleague builds the 1,000 by 1,000 square matrix D with squareform and calls linkage(D, method="average"). What goes wrong, and how do you fix it?
Show answer
(a) 1000 * 999 / 2 = 499,500 entries. (b) linkage receives a 2-D array, so it treats it as an observation matrix of 1,000 points with 1,000 features each, and clusters those rows instead of using the values as distances. No error is raised, so the mistake is silent. Fix it by passing squareform(D) (the condensed form), or by passing the raw data X with the metric argument.