Hierarchical Clustering

Imagine a biologist with gene-expression profiles for a thousand species. She has no idea how many "groups" should exist. She wants a picture showing which species resemble each other closely. It should also show which form loose families. Finally, it should show how those families nest inside larger clades. A single flat partition into kk clusters throws away exactly this nested structure. Choosing kk in advance is often the hardest part of the problem. Hierarchical clustering sidesteps that choice entirely. It builds an entire tree of nested partitions at once. This spans from individual points up to one all-encompassing cluster. This idea matters because most real-world groupings are naturally multi-scale. Documents cluster into topics, and topics into broader themes. Species cluster into genera, and genera into families. Customers cluster into micro-segments that roll up into macro-segments for marketing. Hierarchical clustering produces a single object, the dendrogram. It encodes every possible flat clustering simultaneously. This lets an analyst cut the tree at whatever granularity a downstream task demands. It requires only a notion of distance between points — see Distance Metrics and Similarity Measures. It needs no assumption about cluster shape, count, or a generative model. This makes it a robust exploratory default when little is known about the data. The big picture is a trade of computation for flexibility. Rather than solving one clustering problem, hierarchical methods solve all of them at once. This comes at a cost typically quadratic or worse in the number of points. Two families of algorithms achieve this. Agglomerative methods are bottom-up, merging the closest things first. Divisive methods are top-down, splitting the whole dataset repeatedly. The choice of linkage criterion matters greatly. This is the rule for measuring distance between clusters rather than points. It changes the resulting tree's shape and statistical behavior dramatically. This article builds the agglomerative algorithm from first principles. It explains the major linkage rules and the geometric distortions each one introduces. It covers divisive clustering and why it is used less often. It gives a fully worked numeric trace with a dendrogram. It closes with the pitfalls that most often produce misleading trees in practice. It sets up, but does not resolve, the next natural question: Choosing the Number of Clusters by cutting the dendrogram.

Key takeaways
  • Hierarchical clustering builds a nested tree (dendrogram) of clusters rather than a single flat partition.
  • Agglomerative (bottom-up) merges the two closest clusters repeatedly; divisive (top-down) recursively splits.
  • A linkage criterion (single, complete, average, Ward) defines cluster-to-cluster distance and shapes the tree.
  • Naive agglomerative clustering costs O(n3)O(n^3) time and O(n2)O(n^2) space; optimized variants reach O(n2)O(n^2).
  • Cutting the dendrogram at a chosen height yields any flat clustering, deferring the "how many clusters" decision.
  • Linkage choice trades off chaining (single), tight compact clusters (Ward), and outlier sensitivity (complete).
The core insight

Hierarchical clustering replaces the choice of a cluster count with the choice of a merge/split rule, producing a whole tree of nested partitions instead of one.

The idea

A dendrogram is a rooted binary tree whose leaves are the individual data points and whose internal nodes represent merges of clusters, each internal node labeled with the distance (or dissimilarity) at which its two children were joined. Cutting the tree horizontally at any height hh induces a flat partition: all points connected below that cut belong to the same cluster. Because the tree is monotone (heights strictly increase, or at least do not decrease, as we move from leaves to root, under standard linkages), every horizontal cut yields a well-defined partition, and different cuts give a nested family of partitions ordered by refinement.

Agglomerative clustering starts with every point as its own singleton cluster and repeatedly merges the two clusters that are "closest" according to a chosen linkage criterion, until only one cluster remains. The linkage criterion extends a point-to-point distance metric (Euclidean, Manhattan, cosine, etc., as covered in Distance Metrics and Similarity Measures) into a cluster-to-cluster distance D(A,B)D(A, B) between sets of points AA and BB. The four standard choices are:

  • Single linkage: D(A,B)=min⁡a∈A,b∈Bd(a,b)D(A,B) = \min_{a \in A, b \in B} d(a,b) — distance between the closest pair.
  • Complete linkage: D(A,B)=max⁡a∈A,b∈Bd(a,b)D(A,B) = \max_{a \in A, b \in B} d(a,b) — distance between the farthest pair.
  • Average linkage (UPGMA): D(A,B)=1∣A∣∣B∣∑a∈A,b∈Bd(a,b)D(A,B) = \frac{1}{|A||B|} \sum_{a \in A, b \in B} d(a,b) — mean pairwise distance.
  • Ward's method: merges the pair that produces the smallest increase in total within-cluster variance (sum of squared deviations from centroids).

