Machine Learning · Insper

Hierarchical Clustering

The whole family of groupings, as a tree

Build it by hand, read it, cut it, and know what the linkage decides

From one partition to a tree

k-means

needs \(k\) before it starts; returns one flat partition

hierarchical

builds all the groupings at once, nested, as a tree: the dendrogram. \(k\) is chosen afterwards, by cutting it.

The oldest way of organizing living things: kingdoms, classes, orders, families, species. Still what biologists, librarians and marketing teams want when one level of detail is not enough.

The path of this lesson

  1. Build the treemerge the closest pair; four linkages by hand
  2. Read and cutthe dendrogram, the matrix Z, the cut
  3. Choose and checklinkage behaviors, where to cut, cophenetic correlation
  4. In practiceother distances, cost, against k-means and density-based clustering
Each stage answers one question: how does merging, pair by pair, build a tree? → what does the tree say, and how does it become groups? → which linkage, which cut, and how faithful is the tree? → when is a tree the right tool?
Stage 1 · How does merging, pair by pair, build a tree?

The idea: merge the two closest groups, repeat

  1. start with \(n\) clusters, one per point;
  2. find the two clusters closest to each other;
  3. merge them, and record the distance: the merge height;
  4. repeat until one cluster is left.

After \(n - 1\) merges, the history of the merges is the tree. Nothing random, nothing iterated to convergence: the same data always gives the same tree (up to ties).

Step 2 hides the only real decision: the distance between two clusters.

The linkage: distance between clusters

linkagedistance between \(P\) and \(Q\)tends to produce
singlethe closest pairchains; one bridge merges two groups
completethe farthest paircompact groups of similar diameter
averagethe mean of all cross distancesa compromise
Wardhow much the merge raises the within-cluster sum of squaresround groups of similar size, like k-means
\[ \Delta(P, Q) = \frac{|P|\,|Q|}{|P| + |Q|}\, \lVert \mu_P - \mu_Q \rVert^2 \]

The within-cluster sum of squares is the k-means inertia: Ward grows it as slowly as it can, one greedy merge at a time.

Simulator: merge, watch the tree grow, cut it

Predict. On the chain (two blobs and a bridge), which linkage will glue the two blobs together long before the last merge?

Five points on a line

pointABCDE
position0371218

The gaps grow by one: 3, 4, 5, 6. Exactly where the linkages disagree.

ABCDE
A0371218
B304915
C740511
D129506
E18151160
Merge 1 is the same for every linkage: between single points every definition is the plain distance. A + B at height 3.

Merge 2 already splits the linkages

The new row: the distance from \(\{A, B\}\) to everything else.

from {A, B} tosingle = mincomplete = maxaverage = mean
Cmin(7, 4) = 475.5
D91210.5
E151816.5

The rest of the matrix does not change: C–D = 5, C–E = 11, D–E = 6.

Predict. For each linkage, which merge comes next?

Single: the smallest entry is 4, so C joins {A, B}. Complete and average: their row is larger, the smallest entry is C–D = 5, so C pairs with D.

Four trees, to the end

linkagemergesheights
singleAB → ABC → ABCD → ABCDE3, 4, 5, 6
completeAB → CD → CDE → all3, 5, 11, 18
averageAB → CD → ABCD → all3, 5, 8, 12.5
WardAB → CD → CDE → all3, 5, 9.81, 16.78
  • Merge 3: average joins the two pairs (8 against 8.5); complete sees the 12 between A and D and brings E into {C, D} (11).
  • Ward's costs \(\Delta\): 4.5 + 12.5 + 48.17 + 140.83 = 206, the sum of squares of the five points around their mean 8. The height reported is \(\sqrt{2\Delta}\): \(\sqrt{2 \cdot 4.5} = 3\).

One matrix, different trees

The five points and the four dendrograms; cut into two clusters, single and average give {ABCD}{E}, complete and Ward give {AB}{CDE}
Asked for two clusters: single and average isolate E; complete and Ward cut between B and C. Neither is wrong: they answer different definitions of "a cluster".
Stage 2 · What does the tree say, and how does it become groups?

