Skip to content
AI.info

Unsupervised learning

Hierarchical Clustering and Dendrograms

Build agglomerative hierarchies, read dendrograms, and separate merge history from validated multilevel structure.

By the end you can

Visual

How an agglomerative hierarchy grows

The algorithm starts with fine units. It repeatedly combines the closest eligible groups. Every stage below follows from two decisions made before the first merge: the distance metric and the linkage rule. The tree records the joint history of those two choices. It does not record a structure guaranteed to exist in the world.

FigureTimeline · 5 stops
  1. Start: singleton leaves

    Treat each observation as its own cluster.

  2. Early merges

    Combine highly similar observations or tiny groups according to linkage.

  3. Intermediate branches

    Build nested groups whose meaning depends on the merge criterion.

  4. Late merges

    Join broad, increasingly dissimilar regions of the data.

  5. Root

    End with one cluster containing every observation.

The vertical merge scale matters; left-to-right leaf order often does not.

A tree that grouped by sequencing flowcell and looked like biology

RNA-seq profiles from 15 tissues, human and mouse, grouped by species rather than by tissue. The Mouse ENCODE Consortium published that comparison in PNAS in December 2014, and the consortium's own record of the paper reproduces the finding: “the expression for many sets of genes was found to be more similar in different tissues within the same species than between species”. Read as biology, that is a striking claim about how far the two species have diverged.

The following May, an independent group at the University of Chicago reanalysed the same data. Gilad and Mizrahi-Man found that the assignment of samples to sequencing flowcells and lanes was nearly completely confounded with species. The machine run and the organism were, in practice, the same variable. Their abstract states the result plainly: “When we account for the batch effect, the corrected comparative gene expression data from human and mouse tend to cluster by tissue, not by species.” Same matrix, same algorithm, opposite conclusion. Nothing in the shape of the first dendrogram announced which of the two it was drawing.

A hierarchy makes uncertainty look orderly. Its branches record the chosen linkage process applied to whatever the measurements actually vary with. That is not a guaranteed taxonomy of the world.

A dendrogram is a history of merges under one rule.

Key idea

Leaf order is a presentation choice, and the tree itself may not be unique

Subtrees can often be rotated without changing the hierarchy. Two adjacent leaves may look especially related on the page even when their closeness is not uniquely determined.

Interpret merge heights and shared branches, not horizontal spacing alone. For dense trees, pair the visualization with cluster exemplars and quantitative summaries.

The layout is not the only thing left under-determined. A 1995 survey ran seven clustering methods over 20 data sets and reached a blunt conclusion, in Morgan and Ray's words: “Care must be exercised when hierarchical methods of cluster analysis are used. Dendrograms may not be unique, and certain methods are prone to producing inversions.” They also recorded where the warning fails to reach readers: “Insufficient emphasis on the problems of non-uniqueness and of inversion is made in many text-books and also in computer packages and their manuals”.

The mechanism is tied distances, broken by an arbitrary criterion, which yields different hierarchical classifications depending on the criterion followed. Fernández and Gómez named it in 2008. So the caution is stronger than rotation. Two packages handed the identical distance matrix can return genuinely different trees, not different drawings of one tree.

The x-axis of a dendrogram is not an ordinary distance axis.

Case

How many ways the same tree can be drawn, and which one your software picks

The number of ways to draw one tree is larger than it looks. A tree with n leaves has 2ⁿ⁻¹ “linear orderings consistent with the structure of the tree”, and the 2001 paper by Bar-Joseph and colleagues states that number exactly. Their optimal ordering algorithm runs in O(n⁴) time. What it improved on was a heuristic. Adjacency on the page is one choice among many.

Which of those orderings a reader sees is decided by the toolkit, and in both mainstream toolkits the good one is opt-in. SciPy 1.18.0's linkage function takes an optimal_ordering parameter, described this way: “If True, the linkage matrix will be reordered so that the distance between successive leaves is minimal. This results in a more intuitive tree structure when the data are visualized. defaults to False, because this algorithm can be slow, particularly on large datasets.” MATLAB does not fold the reordering into linkage or dendrogram at all. It ships as a separate function, optimalleaforder, which “returns an optimal leaf ordering for the hierarchical binary cluster tree, tree, using the distances, D”, and cites the 2001 paper for the method.