Divisive clustering runs the opposite direction: start with all points in one cluster and recursively split the least homogeneous cluster into two, typically using a flat clustering subroutine like 2-means or a graph-cut criterion at each step, until every point is its own cluster (or a stopping rule fires). Divisive methods can, in principle, produce better top-level splits because they consider the global structure of the whole dataset before committing to a division, but the search space for the best split of a cluster of size mm is exponential (2m−1−12^{m-1}-1 possible bipartitions), so practical divisive algorithms use heuristics and are far less common than agglomerative ones.

How it works

The agglomerative procedure is a greedy algorithm operating on a proximity matrix — the n×nn \times n matrix of pairwise distances between current clusters, updated after every merge. ``` ALGORITHM AgglomerativeClustering(X, n, linkage) Input: X = {x_1, ..., x_n} // n data points linkage // one of SINGLE, COMPLETE, AVERAGE, WARD Output: dendrogram as a sequence of n-1 merge records // 1. Initialize: each point is its own cluster clusters <- { {x_1}, {x_2}, ..., {x_n} } active <- {1, 2, ..., n} // ids of currently "live" clusters D <- n x n matrix, D[i][j] = pairwise_distance(x_i, x_j) size[i] <- 1 for all i // cluster cardinalities (for Ward/average) merges <- empty list next_id <- n + 1 // new clusters get fresh ids // 2. Repeat n-1 times: merge the closest pair, update distances for step = 1 to n - 1: (i, j) <- argmin over i < j in active of D[i][j] h <- D[i][j] // merge height record (i, j, h) in merges new_cluster <- next_id active <- active \ {i, j} // 3. Update distances from the new cluster to all remaining ones // using the Lance-Williams recurrence (see below) for k in active: D[new_cluster][k] <- lance_williams(linkage, D, i, j, k, size) size[new_cluster] <- size[i] + size[j] active <- active U { new_cluster } next_id <- next_id + 1 return merges // n-1 records fully describe the dendrogram ``` The heart of the update step is the Lance–Williams recurrence, a single formula that computes the distance from a newly merged cluster A∪BA \cup B to any other cluster CC without recomputing all pairwise distances from scratch:

D(A∪B,C)=αAD(A,C)+αBD(B,C)+βD(A,B)+γ∣D(A,C)−D(B,C)∣D(A \cup B, C) = \alpha_A D(A,C) + \alpha_B D(B,C) + \beta D(A,B) + \gamma \left| D(A,C) - D(B,C) \right|

Each linkage rule is just a choice of the coefficients αA,αB,β,γ\alpha_A, \alpha_B, \beta, \gamma:

LinkageαA\alpha_AαB\alpha_Bβ\betaγ\gamma
Single1/21/21/21/200−1/2-1/2
Complete1/21/21/21/2001/21/2
Average (UPGMA)nAnA+nB\frac{n_A}{n_A+n_B}nBnA+nB\frac{n_B}{n_A+n_B}0000
WardnA+nCnA+nB+nC\frac{n_A+n_C}{n_A+n_B+n_C}nB+nCnA+nB+nC\frac{n_B+n_C}{n_A+n_B+n_C}−nCnA+nB+nC\frac{-n_C}{n_A+n_B+n_C}00

