Sub topic 7
Cutting the Tree into Flat Clusters
This chapter assumes you can read a linkage matrix and a dendrogram, and that you have used scipy's linkage and scikit-learn's AgglomerativeClustering. Hierarchical clustering produces a tree, but most applications need one label per point. Cutting the tree turns the hierarchy into that flat clustering. The cut is a modeling decision, and a different cut can give you a quite different answer from the same tree.
What a cut does
A dendrogram is a record of n-1 merges, each at a height (the merge distance). A horizontal cut at height t keeps every merge below t and discards every merge above it. The subtrees that hang below the cut line become the clusters.
Two consequences follow:
- Cuts are nested. Raising the cut merges clusters and never splits them. A point can't move between clusters as you change
t. - The number of clusters and the cut height determine each other. Choosing one fixes the other, up to ties.
Cutting with scipy's fcluster
fcluster(Z, t, criterion=...) takes the linkage matrix and a threshold whose meaning depends on the criterion.
| Criterion | Meaning of `t` | Typical use |
|---|---|---|
| `maxclust` | Upper bound on the number of clusters | You know how many groups you want |
| `distance` | Maximum cophenetic distance inside a cluster | You know what "too far apart" means in your units |
| `inconsistent` | Maximum inconsistency coefficient | Clusters with different density levels |
import numpy as np
from scipy.cluster.hierarchy import linkage, fcluster
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=60, centers=3, random_state=0)
Z = linkage(X, method="ward")
by_count = fcluster(Z, t=3, criterion="maxclust")
by_height = fcluster(Z, t=10.0, criterion="distance")
# fcluster labels start at 1, so drop the unused slot 0 from bincount.
print("maxclust sizes:", np.bincount(by_count)[1:])
print("distance sizes:", np.bincount(by_height)[1:])Check these details when you use fcluster:
maxclustmeans "at most". If several merges share exactly the same height, the cut can't separate them, and you may get fewer clusters than requested.- Labels start at 1. scikit-learn labels start at 0. Convert before comparing results across libraries.
- Heights depend on the linkage and on feature scaling. A threshold of 10.0 means nothing until you look at the merge heights in
Z[:, 2]. Ward heights are not in the original units of the data, so a threshold taken from a different dataset or linkage will not transfer.
Choosing the cut from the merge heights
When you don't know the number of clusters, the dendrogram heuristic is to cut where a long vertical stretch has no merges. Merging two well-separated groups requires a big jump in distance, so a big gap in sorted merge heights suggests a natural boundary.
You can automate this. After merge i (0-based), n - (i + 1) clusters remain. A cut between the heights of merge i and merge i + 1 therefore gives that many clusters.
import numpy as np
from scipy.cluster.hierarchy import linkage, fcluster
from sklearn.datasets import make_blobs
def cut_at_largest_gap(Z, min_k=2):
n = Z.shape[0] + 1
heights = Z[:, 2]
gaps = np.diff(heights)
ks = n - (np.arange(len(gaps)) + 1) # clusters left inside each gap
gaps = np.where(ks >= min_k, gaps, -np.inf)
i = int(np.argmax(gaps))
threshold = (heights[i] + heights[i + 1]) / 2
labels = fcluster(Z, t=threshold, criterion="distance")
return labels, int(ks[i])
X, _ = make_blobs(n_samples=60, centers=3, random_state=0)
Z = linkage(X, method="ward")
labels, k = cut_at_largest_gap(Z, min_k=2)
print("clusters found:", k)The min_k argument matters. The final merge is often the largest jump, which always points to two clusters. Raise min_k if you know that a split into two is too coarse for your problem.
This method assumes heights increase from one merge to the next. Single, complete, average, and Ward linkage satisfy this. Centroid and median linkage can produce inversions, where a later merge is lower than an earlier one. On those trees, a cut at a height no longer corresponds to a clean set of subtrees.
The inconsistency criterion
A fixed height treats all regions of the tree alike. The inconsistency coefficient of a merge compares its height with the mean and standard deviation of the heights of the links below it, down to depth levels (default 2). A merge much higher than its neighbors gets a large coefficient.
from scipy.cluster.hierarchy import fcluster, inconsistent
R = inconsistent(Z, d=2) # columns: mean, std, link count, coefficient
labels = fcluster(Z, t=1.1, criterion="inconsistent", depth=2)
print(R[-3:, 3]) # coefficients for the last three merges
print(len(set(labels)), "clusters")Merges between single points have a standard deviation of zero, so their coefficient is zero. They are always treated as consistent. On small or uniform datasets the criterion can therefore behave erratically, and you should look at the coefficients before trusting a threshold.
Cutting in scikit-learn
AgglomerativeClustering exposes both cut types. Set n_clusters to cut by count. Set n_clusters=None and distance_threshold to cut by height.
from sklearn.cluster import AgglomerativeClustering
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=60, centers=3, random_state=0)
model = AgglomerativeClustering(
n_clusters=None, distance_threshold=10.0, linkage="ward"
)
labels = model.fit_predict(X)
print(model.n_clusters_, "clusters found")You must set exactly one of n_clusters and distance_threshold, and the other has to be None. Setting both raises an error.
Comparing several cuts at once
Because the tree is built once, you can read many cuts from it cheaply. cut_tree returns a label column for each requested cluster count, numbered from 0. You can score each column and compare.
from scipy.cluster.hierarchy import linkage, cut_tree
from sklearn.datasets import make_blobs
from sklearn.metrics import silhouette_score
X, _ = make_blobs(n_samples=60, centers=3, random_state=0)
Z = linkage(X, method="ward")
ks = [2, 3, 4, 5, 6]
cuts = cut_tree(Z, n_clusters=ks) # shape (n_samples, len(ks))
for k, col in zip(ks, cuts.T):
print(k, round(silhouette_score(X, col), 3))The best silhouette score is a hint, not a verdict. Silhouette favors compact, round clusters, which suits Ward linkage but can mislead for single linkage.
Common errors
- Reusing a threshold after changing the linkage or the scaling. Recompute the merge heights.
- Cutting a single-linkage tree and getting one large cluster plus several singletons. Chaining and outliers cause this. A cut can't fix it, so consider another linkage.
- Expecting a cut to refine cluster boundaries. Cuts only reveal the tree, and they never reassign points.
- Comparing label values directly across libraries. Compare partitions with a metric such as the adjusted Rand index instead.
Exercise
Exercise
A dataset has 50 points, so its linkage matrix Z has 49 rows. The merge heights in Z[:, 2] are increasing. Rows 0 to 46 (0-based) have heights up to 2.1, row 47 has height 6.8, and row 48 has height 7.0. You call fcluster(Z, t=4.0, criterion="distance"). How many clusters do you get, and why?
Show answer
Three clusters. Every merge with height at most 4.0 is kept, which is rows 0 to 46, so 47 merges happen. Each merge reduces the cluster count by one, so 50 - 47 = 3 clusters remain. Rows 47 and 48 are above the cut and are discarded.
Exercise
You change linkage from "ward" to "single" and keep the same distance threshold. Why might the number of clusters change a lot, and what should you do?
Show answer
Single-linkage merge heights are the smallest gaps between clusters, so they are usually much lower than Ward heights, and Ward heights are not in the data's original units. The same number therefore marks a different place in the tree. Recompute the linkage, inspect the new merge heights, and pick a new threshold, or cut by cluster count instead.