Unless the analyst asked for better, the plot on the screen is one of those 2ⁿ⁻¹ orderings, selected by the implementation for its own convenience. Two leaves side by side is a default, not a finding.

Figure

The same tree, half a million ways: what a dendrogram's leaf order does and does not tell you, and what the optimal ordering costs.

Comparison

A hierarchy and a flat partition answer different questions

Cutting the tree discards some of the multiscale information that made hierarchical clustering attractive.

The dendrogram's dependence on linkage and metric is not a matter of taste either, to be settled by whichever pair looks best. Several linkages are defined only for one metric. SciPy 1.18.0's documentation states it as a restriction: “Methods 'centroid', 'median', and 'ward' are correctly defined only if Euclidean pairwise metric is used.” MATLAB's method table for linkage says the same in its own words. It marks 'centroid' as “Centroid distance (UPGMC), appropriate for Euclidean distances only”, 'median' as “Weighted center of mass distance (WPGMC), appropriate for Euclidean distances only” and 'ward' as “Inner squared distance (minimum variance algorithm), appropriate for Euclidean distances only”.

Both packages will nonetheless run Ward over a cosine distance matrix and return a tree. That tree is outside the criterion's definition. No amount of downstream cutting, naming or stability checking repairs it. The metric you chose decides which column of this comparison you are entitled to build at all.

FigureComparison · 3 columns

Dendrogram

Shows nested merge relationships across many levels.

  • Retains multiple granularities
  • Can reveal abrupt merge gaps
  • May be unreadable for large samples
  • Depends on linkage and metric

Flat cut

Assigns one cluster label at a chosen height or count.

  • Supports downstream actions
  • Requires a cut rule
  • Hides alternative levels
  • Can split or merge unstable branches

Domain taxonomy

A human-defined hierarchy of concepts or operations.

  • Can include causal or functional meaning
  • May not align with measured similarity
  • Needs governance and definitions
  • Should not be inferred from branch shape alone

Analogy

Building a family tree from resemblance alone

A family tree built by repeatedly pairing the most similar faces organizes visual resemblance. It cannot establish ancestry or family roles.

Faces in a family album have a direct visual relation. Hierarchical clustering may instead combine abstract group distances through a linkage rule, and by the upper merges no two faces are being compared at all. Only groups of groups are.

Nested resemblance is not the same thing as a true taxonomy.

Example

Reading a dendrogram without overclaiming

These checks focus attention on evidence rather than decorative branch labels. Each one has a documented limit, and the limits are as useful as the checks.

  • Merge height: A large jump suggests the algorithm had to combine groups that were relatively dissimilar under the chosen linkage. But the axis is not guaranteed to rise. MathWorks' documentation for linkage is explicit: “The 'centroid' and 'median' methods can produce a cluster tree that is not monotonic.” Morgan and Ray's 1995 survey of seven methods on 20 data sets reports the same failure as a general hazard, certain methods being prone to producing inversions — a merge drawn lower than the one that preceded it. Under those two linkages, height is not a ladder and a gap is not a gap.
  • Leaf examples: Reviewing observations beneath a branch tests whether its apparent coherence survives direct inspection. This is the check that would have caught the Mouse ENCODE tree, where the samples under each branch shared a sequencing flowcell as reliably as they shared a species.
  • Subsample stability: Rebuilding the tree on perturbed samples reveals branches that repeatedly disappear or exchange members. The 70% support threshold analysts routinely apply comes from a single simulation study with stated conditions. Hillis and Bull wrote in 1993: “Specifically, under conditions of equal rates of change, symmetric phylogenies, and internodal change of ≤20% of the characters, bootstrap proportions of ≥70% usually correspond to a probability of ≥95% that the corresponding clade is real.” Outside those conditions, under very high or unequal rates, they warn that “bootstrap proportions >50% are overestimates of accuracy”. The canonical threshold is itself conditional.
  • Alternative metrics: A branch preserved under cosine and Euclidean preprocessing carries different evidence than one appearing under only one relation — provided both runs are legitimate. SciPy and MATLAB both restrict centroid, median and ward to Euclidean distances, so a cosine-versus-Euclidean comparison run under Ward linkage is not a robustness test. It is one defined tree set beside one that the method's own documentation says is not correctly defined.
  • Cut comparison: Several heights may support different operational levels, such as broad routing families and narrower diagnostic subtypes.

