Sub topic 9
Cost and limits of hierarchical clustering
This chapter assumes you can run linkage and AgglomerativeClustering, and that you know what the linkage criteria (single, complete, average, Ward) do. You also need basic NumPy. The goal is to learn where hierarchical clustering stops being practical and how to recognize its characteristic failures.
Where the cost comes from
Agglomerative clustering starts with every point as its own cluster and merges the closest pair until one cluster remains. To find "the closest pair" it needs the distance between every pair of points. That requirement drives both the memory cost and the time cost.
Memory: the distance matrix
For n points there are n * (n - 1) / 2 pairwise distances. SciPy stores them as a condensed vector of 64-bit floats, 8 bytes each. Memory therefore grows with the square of n.
| Points (n) | Pairwise distances | Approximate memory |
|---|---|---|
| 1,000 | 499,500 | 4 MB |
| 10,000 | about 50 million | 0.4 GB |
| 50,000 | about 1.25 billion | 10 GB |
| 100,000 | about 5 billion | 40 GB |
These figures cover only the condensed matrix. linkage also needs working space, and a full square matrix is 2 times larger. In practice, 20,000 to 30,000 points is where many laptops run out of memory.
Time
A naive implementation rescans the distance matrix at every merge, which costs O(n³). SciPy uses faster algorithms for its linkage methods, such as nearest-neighbor chains and a specialized single-linkage algorithm. These bring the time to O(n²) for single, complete, average, and Ward linkage. That is still quadratic, so doubling the data roughly quadruples the run time. The centroid and median methods can be slower in the worst case.
The following script measures the growth on your machine.
import time
import numpy as np
from scipy.cluster.hierarchy import linkage
from sklearn.datasets import make_blobs
def condensed_gb(n):
return n * (n - 1) / 2 * 8 / 1e9
for n in [500, 1000, 2000, 4000]:
X, _ = make_blobs(n_samples=n, centers=5, random_state=0)
start = time.perf_counter()
linkage(X, method="ward")
elapsed = time.perf_counter() - start
print(f"n={n:5d} time={elapsed:6.3f}s condensed matrix={condensed_gb(n):.4f} GB")Each doubling of n should raise the time by a factor near 4. Compare that with k-means, whose cost grows roughly linearly in n for fixed k.
Merges cannot be undone
Hierarchical clustering is greedy. At each step it takes the locally best merge and never revisits it. If a noisy point causes an early wrong merge, every later level of the tree inherits that mistake. Algorithms like k-means can reassign points on later iterations, but a dendrogram cannot.
Two consequences follow:
- The tree is only as good as its first merges, which happen among the most closely spaced points. Those are the points most affected by measurement noise.
- Cutting the tree gives a flat clustering that is consistent with the hierarchy. It is not necessarily the best flat clustering for that
k.
Failure modes by linkage
Each linkage criterion has a characteristic way of going wrong.
| Linkage | Typical failure | Why |
|---|---|---|
| Single | Chaining: a thin line of points joins two real clusters. Outliers form singleton clusters. | Cluster distance is the closest pair, so one bridge point is enough. |
| Complete | Splits large or elongated clusters. Sensitive to outliers. | Cluster distance is the farthest pair, so one distant point inflates it. |
| Average | A compromise, but still biased toward similar spread. | It averages all pairs, so extremes matter less but still count. |
| Ward | Favors compact, similar-sized, roughly spherical clusters. Requires Euclidean distance. | It minimizes the growth in within-cluster variance. |
The next example builds two compact blobs and one far outlier. It then asks for two clusters.
import numpy as np
from sklearn.cluster import AgglomerativeClustering
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=200, centers=[[0, 0], [6, 0]],
cluster_std=0.5, random_state=0)
X = np.vstack([X, [[0, 12]]]) # one outlier far above the first blob
for link in ["single", "ward"]:
labels = AgglomerativeClustering(n_clusters=2, linkage=link).fit_predict(X)
print(link, sorted(np.bincount(labels)))Single linkage isolates the outlier, giving sizes [1, 200]. Ward absorbs the outlier into the nearby blob, giving sizes close to [100, 101]. Neither behavior is wrong in the abstract, but you need to know which one you asked for.
Other metric and linkage constraints
- Ward, centroid, and median linkage in SciPy are only defined for Euclidean distance. Passing a precomputed non-Euclidean matrix to them gives meaningless results.
- Centroid and median linkage can produce inversions. A later merge happens at a smaller distance than an earlier one, so the dendrogram has branches that go back down. Most people use Ward or average linkage instead.
- Every linkage inherits the weaknesses of the distance metric. If features are unscaled or the metric is a poor fit for the data, no linkage will fix that.
Interface and interpretation limits
- No labels for noise. Every point ends up in some cluster. An outlier either becomes a singleton or gets absorbed into a cluster and distorts it. DBSCAN, covered later, handles this differently.
- No
predictfor new data.AgglomerativeClusteringoffersfit_predictbut nopredict. A tree is built for one fixed dataset. To label new points you must refit, or train a classifier on the cluster labels, or assign each new point to the nearest existing cluster yourself. - You still choose a cut. The dendrogram does not tell you the number of clusters. Large vertical gaps are a heuristic, and for data without clear structure there may be no obvious gap.
- Large dendrograms are unreadable. With thousands of leaves the plot becomes a smear. Use
dendrogram(Z, truncate_mode="lastp", p=30)to show only the last 30 merged clusters.
Ways to reduce the cost
Three practical mitigations:
- Subsample. Cluster a random sample of a few thousand points, then assign the remaining points to the nearest cluster by centroid or with a classifier.
- Compress first. Run k-means with a large
k(for example 500), then build the hierarchy on the 500 centers. This keeps the tree but loses detail below the compression level. - Add connectivity. Scikit-learn lets you pass a sparse neighbor graph so only neighboring clusters can merge. This reduces work and also helps the clusters follow the shape of the data.
from sklearn.cluster import AgglomerativeClustering
from sklearn.datasets import make_moons
from sklearn.neighbors import kneighbors_graph
X, _ = make_moons(n_samples=1000, noise=0.05, random_state=0)
connectivity = kneighbors_graph(X, n_neighbors=10, include_self=False)
model = AgglomerativeClustering(
n_clusters=2, linkage="average", connectivity=connectivity
)
labels = model.fit_predict(X)
print(sorted(set(labels)))The graph limits merges to points that are neighbors, which encodes a local structure assumption. If n_neighbors is too small, the graph may split into disconnected parts and sklearn will warn you about it.
Quick checklist
- Estimate
n * (n - 1) / 2 * 8bytes before you calllinkage. - Scale features first, since distances drive every merge.
- Check the dendrogram for singleton leaves attached high up. They usually mark outliers.
- Compare two linkages on the same data. If the clusters differ a lot, the structure is weak or one criterion's bias is showing.
Exercise
You have 80,000 customer records with 10 scaled numeric features. A colleague wants to call scipy.cluster.hierarchy.linkage on them. Estimate the memory for the condensed distance matrix, say whether this is a good idea, and name two alternatives.
Show answer
The condensed matrix has 80,000 * 79,999 / 2, about 3.2 billion, entries. At 8 bytes each that is about 25.6 GB, before working space. This is not practical on most machines, and run time would also be quadratic. Alternatives: cluster a random subsample of a few thousand points and assign the rest to the nearest cluster; run k-means with a large k and build the hierarchy on the centers; or use a method designed for large data, such as BIRCH or a connectivity-constrained AgglomerativeClustering.
Exercise
Single linkage with n_clusters=2 returns one cluster of size 1 and one of size 200 on a dataset with two obvious blobs and one outlier. Explain why, and name a linkage that would likely give two balanced clusters.
Show answer
Single linkage merges by the closest pair of points, and the last merge it undoes is the one at the largest distance. The outlier is farther from either blob than the blobs are from each other, so cutting the tree into two clusters separates the outlier alone. Ward linkage minimizes the increase in variance, so it merges the outlier into a nearby blob early and keeps the two blobs as the final two clusters. Average or complete linkage may also work, depending on how far the outlier is.