Reading a dendrogram

  • The y-axis is a distance. Two points are as similar as the height of the lowest bar that joins them: the cophenetic distance. Complete tree: A and B at 3, A and E at 18.
  • Long vertical lines are the interesting part: a group that stays far from everything. {C, D, E} forms at 11 and waits until 18.
  • The left-to-right order carries almost no information: each bar can flip, so 5 leaves have \(2^4 = 16\) equivalent drawings.
In the complete tree, E is drawn right next to B, although they end up 18 apart. Read similarity from the height where they meet, never from neighboring leaves.

The linkage matrix Z


Z = linkage(X, 'complete')
# [[ 0.  1.  3.  2.]
#  [ 2.  3.  5.  2.]
#  [ 4.  6. 11.  3.]
#  [ 5.  7. 18.  5.]]
    
columnmeaning
0, 1the two clusters merged; ids 0 to \(n-1\) are points, row \(i\) creates cluster \(n + i\)
2the merge height: 3, 5, 11, 18
3how many points the new cluster has: 2, 2, 3, 5

One row per merge, \(n - 1\) rows, in the order the merges happened.

Cutting the tree

A horizontal line at height \(t\): each piece hanging below it is one cluster.

Predict. Complete tree (heights 3, 5, 11, 18). Which clusters does a cut at 8 give?
cut atclusters
4{A, B}, {C}, {D}, {E}
8{A, B}, {C, D}, {E}
12{A, B}, {C, D, E}
20everything

Any cut between 11 and 18 gives the same two clusters: a range 7 units wide. That width is what makes the two-cluster answer stable here.

In scikit-learn, and one property


AgglomerativeClustering(n_clusters=2, linkage='ward').fit(X)
AgglomerativeClustering(n_clusters=None, distance_threshold=8, linkage='complete').fit(X)
  
  • The same merge heights as the hand tables (Ward on the \(\sqrt{2\Delta}\) scale).
  • No predict: a new point has no place in the tree until you rebuild it or assign it with another rule.
Cuts of the same tree are nested: the 3-cluster cut is the 2-cluster cut with one cluster split. Two k-means runs with \(k = 3\) and \(k = 4\) have no such obligation.
Stage 3 · Which linkage, which cut, and how faithful is the tree?

Linkage behaviors, measured

Four datasets with known groups, 300 points each, every method told the true number of clusters. Score: the ARI (Adjusted Rand Index): 1 for the true groups, about 0 for chance.

Predict. Which linkage recovers the two moons?
singlecompleteaverageWard
blobs0.570.980.980.98
blobs + bridge0.000.910.990.96
moons1.000.200.430.30
parallel strips1.000.120.190.22

Two camps

Four datasets by four linkages: single wins on moons and strips but fails on blobs and the bridge; the others the opposite

Single asks "is there some short hop?": it follows chains (1.00 on moons and strips), and a bridge of 20 points merges two blobs (0.00). That is chaining.

Complete, average, Ward compare the groups as a whole: a bridge cannot pull blobs together, but they cut moons and strips across, as k-means does.

Ward (the default) or average for compact groups; single for thin, connected, well-separated shapes. Always look at the tree.

Choosing where to cut

400 points in four blobs that come in two pairs: two scales of structure. Ward tree.

\(k\)range of cut heightsgapsilhouette
232.3 to 159.2126.90.787
330.3 to 32.32.10.664
49.7 to 30.320.60.545
59.2 to 9.70.50.473
Ward tree of 400 points with cuts at 2 and 4 clusters; gap 126.9 for k=2 and 20.6 for k=4; silhouette falling from 0.787 to 0.545

The wider the range of heights a \(k\) survives, the more the data insist on it. The silhouette prefers the coarsest split and does not see the second scale.

So which cut is right?

  • Both: the cuts are nested. Report two segments at the coarse level and four at the fine level; they agree.
  • When one number is required, choose with the question in mind (how many groups can someone act on?) and use the gaps and the silhouette to rule out cuts the data do not support: \(k = 3\), gap 2.1.
  • The inconsistency coefficient is local: with depth 2 it cannot exceed \(2/\sqrt3 = 1.15\), and the top three merges all reach it. One more hint, at most.

Cophenetic correlation: how faithful is the tree?

The correlation between the original distances and the cophenetic ones. By hand, single-linkage tree of the five points:

ABACADAEBCBDBECDCEDE
original \(d\)37121849155116
cophenetic \(c\)3456456566

