Hierarchical clustering
Build a tree of nested clusters by repeated merging, and read it as a dendrogram.
Animated explanation
The idea
Instead of choosing up front, agglomerative clustering builds every clustering at once. Start with each point as its own cluster. Repeatedly merge the two clusters that are closest. After merges everything is one cluster.
The history of merges is a tree, drawn as a dendrogram: each merge is a horizontal bar at the height of the distance at which it happened. Cut the dendrogram with a horizontal line and the branches below it are your clusters. You see the structure at every scale, families inside families, which is why biologists use it for gene expression and taxonomies.
Linkage decides the shape
"Distance between two clusters" must be defined. Single linkage (nearest members) can follow long chains and find non-convex clusters but is easily bridged by noise. Complete linkage (farthest members) makes compact clusters. Average is in between. Ward merges the pair that least increases total within-cluster variance and behaves like a hierarchical k-means. Try several and inspect the dendrograms.
Cost and practicalities
The naive algorithm stores an distance matrix and costs (or with priority queues), so it suits thousands of points, not millions. It is deterministic (no random initialisation). Divisive clustering (split top-down) is the less common alternative.
The algorithm, step by step
- 1Compute all pairwise distances; make every point a cluster.
- 2Find the two clusters with the smallest linkage distance; merge them; record the height.
- 3Update distances from the new cluster to all others (Lance–Williams formula).
- 4Repeat until one cluster remains; cut the dendrogram at a height or at k clusters.
The maths
Average linkage
Ward criterion
Lance–Williams update
Strengths and weaknesses
Strengths
- No need to fix k in advance
- The dendrogram shows structure at all scales
- Deterministic; any distance or similarity works
Weaknesses
- O(n²) memory, at least O(n² log n) time
- Merges are final: early mistakes can't be undone
- Results depend strongly on linkage
Reach for it when…
Check your understanding
Lambdian Lab
Agglomerative clustering
Implement naive agglomerative clustering with Euclidean distance.
- linkage_distance(A, B, method): for point arrays A and B with method in "single", "complete", "average".
- agglomerate(X, k, method): merge until k clusters remain; return integer labels 0..k−1 (any numbering).
- merge_heights(X, method): the list of n − 1 merge distances in order (they never decrease for these linkages).