where nA,nB,nCn_A, n_B, n_C are cluster sizes. This recurrence is what makes the algorithm practical: updating one row/column of the proximity matrix after a merge takes O(n)O(n) time rather than O(n2)O(n^2), and it is provably equivalent to recomputing the linkage distance directly from the point sets (a short induction on each linkage's definition confirms this, e.g., for single linkage min⁡(D(A,C),D(B,C))=12D(A,C)+12D(B,C)−12∣D(A,C)−D(B,C)∣\min(D(A,C), D(B,C)) = \frac{1}{2}D(A,C)+\frac{1}{2}D(B,C)-\frac{1}{2}|D(A,C)-D(B,C)| is just the identity min⁡(x,y)=x+y2−∣x−y∣2\min(x,y) = \frac{x+y}{2}-\frac{|x-y|}{2}). The output — the sequence of n−1n-1 merges, each with its height — is exactly enough information to draw the full dendrogram, since it specifies, in order, which two clusters merge and at what dissimilarity.

Figure
A dendrogram: leaves are points, internal node height = merge distance
height 4 3 2 1 A B C D E F cut → 3 clusters

Complexity & correctness

Time complexity. The naive implementation above scans the full n×nn \times n proximity matrix at every one of the n−1n-1 steps to find the global minimum, costing O(n2)O(n^2) per step and O(n3)O(n^3) overall. This can be improved: maintaining a priority queue (e.g., a nearest-neighbor heap per cluster) reduces the search for the minimum to O(log⁡n)O(\log n) amortized per merge, and the Lance–Williams update touches O(n)O(n) entries per merge, giving an O(n2log⁡n)O(n^2 \log n) algorithm; for single and complete linkage, the specialized SLINK and CLINK algorithms achieve the information-theoretic optimum of O(n2)O(n^2) time and O(n)O(n) additional space beyond the input, by exploiting the fact that only nearest-neighbor chains need to be tracked. In practice, most general-purpose libraries implement the O(n2log⁡n)O(n^2 \log n) or O(n3)O(n^3) variants because they support arbitrary linkages.

Space complexity. The proximity matrix requires O(n2)O(n^2) space regardless of the time-optimization used, since all pairwise cluster distances must be available for merging; this is the dominant practical bottleneck, making naive hierarchical clustering infeasible much beyond n∼104n \sim 10^4–10510^5 points without approximations (e.g., first pre-clustering with a cheap method, or restricting to a sparse kk-nearest-neighbor graph).

Why the algorithm is correct. "Correctness" here means the produced dendrogram faithfully represents the greedy nested-merge structure defined by the linkage rule — there is no separate ground truth to converge to, since hierarchical clustering is defined by the procedure. The key invariant is: at every step, the proximity matrix entry D[i][j]D[i][j] for any two active clusters i,ji,j equals the true linkage distance between the point sets they represent. This holds by induction — the base case is trivial (DD initialized from the raw metric), and the Lance–Williams recurrence is constructed precisely so that the inductive step reproduces each linkage's definition exactly (as shown algebraically above for single linkage; analogous identities hold for complete, average, and Ward). Given this invariant, greedily picking the global minimum at each step is exactly "merge the two currently-closest clusters," which is the definition of agglomerative clustering — so the algorithm computes precisely what it claims to.

Monotonicity caveat. For single, complete, and average linkage, merge heights are guaranteed non-decreasing as the algorithm proceeds — a consequence of the fact that adding points to a cluster can only keep the min the same or smaller in one direction and never smaller in the relevant aggregate sense for these three rules — so the dendrogram never exhibits an "inversion" where a later merge occurs at a lower height than an earlier one. Ward's method is also monotone in practice for Euclidean data, though pathological centroid-based variants (centroid linkage, median linkage) can produce inversions, a known defect that makes those two linkages harder to interpret visually.

Tradeoffs across linkages.

  • Single linkage is O(n2)O(n^2)-computable exactly (via SLINK) and is invariant to monotone transformations of distance, but is notorious for chaining: a thin bridge of intermediate points can fuse two otherwise well-separated blobs into one elongated cluster.
  • Complete linkage avoids chaining by penalizing the worst-case pair, producing compact, roughly equal-diameter clusters, but is sensitive to outliers (one distant point inflates D(A,B)D(A,B) for the whole cluster) and tends to break large clusters apart.
  • Average linkage is a compromise, less chain-prone than single and less outlier-sensitive than complete, but its results depend on the distance metric's scale in ways that are harder to reason about geometrically.
  • Ward's method minimizes the increase in total within-cluster variance at each merge — the hierarchical analogue of k-Means Clustering's objective — and tends to produce balanced, spherical clusters; it implicitly assumes Euclidean geometry and squared distances, so it is not well-defined for arbitrary non-Euclidean dissimilarities.

Worked example

Consider six points in 1-D for clarity of arithmetic: A=1,B=2,C=4,D=5,E=9,F=10A=1, B=2, C=4, D=5, E=9, F=10. We use Euclidean distance and single linkage, and trace every merge.

Step 0 — initial distance matrix (absolute differences):

ABCDEF
A013489
B102378
C320156
D431045
E875401
F986510

Step 1. Global minimum is D(A,B)=1D(A,B)=1 (tied with D(C,D)=1D(C,D)=1 and D(E,F)=1D(E,F)=1; ties broken by index order here). Merge A,B→G1={A,B}A,B \to G_1 = \{A,B\} at height 11. Update, single linkage: D(G1,C)=min⁡(D(A,C),D(B,C))=min⁡(3,2)=2D(G_1, C) = \min(D(A,C), D(B,C)) = \min(3,2) = 2; D(G1,D)=min⁡(4,3)=3D(G_1,D)=\min(4,3)=3; D(G1,E)=min⁡(8,7)=7D(G_1,E)=\min(8,7)=7; D(G1,F)=min⁡(9,8)=8D(G_1,F)=\min(9,8)=8.

Step 2. Remaining minimum is D(C,D)=1D(C,D)=1. Merge C,D→G2={C,D}C,D \to G_2=\{C,D\} at height 11. Update: D(G1,G2)=min⁡(D(G1,C),D(G1,D))=min⁡(2,3)=2D(G_1,G_2)=\min(D(G_1,C),D(G_1,D))=\min(2,3)=2; D(G2,E)=min⁡(D(C,E),D(D,E))=min⁡(5,4)=4D(G_2,E)=\min(D(C,E),D(D,E))=\min(5,4)=4; D(G2,F)=min⁡(6,5)=5D(G_2,F)=\min(6,5)=5.

Step 3. Remaining minimum is D(E,F)=1D(E,F)=1. Merge E,F→G3={E,F}E,F \to G_3=\{E,F\} at height 11. Update: D(G1,G3)=min⁡(7,8)=7D(G_1,G_3)=\min(7,8)=7; D(G2,G3)=min⁡(4,5)=4D(G_2,G_3)=\min(4,5)=4.

Step 4. Remaining pairs: D(G1,G2)=2D(G_1,G_2)=2, D(G1,G3)=7D(G_1,G_3)=7, D(G2,G3)=4D(G_2,G_3)=4. Minimum is D(G1,G2)=2D(G_1,G_2)=2. Merge G1,G2→G4={A,B,C,D}G_1,G_2 \to G_4=\{A,B,C,D\} at height 22. Update: D(G4,G3)=min⁡(D(G1,G3),D(G2,G3))=min⁡(7,4)=4D(G_4,G_3) = \min(D(G_1,G_3), D(G_2,G_3)) = \min(7,4) = 4.

Step 5. Only pair left: D(G4,G3)=4D(G_4,G_3)=4. Merge everything into the root at height 44.

Final merge sequence (the dendrogram, in order):

StepMergeHeight
1A,B1
2C,D1
3E,F1
4{A,B},{C,D}2
5{A,B,C,D},{E,F}4

Cutting this dendrogram at height h=3h=3 (between step 4 and step 5) yields the 2-cluster partition {A,B,C,D}\{A,B,C,D\} and {E,F}\{E,F\} — exactly the two visually obvious blobs in the raw coordinates, confirming the algorithm recovered the correct structure. Cutting instead at h=1.5h=1.5 recovers three clusters, {A,B},{C,D},{E,F}\{A,B\}, \{C,D\}, \{E,F\}, matching the three tight pairs. This illustrates the central payoff of hierarchical clustering: one computation, many valid answers, chosen post hoc by where you cut.

Common pitfalls & traps

PitfallWhy it happensConsequence
Using single linkage on noisy dataA few bridging points chain distant clusters togetherOne giant elongated "cluster" instead of separated groups
Forgetting to standardize featuresFeatures with larger numeric scale dominate the distanceClustering reflects units, not structure
Applying Ward's method to non-Euclidean dissimilaritiesWard assumes squared Euclidean geometry to define varianceMerge heights become meaningless; results uninterpretable
Reading dendrogram height as distance between original pointsHeights are linkage distances between clusters, not point-pairsOverinterpreting exact numeric gaps between leaves
Assuming the algorithm reveals the "true" number of clustersThe tree always has n−1n-1 merges regardless of real structureAnalysts cut arbitrarily without validating the choice
Ignoring O(n2)O(n^2) memory blow-upFull pairwise matrix stored explicitlyOut-of-memory failures on datasets beyond ~10510^5 points
Comparing dendrograms across different linkages as if equivalentEach linkage optimizes a different, incompatible criterionMisleading conclusions about "which clusters are real"

Pioneers & history

Origins · 1 minRobert R. Sokal and how this was discovered
RR
Robert R. Sokal
1926–2012 · biological classification and numerical taxonomy

A biologist and pioneer of quantitative approaches to classifying organisms, Sokal (with Peter Sneath) formalized much of what is now called numerical taxonomy in the 1960s, including the average-linkage method still known by their initials, UPGMA (Unweighted Pair Group Method with Arithmetic mean). Their work grew from a practical need: classifying species and specimens using measured traits rather than subjective expert judgment, which demanded a rigorous, repeatable clustering procedure — exactly the gap hierarchical clustering was built to fill.

History
1958
Joe H. Ward Jr. develops the variance-minimizing merge criterion later named Ward's method.
1963
Sokal and Sneath publish Principles of Numerical Taxonomy, formalizing UPGMA and cluster analysis for biology.
1973
Sibson introduces SLINK, an O(n2)O(n^2)-time, O(n)O(n)-space exact algorithm for single-linkage clustering.
1977
Defays introduces CLINK, the analogous optimal algorithm for complete-linkage clustering.
1980
s–1990s: hierarchical clustering becomes a standard exploratory tool in statistics packages and bioinformatics (gene-expression heatmaps).

Hierarchical clustering's roots lie less in computer science proper and more in numerical taxonomy and psychometrics, where researchers needed a principled way to group specimens or survey respondents from measured attributes alone. The method's popularity surged with the rise of microarray gene-expression analysis in the late 1990s and 2000s, where the clustered heatmap — rows and columns each reordered by their own dendrogram — became a near-universal visualization for exploring which genes and which samples behave similarly, cementing hierarchical clustering's place as a default first step in exploratory data analysis across biology, marketing analytics, and document clustering.

Where this matters

Bioinformatics pipelines use hierarchical clustering constantly: clustering genes by co-expression pattern, samples by similarity, or species by sequence divergence to build phylogenetic-style trees. Document and text-mining systems use it to build topic hierarchies without pre-specifying a topic count, often as a precursor to labeling clusters for search or recommendation. Market segmentation teams use it to explore customer bases at multiple granularities — broad segments for strategy, fine segments for targeted campaigns — using the same dendrogram. Image and signal processing pipelines use agglomerative merging for region-growing segmentation, where pixels or superpixels are merged based on color or texture similarity. Statistical software (R's `hclust`, Python's `scipy.cluster.hierarchy`, `scikit-learn`'s `AgglomerativeClustering`) ships hierarchical clustering as a default exploratory tool precisely because it needs no assumption about cluster count, complementing centroid-based methods like k-Means Clustering and forming the natural bridge to the practical question of Choosing the Number of Clusters once a dendrogram is in hand.

Ask the tutor: How does the choice of linkage criterion change which points get merged first when clusters have very different sizes?

What is the difference between hierarchical clustering and k-means?

K-means requires the number of clusters kk fixed in advance and produces one flat partition by iteratively optimizing centroid assignments; it scales roughly linearly per iteration but can converge to different local optima. Hierarchical clustering builds the entire nested sequence of partitions at once, deferring the choice of cluster count to a later cut, at the cost of quadratic or worse time and space. Ward's linkage in hierarchical clustering shares k-means' variance-minimizing objective, effectively giving a deterministic, tree-structured relative of k-means. Neither dominates: hierarchical is preferred for small-to-medium data needing interpretability, k-means for large data needing speed.

Can I choose the number of clusters from the dendrogram itself?

Yes — one common heuristic is to cut at the height of the largest vertical gap between successive merge heights, on the reasoning that a big gap indicates the tree was forced to merge otherwise very dissimilar clusters. This gives a data-driven candidate for kk, though it is only a heuristic and can be misleading on noisy or hierarchically ambiguous data. More rigorous approaches (e.g., the gap statistic, silhouette analysis, or cophenetic correlation checks) are usually layered on top. This question is explored in depth under Choosing the Number of Clusters.

Is hierarchical clustering sensitive to the order in which points are processed?

The algorithm itself is deterministic given a fixed tie-breaking rule, so processing order does not change the result as long as ties in distance are broken consistently. However, real datasets rarely have exact numerical ties, so in practice the output is essentially order-independent. Where order does matter is in some divisive implementations that greedily process clusters in a fixed queue order, and in approximate/streaming variants that process points incrementally, both of which can produce different trees depending on input order.

Why does Ward's method require Euclidean distance?

Ward's method is defined as the merge that minimizes the increase in total within-cluster sum of squared deviations from the cluster centroid, a quantity whose algebraic simplification (the basis of the Lance–Williams coefficients for Ward) relies on the parallelogram law of Euclidean geometry. Applying Ward's formula to a non-Euclidean dissimilarity (e.g., edit distance or cosine distance) still runs mechanically but no longer corresponds to any meaningful variance-minimization interpretation, and merge heights can become non-monotone or nonsensical. If your distance is not Euclidean, average or complete linkage are safer defaults.

How do I read a dendrogram's leaf order — does left-to-right position mean anything?

The horizontal order of leaves is largely a layout convention chosen for visual clarity (commonly, keeping merged subtrees adjacent), and does not itself encode a distance or ranking; only the tree topology and merge heights carry information. Software typically reorders leaves at each internal node to minimize crossing lines or to respect a secondary ordering. Never infer that two adjacent leaves are close just from their position — always check the height at which their nearest common ancestor merges.

Can hierarchical clustering handle very large datasets?

Not directly in its naive form: the O(n2)O(n^2) memory for the proximity matrix and O(n2log⁡n)O(n^2\log n)–O(n3)O(n^3) time make datasets beyond roughly 10410^4–10510^5 points impractical on typical hardware. Common workarounds include first running a coarse pre-clustering (e.g., BIRCH's CF-trees, or k-means with many centers) and hierarchically clustering the resulting summaries, or restricting the proximity computation to a sparse k-nearest-neighbor graph so most cluster pairs are never compared. These approximations trade exactness for tractable scaling to millions of points.

Does hierarchical clustering assume clusters are convex or spherical?

It depends entirely on the linkage. Single linkage can recover arbitrarily shaped, elongated clusters (much like density-based methods), because it only needs one close pair of points to connect two regions — that flexibility is precisely the source of its chaining vulnerability. Complete and Ward linkage implicitly favor compact, roughly convex, similarly sized clusters because they penalize large intra-cluster spread. So unlike k-means, which always assumes roughly spherical clusters, hierarchical clustering's shape assumption is a choice, encoded entirely in the linkage rule.

Before this