Sub topic 6
Reading a dendrogram
This chapter assumes you can run scikit-learn and matplotlib code. It also assumes you know how agglomerative clustering merges the two closest clusters at each step, and what a linkage criterion is. Here you will learn to read the tree that agglomerative clustering produces and to avoid the usual misreadings.
What a dendrogram encodes
A dendrogram is a tree drawn from the merge history of agglomerative clustering. It shows two things:
- Which clusters merged. Each U-shaped link joins two clusters.
- How far apart they were when they merged. The height of the link is the merge distance under the chosen linkage.
The leaves are the original samples, all at height zero. Moving up the tree is moving forward in time. Each link is one merge, so a dataset of n points has n − 1 links.
The linkage matrix behind the picture
SciPy stores the merge history in a linkage matrix Z with n − 1 rows and four columns. Each row records one merge:
| Column | Meaning |
|---|---|
| 0 and 1 | Indices of the two clusters merged. Indices 0 to n − 1 are original samples. |
| 2 | Merge distance, which becomes the link height. |
| 3 | Number of original samples in the new cluster. |
The cluster created by row i gets index n + i. A later row refers to it by that index. The following code builds the five-point tree from the diagram.
import numpy as np
from scipy.cluster.hierarchy import linkage
X = np.array([[0.0], [1.0], [5.0], [6.5], [15.0]])
Z = linkage(X, method="average")
print(np.round(Z, 3))The rows come out as follows:
| Row | Merged | Distance | Size | New index |
|---|---|---|---|---|
| 0 | 0 and 1 | 1.0 | 2 | 5 |
| 1 | 2 and 3 | 1.5 | 2 | 6 |
| 2 | 5 and 6 | 5.25 | 4 | 7 |
| 3 | 4 and 7 | 11.875 | 5 | 8 |
Row 2 is the average of the four distances between {0, 1} and {5, 6.5}: (5 + 6.5 + 4 + 5.5) / 4 = 5.25. Reading Z row by row is the most precise way to read a dendrogram. The plot is a drawing of this table.
What the axes mean
Only the vertical axis carries information. This is the rule people break most often.
- Height is the merge distance. Compare heights to compare how dissimilar the merged groups were.
- Horizontal order is arbitrary. At each merge, the two children can be swapped without changing the tree. Two leaves that sit side by side in the plot are not necessarily similar. They may be separated by a high link.
- Horizontal spacing is not a distance. Leaves are drawn at equal intervals.
To judge how similar two samples are, find the lowest link that connects them. Its height is their cophenetic distance. Follow the links up from each leaf until the paths meet.
Finding natural cut points
A long vertical stretch with no merges means the clusters present at that height stayed distinct over a wide range of distances. Merging them required a large jump. Large gaps between consecutive merge heights suggest good places to cut.
The code below finds the largest gap, computes a cut height in the middle of it, and draws the tree with that line.
import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import linkage, dendrogram, fcluster
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=30, centers=3, random_state=0)
n = X.shape[0]
Z = linkage(X, method="ward")
heights = Z[:, 2]
gaps = np.diff(heights)
i = int(np.argmax(gaps)) # largest jump is between row i and row i + 1
cut = (heights[i] + heights[i + 1]) / 2
n_clusters = n - (i + 1) # i + 1 merges have happened below the cut
print(f"cut height {cut:.2f} gives {n_clusters} clusters")
dendrogram(Z, color_threshold=cut)
plt.axhline(cut, linestyle="--", color="gray")
plt.xlabel("sample index")
plt.ylabel("merge distance")
plt.show()
labels = fcluster(Z, t=cut, criterion="distance")
print(np.unique(labels))The color_threshold argument colors each subtree below the cut separately. Without it, SciPy uses 70% of the maximum height. The criterion="distance" option in fcluster cuts at a height instead of asking for a cluster count. The next chapter covers cutting in detail.
A largest-gap rule is a heuristic. It works well on clean blobs and can mislead on data with no clear structure. It also always favors the top of the tree, where a gap of two clusters merging into one is common. Treat the result as a candidate and check it against domain knowledge.
Reading large trees
With hundreds of leaves, the bottom of the plot becomes unreadable. Truncate the tree to show only the top levels:
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import linkage, dendrogram
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=500, centers=4, random_state=1)
Z = linkage(X, method="ward")
dendrogram(Z, truncate_mode="lastp", p=12, show_contracted=True)
plt.xlabel("cluster (size in parentheses if more than one sample)")
plt.ylabel("merge distance")
plt.show()With truncate_mode="lastp", the plot shows only the last p merged clusters. Each leaf then stands for a whole subtree, labeled with its sample count. The other option, truncate_mode="level", limits the depth instead.
You can also skip the plot and get the drawing data. dendrogram(Z, no_plot=True) returns a dictionary. Its "leaves" entry gives the leaf order as sample indices. This is how you map a plotted position back to a sample.
Checking how faithful the tree is
A dendrogram compresses all pairwise distances into a tree. You can measure how much was lost by comparing the cophenetic distances with the original distances:
from scipy.cluster.hierarchy import linkage, cophenet
from scipy.spatial.distance import pdist
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=30, centers=3, random_state=0)
D = pdist(X)
for method in ["single", "complete", "average", "ward"]:
Z = linkage(X, method=method)
c, _ = cophenet(Z, D)
print(f"{method:9s} cophenetic correlation = {c:.3f}")The cophenetic correlation is the correlation between the tree's distances and the original ones. Values near 1 mean the tree preserves the original distances well. Average linkage often scores highest, but a high value does not make a linkage right for your data. Ward heights are on a different scale from raw distances, so use the score to compare trees of the same data, not to judge absolute quality.
Common misreadings
- Reading horizontal closeness as similarity. Only the lowest connecting link matters.
- Comparing heights across linkages. Single linkage heights are nearest-neighbor distances. Complete linkage heights are farthest-pair distances. Ward heights measure variance increase. A height of 5 means something different in each plot.
- Reading too much into the top. In Ward and complete linkage the final merges are almost always the tallest, because the last clusters are large. A tall root link does not prove two real groups exist.
- Ignoring scale. If one feature dominates the distance, the dendrogram reflects that feature. Scale first.
- Expecting a clean gap from single linkage. Single linkage chains clusters through bridges of points. Its tree often shows a staircase of small merges instead of tidy gaps.
- Expecting monotone heights from every method. Single, complete, average, and Ward heights never decrease going up. Centroid and median linkage can produce inversions, where a parent sits lower than a child. Those inversions make the plot hard to read.
Exercise
Exercise
A dendrogram built with average linkage has leaves 7 and 12 drawn next to each other. The link joining them sits at height 9.0. The link joining leaf 7 to leaf 3, which is far away on the x axis, sits at height 2.0. Which pair of samples is more similar, and why?
Show answer
Leaves 7 and 3 are more similar. Similarity is read from the lowest link connecting two samples, which is their cophenetic distance. For 7 and 3 that is 2.0, and for 7 and 12 it is 9.0. Horizontal position carries no meaning, because the order of children at each merge is arbitrary, so being drawn side by side says nothing.
Exercise
Given the linkage matrix row [5, 6, 5.25, 4] in a dataset of 5 samples, what do the entries mean, and what index does the new cluster get if this is row 2 of Z?
Show answer
The row merges clusters 5 and 6 at distance 5.25, and the new cluster contains 4 original samples. Row 2 creates cluster index n + 2 = 7.