\(33 / \sqrt{220 \times 10} = \mathbf{0.704}\). The other trees: complete 0.565, average 0.691, Ward 0.561.

Single keeps the distances best, although its tree is a chain; complete and Ward push every cross pair to one big height, erasing the difference between B–C (4) and A–E (18).

Faithful tree ≠ good clusters

The four blobs, four linkages:

cophenetic correlationARI at \(k = 4\)
single0.9440.496
complete0.9470.954
average0.9530.856
Ward0.9520.892
The cophenetic correlation measures how faithfully the tree represents the distances, not how good the clusters are. Use it when the tree itself is the product: a taxonomy, the order of a heat map.
Stage 4 · When is a tree the right tool?

Beyond Euclidean distance

profiles: correlation distance

Four customers: two grow steadily, two spend in one peak month; one of each spends five times more.

Euclidean groups by how much they spend; \(1 - r\) groups by the shape.

documents: cosine distance

A text, the same text ten times longer, a text on another topic. From the first, Euclidean: 20.12 to the long copy, 3.87 to the other topic. Cosine: 0.0 and 1.0.

Which distance is right depends on the question; no index on the data can tell. Single, complete and average take any dissimilarity; Ward only Euclidean.

Cost: why it does not scale

rowspairwise distances
1,0000.004 GB
10,0000.400 GB
100,00040 GB
1,000,000about 4,000 GB
Time of SciPy linkage grows like n to the 2.5 for Ward and 2.3 for single, against 0.004 s for k-means; memory 0.4 GB at 10,000 rows, 40 GB at 100,000

The best algorithms are \(O(n^2)\), still quadratic. On the machine that drew the figure, 16,000 rows took 6.11 s with Ward; k-means, 0.004 s. A method for hundreds to tens of thousands of rows.

What to do with more rows

  • Sample, then assign. Tree on a 2% sample (2,000 of 100,000 rows), cut into 5, every other row to the nearest centroid: ARI 0.993. What you lose is the fine structure: a group of 30 points would have about 0.6 representatives.
  • Connectivity constraints: merge only neighbors in a sparse graph.
  • HDBSCAN (hierarchical DBSCAN, density-based spatial clustering of applications with noise) is itself hierarchical: a single-linkage tree on a density-adjusted distance, without the full matrix, and it marks noise.

Hierarchical vs k-means vs DBSCAN

hierarchicalk-meansDBSCAN / HDBSCAN
a cluster isa branch of the merge treethe points nearest one centroida dense region
decided after fitting\(k\) or the cut height——
outputa nested family of partitionsone partitionone partition + noise
any distance?yes, except WardEuclidean onlyyes
new pointsno predictpredictno predict
same result every runyesdepends on the startyes

Applications

Taxonomies: whenever the product is a tree, not a partition.

Segmentation at several granularities: 12 fine segments that are subdivisions of 3 coarse ones.

Gene-expression heat maps: cluster rows and columns with correlation distance and redraw in leaf order.

A 40 genes by 12 samples table looks like noise in measured order and forms clear blocks in dendrogram leaf order; tumour and normal samples separate at the top

Same numbers, reordered by the tree: blocks of genes up and down in tumours appear, and the column tree splits tumour from normal samples at its top merge.

Summary

  1. Merge the two closest clusters, repeat: the history of merges is the tree.
  2. The linkage defines "closest" and decides what the tree finds.
  3. Read heights, not the left-to-right order; cuts of one tree are nested.
  4. Choose the cut by the gaps in merge heights, with the question in mind.
  5. Cophenetic correlation = fidelity of the tree, not quality of the clusters.
  6. Quadratic cost: hundreds to tens of thousands of rows.
Lab · a few seconds to run

A tree of 101 animals

  • The UCI (University of California, Irvine) Zoo table: 15 yes/no questions and the number of legs. The zoologist's class is sealed until step 8.
  • Can a tree of 16 plain features rediscover the taxonomy? What does it show that k-means does not?
  • Download the lab notebook and open it in Jupyter or Colab.

1. load and look
2. the columns on the same scale
3. four linkages, how faithful each tree is

4. draw the tree
5. choose the cut: gaps and silhouette
6. profile the clusters

7. the same data with k-means
8. open the answer key
9. the heat map, reordered by the tree