Build an agglomerative clustering tree with complete or average linkage

Why it matters Hierarchical clustering builds dendrograms for gene expression, document grouping and customer taxonomies, and the merge table format here matches what common libraries return.

Hierarchical clustering merges the two closest clusters again and again. The Lance-Williams update lets you get the new distances from the old ones without looking at points again.

Write agglomerative_merges(X, method). method is "complete" or "average". Start with each point as its own cluster, ids 0 .. n - 1; the cluster made at merge step t gets id n + t. At each step merge the pair (a, b), a < b, with the smallest distance (break ties by the smallest (a, b) pair), and record (a, b, dist, size) where size is the new cluster's point count. Distances start as Euclidean. After merging a and b into m, set d(m, k) = max(d(a, k), d(b, k)) for complete linkage and (n_a * d(a, k) + n_b * d(b, k)) / (n_a + n_b) for average linkage. Return the list of n - 1 merges as tuples (int, int, float, int).

Signaturedef agglomerative_merges(X, method)

Example

X [[0], [1], [5], [7]], method "average" gives [(0, 1, 1.0, 2), (2, 3, 2.0, 2), (4, 5, 5.5, 4)].

Understand the idea

Agglomerative clustering starts with every point alone and keeps joining the two closest groups until one group is left. The record of joins forms a tree (a dendrogram), and cutting it at a height gives clusters.

The question is how far apart two groups are. Complete linkage uses the farthest pair of points, so clusters stay compact. Average linkage uses the average over all cross pairs. The Lance-Williams formulas update these distances from old ones after each merge, without looking at the points again.

Worked example with average linkage: points 0, 1, 5, 7. First merge 0 and 1 (distance 1) into cluster 4 of size 2. Its distance to point 5 is (1 * 5 + 1 * 4) / 2 = 4.5, and to 7 it is (7 + 6) / 2 = 6.5. Next merge 5 and 7 (distance 2) into cluster 5. Finally cluster 4 to cluster 5: (2 * 4.5 + 2 * 6.5) / 4 = 5.5.

Rule: complete d(m, k) = max(d(a, k), d(b, k)); average d(m, k) = (n_a d(a, k) + n_b d(b, k)) / (n_a + n_b).

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampleagglomerative_merges([[0], [1], [5], [7]], 'average')
  • Sample 2: completeagglomerative_merges([[0], [1], [5], [7]], 'complete')