Steps

Turn a hierarchy into a defensible multilevel analysis

Preserve more than one level until the intended use requires a flat decision. Two of these steps have published tooling and published benchmarks behind them, so neither has to rest on judgement alone.

Step 3, branch stability, can be computed rather than eyeballed. The R package pvclust, published by Suzuki and Shimodaira in Bioinformatics in 2006, attaches p-values to every cluster in a dendrogram: an approximately unbiased (AU) p-value from multiscale bootstrap resampling, and a bootstrap probability (BP) from the ordinary bootstrap. The AU value is superior in bias to BP. The current CRAN release, version 2.2-0 from November 2019, reports a third. Its package description: “An implementation of multiscale bootstrap resampling for assessing the uncertainty in hierarchical cluster analysis. It provides SI (selective inference) p-value, AU (approximately unbiased) p-value and BP (bootstrap probability) value for each cluster in a dendrogram.”

Step 4, the cut, has been benchmarked head-to-head on data with known answers. Milligan and Cooper ran a Monte Carlo evaluation of 30 stopping rules in 1985, on artificial data containing 2, 3, 4 or 5 distinct nonoverlapping clusters, analysed by four hierarchical methods. Their verdict: “The simulation results for the stopping rules revealed a wide range in their ability to determine the correct number of clusters in the data. Several procedures worked fairly well, whereas others performed rather poorly.” SAS/STAT's 14.1 user guide names the three that performed best with a high degree of error in the data: the pseudo F statistic of Caliński and Harabasz (1974), the Je(2)/Je(1) statistic of Duda and Hart (1973) that can be transformed into a pseudo t², and the cubic clustering criterion. Thirty candidate rules, a handful defensible. The number of clusters is a claim to be argued, not a value to be read off.

FigureProcess · 5 steps
  1. 1. Fit several linkages

    Compare plausible metrics and linkage rules rather than accepting the first tree.

  2. 2. Inspect merge gaps

    Locate heights where broad structures join and review the underlying examples.

  3. 3. Test branch stability

    Use resampling or perturbation to identify persistent subtrees.

  4. 4. Propose candidate cuts

    Select levels that match review capacity or operational granularity.

  5. 5. Document nesting

    Record how fine groups roll into broader groups and where interpretation becomes uncertain.

A hierarchy can express uncertainty better than one forced K

Many datasets support coarse regimes and finer local variants rather than one privileged partition. Hierarchical clustering can preserve that structure when its branches remain stable and interpretable. The tree should remain an analytical object, not an automatic ontology. Names and actions still require evidence beyond the merge procedure.

Even the linkage name can be ambiguous. Two algorithms in the literature both go by Ward's method, and Murtagh and Legendre set them side by side in 2014: “Two algorithms are found in the literature and software, both announcing that they implement the Ward clustering method. When applied to the same distance matrix, they produce different results. One algorithm preserves Ward’s criterion, the other does not.” R ships both, and its manual is explicit. The “ward.D” option “does not implement the clustering criterion of Ward Jr. (1963)”, whereas “ward.D2” does. The authors' own preprint tells readers what follows from that: check what their favorite software package is doing.

A tree is reproducible only when the software option is recorded too — alongside the metric, the tie-breaking rule, whether leaf ordering was optimized, and the stability statistic that supported the level you acted on.

Use the dendrogram to explore levels, then validate the level you act upon.

Key takeaways