Sub topic 7
Cutting the tree into flat clusters
This chapter assumes you can read a dendrogram and know what a linkage matrix is. A dendrogram holds every possible clustering from n singletons down to one cluster. To get labels you must cut it. Cutting means choosing a rule that turns the tree into a flat partition.
Two ways to cut
A horizontal line drawn across the dendrogram at height h splits the tree. Every branch the line crosses becomes one cluster. Lower lines give more clusters, and higher lines give fewer.
You can pick the cut in two ways:
- By distance. Choose a merge distance
t. Any merge abovetis undone. - By count. Choose the number of clusters
k. The cut is placed so that exactlykbranches remain (at mostkwhen ties exist).
Cutting just below the root leaves two clusters: {A, B} and {C, D}.
Cutting with scipy
fcluster applies a cut to the linkage matrix. The criterion argument selects the rule.
import numpy as np
from scipy.cluster.hierarchy import linkage, fcluster
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=30, centers=3, random_state=0)
Z = linkage(X, method="ward")
# Cut by count: at most 3 clusters.
by_count = fcluster(Z, t=3, criterion="maxclust")
# Cut by height: undo every merge above distance 10.
by_height = fcluster(Z, t=10, criterion="distance")
print(np.unique(by_count))
print(np.unique(by_height))Labels from fcluster start at 1, not 0. This differs from scikit-learn, so subtract 1 if you mix the two.
Choosing where to cut
A good cut sits in a large vertical gap. A big gap means the algorithm had to jump a long distance to join the next clusters, so the clusters below the gap are well separated. The last column of Z that holds merge distances makes this easy to check numerically.
import numpy as np
from scipy.cluster.hierarchy import linkage
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=30, centers=3, random_state=0)
Z = linkage(X, method="ward")
heights = Z[:, 2]
gaps = np.diff(heights)
i = int(np.argmax(gaps))
# Merge i is the last merge before the biggest jump,
# so cutting between heights[i] and heights[i + 1] is a candidate.
n_clusters = len(Z) - i
print(n_clusters, heights[i], heights[i + 1])With n points there are n − 1 merges. After merge index i (zero-based), n − (i + 1) clusters remain, which equals len(Z) - i. The largest gap is only a heuristic. Treat it as a candidate, then look at the dendrogram and the data.
Common errors
- Cutting by distance across different linkages. Heights mean different things for single, average and Ward linkage. A
tthat works for one will not carry over to another. - Forgetting that scaling changes heights. If you rescale features, distances change and so does every sensible
t. - Expecting equal sizes. A cut produces whatever sizes the tree implies. Single linkage often returns one huge cluster plus tiny ones.
- Reading the gap rule as proof. Data without real structure still has a largest gap.
Exercise
A linkage matrix Z has 49 rows. You cut it with criterion="maxclust" and t=5. How many points were clustered, and what is the largest label you expect?
Show answer
There are n − 1 merges, so 49 rows means 50 points. Cutting at t=5 gives five clusters, and fcluster labels start at 1, so the largest label is 5.