Module contents
Lesson 3 of 24Core 80 min

Hierarchical clustering

Hierarchical clustering, linkage criteria, dendrograms, minimum spanning trees, Ward's criterion and efficient implementations.

After this lesson you can

  • Implement agglomerative clustering with Lance–Williams updates.
  • Prove the single-linkage and minimum-spanning-tree connection.
  • Interpret dendrogram cuts and assess cophenetic fidelity.
  • Explain chaining and centroid-linkage inversions.
  • Choose efficient implementations and estimate memory requirements.

Before you start

Motivation: a hierarchy instead of a partition

A biologist does not group organisms into kk boxes: they arrange them in a tree whose branches contain finer branches. A portfolio manager sees stocks in a sector move together, sectors group into markets and those groupings change with the time horizon. A malware analyst receives thousands of binaries sharing code fragments and wants to see variants within a family, similar families and the behavioral groups containing them. In all three cases the question is not “what are the kk groups?” but “how are groups nested at every scale?”

k-means requires choosing kk before starting, and each different kk is a different problem (with its own local optimum). Hierarchical clustering does something else: compute a nested family of partitions once, from finest (each point alone) to coarsest (all together), and postpone choosing kk or scale until the result is visible. The price: with an arbitrary dissimilarity, building that family costs at least Θ(n2)\Theta(n^2) time (all pairs must be inspected) and, except for single linkage, Θ(n2)\Theta(n^2) memory too. And the hierarchy depends entirely on a decision that is yours rather than the algorithm’s: the linkage criterion, what it means for two groups to be “close.”

This lesson starts from a point dissimilarity (chosen in lesson 1: the algorithm sees only a distance matrix) and constructs the hierarchy by successive merges. It first establishes the agglomerative scheme and naive algorithm’s cost. It then studies linkage criteria and the Lance–Williams formula unifying them, proving two central results: Ward’s criterion minimizes the increase in k-means inertia, and single linkage is the minimum spanning tree. Next come correct dendrogram reading (heights, cuts, cophenetic distance, inversions), algorithms that make this viable as nn grows, and the reverse, divisive approach.

The agglomerative scheme and its cost

Start from nn single-point clusters and at each step merge the two nearest according to a chosen between-cluster dissimilarity Δ(A,B)\Delta(A, B).

The reverse is divisive: start from all points and split. There is an immediate problem: a cluster of mm points admits 2m−1−12^{m-1} - 1 splits into two nonempty parts; for m=40m = 40 that is over 5⋅10115 \cdot 10^{11}, so divisive clustering is always heuristic (see bisecting k-means at the end). Agglomerative clustering compares only existing cluster pairs.

Notice how little is needed to count the work. Maintain the n×nn \times n matrix D\mat{D} of dissimilarities between current clusters. Each step searches for the minimum of m(m−1)/2m(m-1)/2 entries and, after merging, recalculates the new cluster’s row. Summing the search over all steps gives ∑m=2n(m2)=(n+13)=(n3−n)/6\sum_{m=2}^{n}\binom{m}{2} = \binom{n+1}{3} = (n^3 - n)/6 comparisons: the naive algorithm costs O(n3)\bigO(n^3) time and O(n2)\bigO(n^2) memory. Improvement is possible because recalculation should not touch the points: if the new row comes from the two merged rows in O(n)\bigO(n), the whole algorithm except minimum search costs O(n2)\bigO(n^2). This is the Lance–Williams formula’s idea (below), while modern algorithms tackle the minimum search (final section).

And memory: the condensed matrix (only the upper triangle, n(n−1)/2n(n-1)/2 numbers) occupies 4n(n−1)4n(n-1) bytes in float64: about 400 MB with n=104n = 10^4, 10 GB with n=5⋅104n = 5 \cdot 10^4 and 40 GB with n=105n = 10^5. RAM sets the practical limit of distance-matrix hierarchical clustering well before time does.

Linkage criteria

We still need to say what Δ(A,B)\Delta(A, B) is when AA and BB contain multiple points. There are several answers, each imposing a bias on the shape of clusters found.

The first three need only the dissimilarity matrix (hence they work with Gower, Jaccard or edit distances from lesson 1). The last two use centroids, which exist only with coordinates: this is the lesson’s first common error, revisited below. Weighted average linkage (WPGMA, the mean of the two subcluster averages) and median linkage (WPGMC) also exist.

Each criterion asks a different question about two groups. Single asks whether any pair of points is close: one bridge suffices. Complete asks whether all pairs are close: it is the merged cluster’s diameter, so avoids chains and favors compact groups of similar diameter. Average compromises between the two. Ward asks how much k-means fit worsens when the two groups merge, and therefore favors spherical clusters of similar variance and, as you will see, similar size. The next two figures show them in action.

InteractiveMerges and dendrogram side by side
0 / 43 merges
Data with single linkage after 0 merges
Dendrogram. The height of each U shows the criterion value at its merge.
el orden de las hojas es arbitrario
  • cluster (inherits the larger cluster’s color)
  • point still alone
  • last merge
  • last merge height
Data
Linkage
Merges completed0 of 43
Clusters remaining44
Last merge height0
Largest cluster (points)1
Height where the blobs mix0.88
Minimum distance between blobs without the bridge5.12
Each point starts as a cluster. Press play or move the timeline. At each step, the pair with the lowest criterion value merges.
Points merge step by step while the dendrogram grows. The black segment of the last merge is the closest pair (single), farthest pair (complete) or centroid to centroid (the rest). With 'Two clouds and a bridge' and single linkage, the clouds join at height (0.88), a fraction of their smallest distance without the bridge (5.12), because the eight bridge points hop from one to the next: the dendrogram shows no gap separating two groups. Switch to complete linkage without moving the line: the final merge lies far above the others. With 'Triangle' and centroid linkage, the second merge lies below the first: an inversion.

Two things you cannot yet explain, but have seen: single linkage first joins what is connected, even if the resulting group is long and awkwardly shaped, and centroid linkage can produce a dendrogram in which a cluster joins at a lower height than its children. Both are proved below. First, the formula that computes all these criteria without revisiting the data.

The Lance–Williams formula

When II and JJ merge, the new cluster’s dissimilarity to any other KK is obtained only from Δ(K,I)\Delta(K, I), Δ(K,J)\Delta(K, J) and Δ(I,J)\Delta(I, J), with coefficients depending on sizes. Lance and Williams (1967) observed that all previous criteria fit one formula.

Proof

Single and complete. Since min⁡(a,b)=a+b2−∣a−b∣2\min(a, b) = \tfrac{a + b}{2} - \tfrac{\abs{a - b}}{2} and max⁡(a,b)=a+b2+∣a−b∣2\max(a, b) = \tfrac{a + b}{2} + \tfrac{\abs{a - b}}{2}, and the minimum (maximum) over I∪JI \cup J is the minimum (maximum) of the two minima (maxima), the result follows directly. Average. The mean over nk(ni+nj)n_k(n_i + n_j) pairs is the nin_i- and njn_j-weighted mean of pair averages with II and JJ. Weighted average. This is its recursive definition.

Centroid and Ward. We need two identities. The first, with cij=λci+(1−λ)cj\vb{c}_{ij} = \lambda\vb{c}_i + (1 - \lambda)\vb{c}_j and λ=ni/(ni+nj)\lambda = n_i/(n_i + n_j) (the centroid of I∪JI \cup J), holds for any point p\vb{p} and is the variance decomposition of a variable taking value ci\vb{c}_i with probability λ\lambda and cj\vb{c}_j with probability 1−λ1 - \lambda:

∥p−cij∥2=λ∥p−ci∥2+(1−λ)∥p−cj∥2−λ(1−λ)∥ci−cj∥2.(1)\norm{\vb{p} - \vb{c}_{ij}}^2 = \lambda\norm{\vb{p} - \vb{c}_i}^2 + (1 - \lambda)\norm{\vb{p} - \vb{c}_j}^2 - \lambda(1 - \lambda)\norm{\vb{c}_i - \vb{c}_j}^2. \tag{1}

With p=ck\vb{p} = \vb{c}_k and λ(1−λ)=ninj/(ni+nj)2\lambda(1 - \lambda) = n_i n_j/(n_i + n_j)^2 this is exactly the centroid update. For Ward, let Δab=nanbna+nb∥ca−cb∥2\Delta_{ab} = \frac{n_a n_b}{n_a + n_b}\norm{\vb{c}_a - \vb{c}_b}^2. Then Δ(K,I∪J)=nk(ni+nj)n∥ck−cij∥2\Delta(K, I \cup J) = \frac{n_k (n_i + n_j)}{n}\norm{\vb{c}_k - \vb{c}_{ij}}^2, and substituting (1) multiplied by that factor:

Δ(K,I∪J)=nkn[ ni∥ck−ci∥2+nj∥ck−cj∥2−ninjni+nj∥ci−cj∥2].\Delta(K, I \cup J) = \frac{n_k}{n}\Big[\,n_i\norm{\vb{c}_k - \vb{c}_i}^2 + n_j\norm{\vb{c}_k - \vb{c}_j}^2 - \frac{n_i n_j}{n_i + n_j}\norm{\vb{c}_i - \vb{c}_j}^2\Big].

But nkni∥ck−ci∥2=(nk+ni)Δ(K,I)n_k n_i\norm{\vb{c}_k - \vb{c}_i}^2 = (n_k + n_i)\Delta(K, I), likewise with JJ, and nkninjni+nj∥ci−cj∥2=nk Δ(I,J)n_k \frac{n_i n_j}{n_i + n_j}\norm{\vb{c}_i - \vb{c}_j}^2 = n_k\,\Delta(I, J). This leaves Δ(K,I∪J)=(nk+ni)Δ(K,I)+(nk+nj)Δ(K,J)−nkΔ(I,J)n\Delta(K, I \cup J) = \frac{(n_k + n_i)\Delta(K, I) + (n_k + n_j)\Delta(K, J) - n_k \Delta(I, J)}{n}. Median is the recursion defined by α=1/2\alpha = 1/2 and β=−1/4\beta = -1/4 (the midpoint of the two centroids).

∎

The algorithmic consequence matters: the between-cluster dissimilarity matrix is updated without revisiting points, in O(n)\bigO(n) per merge. And the practical consequence changes how you think: the five criteria are not five algorithms but one algorithm with five sets of coefficients. This is exactly what the lab cell below implements.

Ward minimizes the increase in inertia: connection to k-means

Ward’s criterion is not arbitrary. It is the merge that least worsens the k-means objective, inertia SSE(P)=∑C∈P∑x∈C∥x−cC∥2\mathrm{SSE}(\mathcal{P}) = \sum_{C \in \mathcal{P}}\sum_{\vb{x} \in C}\norm{\vb{x} - \vb{c}_C}^2.

Proof

Let c\vb{c} be the centroid of A∪BA \cup B. By Steiner’s theorem (sum of squares around a point is the sum around the centroid plus nn times squared distance between them), ∑x∈A∥x−c∥2=SSE(A)+nA∥cA−c∥2\sum_{\vb{x} \in A}\norm{\vb{x} - \vb{c}}^2 = \mathrm{SSE}(A) + n_A\norm{\vb{c}_A - \vb{c}}^2, and similarly for BB. Since cA−c=nBnA+nB(cA−cB)\vb{c}_A - \vb{c} = \frac{n_B}{n_A + n_B}(\vb{c}_A - \vb{c}_B) and cB−c=−nAnA+nB(cA−cB)\vb{c}_B - \vb{c} = -\frac{n_A}{n_A + n_B}(\vb{c}_A - \vb{c}_B), the two terms sum to (nAnB2(nA+nB)2+nBnA2(nA+nB)2)∥cA−cB∥2=nAnBnA+nB∥cA−cB∥2\big(\frac{n_A n_B^2}{(n_A + n_B)^2} + \frac{n_B n_A^2}{(n_A + n_B)^2}\big)\norm{\vb{c}_A - \vb{c}_B}^2 = \frac{n_A n_B}{n_A + n_B}\norm{\vb{c}_A - \vb{c}_B}^2. The second part is a telescoping sum: SSE(Pn)=0\mathrm{SSE}(\mathcal{P}_n) = 0 (each point is its own centroid), and each merge adds its Δt\Delta_t to inertia. With k=1k = 1 the partition is the whole dataset and its inertia is total inertia.

∎

Two readings. First: Ward is bottom-up greedy k-means. It starts at inertia 0 and chooses the merge increasing it least at each step; the dendrogram gives a partition for every kk without seeding centroids or repeating runs, but not an optimal one (the problem is NP-hard, and a greedy one-step choice need not reach the minimum). Second, its bias: joining an isolated point to a cluster of mm points costs mm+1∥x−c∥2≈∥x−c∥2\frac{m}{m+1}\norm{\vb{x} - \vb{c}}^2 \approx \norm{\vb{x} - \vb{c}}^2, and joining two clusters of mm points costs m2∥cA−cB∥2\frac{m}{2}\norm{\vb{c}_A - \vb{c}_B}^2, which grows with size. Large clusters resist merging, so Ward tends to produce clusters of similar sizes.

Since a Ward partition is a possible k-means partition, its inertia is at least that of the global optimum; but a local Lloyd optimum can be worse. What is certain is that Lloyd’s algorithm never increases inertia, so starting it from a Ward partition is a reasonable deterministic initialization. The lab section’s cell measures this.

Reducibility and inversions

A dendrogram should grow upward. With heights h1,h2,…h_1, h_2, \dots in merge order, is h1≤h2≤…h_1 \le h_2 \le \dots always true? No. A property of the criterion is required.

Proof

Single, complete: the minimum (maximum) of Δ(K,I)\Delta(K, I) and Δ(K,J)\Delta(K, J) is at least min⁡\min. Average and weighted average: the update is a convex combination of Δ(K,I)\Delta(K, I) and Δ(K,J)\Delta(K, J), at least the smaller. Ward: with m=min⁡{Δ(K,I),Δ(K,J)}m = \min\{\Delta(K, I), \Delta(K, J)\} and Δ(I,J)≤m\Delta(I, J) \le m, Δ(K,I∪J)=(nk+ni)Δ(K,I)+(nk+nj)Δ(K,J)−nkΔ(I,J)n≥(nk+ni)m+(nk+nj)m−nkmn=m.\Delta(K, I \cup J) = \frac{(n_k + n_i)\Delta(K, I) + (n_k + n_j)\Delta(K, J) - n_k\Delta(I, J)}{n} \ge \frac{(n_k + n_i)m + (n_k + n_j)m - n_k m}{n} = m. Monotonicity: merged pair (I,J)(I, J) has the smallest Δ\Delta of all, say hh. Unchanged pairs remain ≥h\ge h, and new pairs (K,I∪J)(K, I \cup J) satisfy by reducibility Δ(K,I∪J)≥min⁡{Δ(K,I),Δ(K,J)}≥h\Delta(K, I \cup J) \ge \min\{\Delta(K, I), \Delta(K, J)\} \ge h. The next step’s minimum is therefore at least hh. For an equilateral triangle of side 1, all three distances are 1, a pair merges at height 1 and its centroid is 1−1/4=3/2\sqrt{1 - 1/4} = \sqrt{3}/2 from the remaining vertex, less than 1.

∎

With inversions, “cutting at a height” ceases to be a well-defined partition (a cluster can lie above the cut while its children lie below), and the nearest-neighbor chain in the final section is no longer valid. This is why centroid and median are rare in practice; the lab cell shows inversions occur even with ordinary Gaussian data.

Single linkage and the minimum spanning tree

Let GtG_t be the graph whose vertices are the points and which joins ii and jj when dij≤td_{ij} \le t. Single linkage has a characterization that does not mention clusters.

Proof

Components of GtG_t. We must check that after the last merge of height ≤t\le t, two points are in the same cluster if and only if connected in GtG_t. By induction over merges, each cluster is connected in GtG_t (if AA and BB merge at height h≤th \le t, there is a pair a∈Aa \in A, b∈Bb \in B with d(a,b)=h≤td(a, b) = h \le t, a GtG_t edge between connected sets). Conversely, if distinct clusters A≠BA \neq B remain separated after the algorithm processes all heights ≤t\le t, then Δ(A,B)=min⁡d(a,b)>t\Delta(A, B) = \min d(a, b) > t for every pair (otherwise they would have merged before passing tt), so no GtG_t edge joins them. Each cluster is thus a union of components and no edge leaves it: it is a component.

Equivalence with T≤tT_{\le t} is exercise 1 below, which guides you step by step: use the fact that if uu and vv are connected in GtG_t but their path in TT contains an edge ee heavier than tt, the GtG_t path must cross the cut ee defines in TT with a lighter edge ff, and T−e+fT - e + f would be a lower-weight spanning tree. (This uses, from tree characterizations, that removing an edge splits a tree into two components, and from paths and connectivity, that a path between the two sides of a cut crosses it.)

∎
InteractiveThe three cuts agree
Graph GtG_t (gray), minimum spanning tree (thick edges) and components
Sorted weights of the n−1n - 1 tree edges, corresponding to single-linkage heights
t = 0.55
  • MST edge with weight ≤t\le t (color shows component)
  • MST edge with weight >t> t (removed)
  • other edges in GtG_t
0.55
Edges in graph GtG_t (d≤td \le t)102
MST edges with weight ≤t\le t36 of 43
Clusters (components)8
All three partitions agreeyes
Largest difference between single-linkage heights and MST edge weights0 (equal)
The graph GtG_t has 102 edges and 8 components. The thresholded MST uses only 36 edges and leaves the same 8 components. The next merge occurs at t=0.560t = 0.560.
Forty-four points (the two clouds and earlier bridge) and threshold tt. Graph GtG_t (gray) can have hundreds of edges; the minimum spanning tree only 43. Move tt and verify in the readouts that components of GtG_t, those of the trimmed MST (red dashed edges, weight >t> t) and the single-linkage dendrogram cut always give the same partition. In the other panel, sorted tree-edge weights are the single-linkage heights (the readout below checks this). Observe that the two clouds join at a low height, the bridge bottleneck, not the minimum distance between clouds.

The theorem’s most useful part is algorithmic. The minimum spanning tree is obtained with Prim on the dense matrix in O(n2)\bigO(n^2) time, or with Kruskal and union-find in O(Elog⁡E)\bigO(E \log E) for a sparse graph; in the plane the Euclidean MST is a subgraph of Delaunay triangulation (with only O(n)\bigO(n) edges), so for points in R2\R^2 single linkage costs O(nlog⁡n)\bigO(n \log n) (in higher dimension triangulation can have Θ(n2)\Theta(n^2) edges and the shortcut is lost). Most interestingly, the matrix need not be stored, since Prim needs only distances from one point to the rest at each step. That is the spirit of SLINK, covered in the algorithms section.

Single-linkage cophenetic distance is the minimum of maxima

A result used soon: the height at which points uu and vv join in single linkage is min⁡caminos Pmax⁡e∈Pd(e)\min_{\text{caminos } P}\max_{e \in P} d(e), the smallest “bottleneck” over all paths in the complete graph between uu and vv. It is the height of the heaviest edge on their unique path in TT. This follows directly: uu and vv are in the same component of GtG_t if and only if a path exists with all edges ≤t\le t, that is, if t≥t \ge that minimum.

There is a consequence that names the property. Call that quantity m(u,v)m(u, v). It satisfies m(u,w)≤max⁡{m(u,v),m(v,w)}m(u, w) \le \max\{m(u, v), m(v, w)\} (concatenate the two best paths) and m≤dm \le d (the direct path). Any function u′u' with the ultrametric inequality u′(x,z)≤max⁡{u′(x,y),u′(y,z)}u'(x, z) \le \max\{u'(x, y), u'(y, z)\} and u′≤du' \le d satisfies, applying it along any path, u′(x,z)≤max⁡u'(x, z) \le \max of its edges’ dd, and hence u′≤mu' \le m. Single linkage thus returns the greatest ultrametric below the original distance, the subdominant ultrametric. Gower and Ross (1969) observed the connection between single linkage and the minimum spanning tree.

Chaining: one bridge suffices

This is single linkage’s flaw and strength. If two groups are at minimum distance gg and you place one point between them, the MST goes from an edge of weight gg to two of weight ≈g/2\approx g/2, and groups merge at height g/2g/2. With mm evenly spaced points, height is g/(m+1)g/(m + 1). Complete linkage measures distance between the farthest points of the two groups, which the bridge does not affect. This is an exact effect, not a trend: the noise figure measures it with added points. That is why when groups really are elongated connected regions (two moons, two bars), single linkage recovers them easily where others fail, at the cost of fragility to noise. Density methods revisit this scheme: HDBSCAN applies single linkage to a modified distance, mutual reachability, precisely to dampen the effect (see also density level-set clustering).

Dendrograms: heights, cuts and cophenetic distance

A dendrogram plots the merge tree with each merge height on the vertical axis. To make it more than a picture, specify what it retains.

How to read a dendrogram, with four costly pitfalls:

  • A cut is a partition. A horizontal line at height tt gives clusters formed by merges below tt (the number kk of clusters is the number of branches the line cuts). Cutting to kk clusters and cutting at a height are the same operation when heights are monotone (except ties: if two merges share a height, no horizontal cut separates the intermediate kk values).
  • Look at gaps. A cut is stable when there is a large interval of heights without merges around it (every cut in that interval gives the same partition). Choosing kk at the largest gap between consecutive heights is a heuristic, not a theorem: the figure below marks it and lets you verify that with other linkages it does not always match what you seek.
  • Leaf order is arbitrary. At each node you may rotate the two children without changing the tree: a dendrogram with nn leaves has 2n−12^{n-1} equivalent drawings. Two adjacent leaves may be as far apart as leaves on opposite sides: the only similarity information between two leaves is their common ancestor’s height.
  • Compare heights only within the same linkage. Ward height in SciPy is 2 Δt\sqrt{2\,\Delta_t}, complete linkage height is a diameter, single linkage height a jump: they do not mean the same thing.
InteractiveCutting the dendrogram
Data: 3 clusters with Ward linkage
Cophenetic versus original distance (correlation 0.958): pairs appear on both sides of the diagonal (Ward heights use a different scale: the square root of twice the increase in inertia)
Dendrogram with a draggable cut line
t = 14.21largest gap
  • cluster below the cut
  • merge above the cut
  • cut line
  • largest height gap
Data
Linkage
14.21
Clusters at cut height tt3
Cluster sizes22, 16, 12
Cut margin (height)16.23
Cophenetic correlation0.958
This cut lies in the largest gap in the hierarchy, from 3.23 to 19.46. It gives 3 clusters with a height margin of 16.23.
Drag the cut line over the dendrogram, or use the slider, and the scatterplot recolors by partition. The aquamarine band is the largest gap between consecutive heights. Below, each pair's cophenetic distance against original distance: Pearson correlation is cophenetic correlation. Try moons with Ward and single linkage, and bars with all linkages. Notice that with single linkage all points lie below the diagonal and with complete linkage above it.

What you just saw demonstrates something important: cophenetic correlation measures hierarchy fidelity to distances, not cluster quality. With moons, single linkage recovers both shapes yet has the lowest cophenetic correlation. The previous theorem explains why: its cophenetic distance is the minimum of maxima, ignoring most of the distance distribution. The lab cell quantifies this in a table.

The fidelity measured by cc does have an interpretation. For single linkage uij≤diju_{ij} \le d_{ij} always, as proved; for complete linkage, uiju_{ij} is the maximum distance between the clusters containing ii and jj when they merge, so uij≥diju_{ij} \ge d_{ij}. In average linkage (UPGMA), uiju_{ij} is the mean distance between the two merging clusters, intermediate between both extremes. Deciding whether real clusters exist and their quality requires what you will see in lesson 7.

When linkages fail: noise in the bridge

The same experiment can be run with all linkages at once, on four two-group datasets while varying noise.

InteractiveNoise in the bridge
Single
Complete
Average
Ward
Two blobs (80 points)
pureza 100 %
pureza 100 %
pureza 100 %
pureza 100 %
Two moons (70 points)
pureza 100 %
pureza 80 %
pureza 79 %
pureza 93 %
Two bars (80 points)
pureza 100 %
pureza 53 %
pureza 55 %
pureza 53 %
Dense and diffuse (80 points)
pureza 100 %
pureza 100 %
pureza 100 %
pureza 100 %
  • original point (color shows cluster)
  • bridge noise (ring)
  • recovered both groups
  • failed to recover both groups
2
0
single linkage: datasets separated4 of 4
complete linkage: datasets separated2 of 4
average linkage: datasets separated2 of 4
Ward linkage: datasets separated2 of 4
With no noise at k = 2: single 4 of 4, complete 2, average 2, and Ward 2. Moons and bars are not ball shaped. Compact-cluster criteria fail, while single linkage succeeds by looking at separation. Add bridge points to see what changes.
Four datasets (rows) by four linkages (columns), cut into kk clusters. An aquamarine border indicates at least 95% purity relative to the two groups generating the data (excluding noise); red means clusters mix points from both groups. Without noise, only single linkage separates moons and bars well. Increase bridge noise points, or click any plot to add one, and see which linkages stop separating them. With k=2k = 2 and single linkage, observe the failure: in moons and bars the bridge joins the groups and the cut separates a piece of one; in two clouds with ten points, it leaves just one point apart.

The figure’s purity counts the dominant class in each cluster and fails when one cluster is a single isolated point and the rest mixes both groups, or when one cluster splits one group and mixes the other. Three takeaways, all directly observable:

  1. Single linkage is not robust to noise points between groups: a chain of points separated by less than the group gap is enough to merge them, and with k=2k = 2 the cut removes something else (sometimes a single isolated point in a distribution tail).
  2. Complete, average and Ward linkage tolerate that bridge much better, but do not recognize nonconvex shapes: moons and bars fool them without noise. This reflects their bias toward compact clusters.
  3. There is no “correct” linkage. There is a criterion’s bias relative to group shape, and the choice is a decision about what you mean by a cluster:
LinkageBiasFails when
Singlechains and elongated shapesthere is noise or bridges between groups
Completecompact clusters of similar diametergroups have very different diameters or are elongated; an outlier dominates diameter
Averagecompromise: partly inherits both extremes’ biasestrue shape is neither clearly compact nor elongated
Wardspherical clusters of similar variance and sizegroups are elongated, very different in size or distance is non-Euclidean

Modern algorithms: when to use each

The naive scheme is O(n3)\bigO(n^3). Müllner (2011) analyzes practice; here are the essentials from that paper.

Generic algorithm (Müllner’s, improving an Anderberg idea; works for any update formula, including centroid and median with inversions). It stores for each cluster a lower bound on distance to its nearest neighbor in a priority queue, and recalculates a neighbor only when the bound popped from the queue is not the true distance. Best-case cost is Θ(n2)\Theta(n^2); worst-case O(n3)\bigO(n^3), because it may need to recalculate O(n)\bigO(n) neighbors in each of n−1n - 1 merges. In Müllner’s experiments with random data it never departed from quadratic behavior, whereas Anderberg’s algorithm did fall to cubic with centroid and median.

Nearest-neighbor chain (NN-chain; Benzécri, 1982, popularized by Murtagh, 1985). Follow a chain a→b→c→…a \to b \to c \to \dots in which each cluster points to its nearest neighbor until finding a reciprocal-neighbor pair, and merge it. The key idea: two reciprocal neighbors merge at some point in the naive algorithm even if they are not the closest pair now, so global minimum search is unnecessary. After merging, continue from the remaining chain without restarting: with a reducible criterion, the new cluster is never closer to a chain element than its parts were, and remaining pointers remain valid. A cluster leaves the chain only when merged, and each merge removes two, so there are at most about 2n2n insertions plus n−1n - 1 reciprocal-neighbor detections, about 3n3n steps, each with linear neighbor search: Θ(n2)\Theta(n^2) time and Θ(n)\Theta(n) memory in addition to a writable copy of the matrix. Merges do not emerge in height order, so finally sort them (stably for ties) and relabel.

There is a nuance literature took time to notice. Murtagh claimed reducibility sufficed; Müllner (2011) gives a counterexample and proves the result with an additional assumption: dissimilarity between I∪JI \cup J and K∪LK \cup L must not depend on which of the two merges happened first. With both conditions, NN-chain produces the same dendrogram as the naive algorithm, and single, complete, average, weighted average and Ward satisfy them. Centroid and median, which are not reducible, are excluded: the lab’s third cell checks this.

Single linkage: minimum spanning tree and SLINK. This is the previous section’s special case: Prim gives the MST in Θ(n2)\Theta(n^2) without writing to the input matrix. SLINK (Sibson, 1973) organizes it so the hierarchy is built point by point with O(n)\bigO(n) memory: for each point ii store level λ(i)\lambda(i) at which it ceases to be last in its cluster and last element π(i)\pi(i) of the cluster it then joins (the pointer representation). Adding a point queries its distances to previous points, one row at a time. The nn pairs (π(i),λ(i))(\pi(i), \lambda(i)) correspond to n−1n - 1 merges: sort by λ\lambda and merge ii with π(i)\pi(i) to obtain the linkage matrix. (Müllner warns this conversion is exact only without repeated distances: with ties, SLINK gives the correct dendrogram but not always the naive algorithm’s merge order. SciPy therefore uses Rohlf’s 1973 Prim version.)

SciPy follows Müllner’s recommendations exactly: linkage uses the MST algorithm for 'single', nearest-neighbor chain for 'complete', 'average', 'weighted' and 'ward', and the generic algorithm (fast_linkage) for 'centroid' and 'median'.

Size nnWhat to do
up to about 10410^4scipy.cluster.hierarchy.linkage on the condensed matrix (about 400 MB with n=104n = 10^4)
10410^4 to about 10510^5single linkage without matrix (SLINK or MST with a spatial tree); others: linkage while the matrix fits in RAM (10 GB with n=5⋅104n = 5 \cdot 10^4; SciPy always converts to float64), or a nearest-neighbor graph as connectivity constraint (scikit-learn’s AgglomerativeClustering(connectivity=...)), which changes the problem: only graph-neighboring clusters merge
more than 10510^5compress first (mini-batch k-means, bisecting k-means) and build the hierarchy on centroids; or use a density hierarchy (HDBSCAN)

Divisive clustering: bisecting k-means

The most common divisive variant is bisecting k-means: start with all points in one cluster and repeat two steps until there are kk: choose a cluster (highest inertia, or largest) and split it in two with 2-means. Each split looks only at one cluster’s points, so with reasonably balanced splits work per level is O(n)\bigO(n) per Lloyd iteration and there are about log⁡2k\log_2 k levels; worst case (each split isolates few points), O(nk)\bigO(nk). It is linear in nn, not quadratic, and needs no distance matrix. In exchange it is top-down greedy: a bad first partition cannot be reconsidered. The next section’s sixth cell compares it with Ward and direct k-means on 2000 points.

Lab: from scratch and with libraries

Everything that follows runs in the browser. The first cell implements agglomerative clustering with Lance–Williams updates for five linkages and compares with SciPy.

[ ]Agglomerative clustering with Lance–Williams from scratch, compared with SciPyBrowser
import numpy as np
from scipy.cluster.hierarchy import linkage, cophenet
from scipy.spatial.distance import pdist, squareform

def lance_williams(D, metodo):
    """Aglomerativo ingenuo, O(n^3), sobre la matriz D (n, n) de distancias euclídeas. Devuelve Z con el formato de SciPy."""
    n = len(D)
    cuadrado = metodo in ("ward", "centroid")      # estos dos se definen con distancias al cuadrado
    W = (D ** 2 if cuadrado else D).astype(float)
    np.fill_diagonal(W, np.inf)
    tam = np.ones(n)
    ident = np.arange(n)                           # id del cluster que ocupa cada fila
    vivo = np.ones(n, dtype=bool)
    Z = []
    for paso in range(n - 1):
        M = np.where(vivo[:, None] & vivo[None, :], W, np.inf)
        i, j = np.unravel_index(np.argmin(M), M.shape)
        i, j = min(i, j), max(i, j)
        wij, ni, nj, nk = W[i, j], tam[i], tam[j], tam
        if metodo == "single":
            nuevo = np.minimum(W[i], W[j])
        elif metodo == "complete":
            nuevo = np.maximum(W[i], W[j])
        elif metodo == "average":
            nuevo = (ni * W[i] + nj * W[j]) / (ni + nj)
        elif metodo == "ward":
            nuevo = ((nk + ni) * W[i] + (nk + nj) * W[j] - nk * wij) / (ni + nj + nk)
        elif metodo == "centroid":
            nuevo = (ni * W[i] + nj * W[j]) / (ni + nj) - ni * nj * wij / (ni + nj) ** 2
        W[i, :] = nuevo
        W[:, i] = nuevo
        W[i, i] = np.inf
        vivo[j] = False
        altura = np.sqrt(wij) if cuadrado else wij
        Z.append([min(ident[i], ident[j]), max(ident[i], ident[j]), altura, ni + nj])
        ident[i] = n + paso
        tam[i] = ni + nj
    return np.array(Z)

rng = np.random.default_rng(0)
X = np.vstack([rng.normal(c, 0.7, size=(20, 2)) for c in ([0, 0], [4, 0], [2, 3])])
D = squareform(pdist(X))
print("n =", len(X))
for metodo in ["single", "complete", "average", "ward", "centroid"]:
    Z = lance_williams(D, metodo)
    Zs = linkage(X, metodo)
    dh = np.abs(np.sort(Z[:, 2]) - np.sort(Zs[:, 2])).max()
    dc = np.abs(cophenet(Z) - cophenet(Zs)).max()
    inv = int(np.sum(np.diff(Z[:, 2]) < -1e-12))
    print(f"{metodo:9s} dif. máx. de alturas = {dh:.1e}   dif. máx. cofenética = {dc:.1e}   inversiones = {inv}")

Differences are of order 10−1510^{-15} or zero: the linkage matrix matches SciPy’s. Notice the last column: with three ordinary Gaussian clouds (nothing pathological), centroid linkage produces an inversion, and the other four none. Single linkage can be obtained another way, from the minimum spanning tree and through SLINK.

[ ]Single linkage: MST with union-find and SLINKBrowser
import numpy as np
from scipy.cluster.hierarchy import linkage, cophenet
from scipy.spatial.distance import pdist, squareform
from scipy.sparse.csgraph import minimum_spanning_tree

def a_linkage(n, fusiones):
    """Convierte aristas (u, v, peso) ordenadas por peso en la matriz Z de SciPy con union-find."""
    padre = np.arange(n); ident = np.arange(n); tam = np.ones(n)
    def raiz(x):
        while padre[x] != x:
            padre[x] = padre[padre[x]]
            x = padre[x]
        return x
    Z = []
    for u, v, w in fusiones:
        ru, rv = raiz(u), raiz(v)
        Z.append([min(ident[ru], ident[rv]), max(ident[ru], ident[rv]), w, tam[ru] + tam[rv]])
        padre[rv] = ru
        ident[ru] = n + len(Z) - 1
        tam[ru] += tam[rv]
    return np.array(Z)

def single_mst(D):
    T = minimum_spanning_tree(D).tocoo()          # los ceros de una matriz densa cuentan como «sin arista»
    orden = np.argsort(T.data)
    return a_linkage(len(D), zip(T.row[orden], T.col[orden], T.data[orden]))

def slink(D):
    """SLINK (Sibson, 1973): representación por punteros (pi, lam) en O(n^2) tiempo y O(n) memoria extra."""
    n = len(D)
    pi = np.zeros(n, dtype=int)
    lam = np.full(n, np.inf)
    for i in range(n):
        pi[i], lam[i] = i, np.inf
        M = D[i, :i].copy()                        # distancias del punto nuevo a los anteriores
        for j in range(i):
            if lam[j] >= M[j]:
                M[pi[j]] = min(M[pi[j]], lam[j])
                lam[j], pi[j] = M[j], i
            else:
                M[pi[j]] = min(M[pi[j]], M[j])
        for j in range(i):
            if lam[j] >= lam[pi[j]]:
                pi[j] = i
    return pi, lam

def slink_a_Z(pi, lam):
    orden = np.argsort(lam[:-1], kind="stable")    # el último punto tiene lam = inf
    return a_linkage(len(pi), [(i, pi[i], lam[i]) for i in orden])

rng = np.random.default_rng(1)
X = rng.normal(size=(50, 2)) * [3, 1]
D = squareform(pdist(X))
Zs = linkage(X, "single")
for nombre, Z in [("MST + union-find", single_mst(D)), ("SLINK", slink_a_Z(*slink(D)))]:
    print(f"{nombre:18s} alturas: {np.abs(np.sort(Z[:, 2]) - np.sort(Zs[:, 2])).max():.1e}   cofenética: {np.abs(cophenet(Z) - cophenet(Zs)).max():.1e}")

Both versions give SciPy’s heights and cophenetic distances. The second, SLINK, uses only vectors pi, lam and M of size nn, besides reading one distance row at a time (here taken from a precomputed matrix for clarity; with coordinates it would be computed on the fly). Gaussian points have no repeated distances, so conversion to Z by λ\lambda order is exact.

The third cell implements the nearest-neighbor chain with the same Lance–Williams update, counts chain steps and also tests it with centroid linkage, which does not satisfy the assumptions.

[ ]Nearest-neighbor chain (NN-chain) and its limitBrowser
import numpy as np
from scipy.cluster.hierarchy import linkage, cophenet
from scipy.spatial.distance import pdist, squareform

def actualiza(metodo, wi, wj, wij, ni, nj, nk):
    """Fila del cluster nuevo con Lance-Williams (Ward y centroide sobre distancias al cuadrado)."""
    if metodo == "complete":
        return np.maximum(wi, wj)
    if metodo == "average":
        return (ni * wi + nj * wj) / (ni + nj)
    if metodo == "ward":
        return ((nk + ni) * wi + (nk + nj) * wj - nk * wij) / (ni + nj + nk)
    return (ni * wi + nj * wj) / (ni + nj) - ni * nj * wij / (ni + nj) ** 2   # centroide

def nn_chain(D, metodo):
    """Fusiones (fila, fila, altura) en el orden en que se descubren y número de pasos de la cadena."""
    n = len(D)
    cuadrado = metodo in ("ward", "centroid")
    W = (D ** 2 if cuadrado else D).astype(float)    # la copia que se sobrescribe
    np.fill_diagonal(W, np.inf)
    tam, vivo = np.ones(n), np.ones(n, dtype=bool)
    cadena, fusiones, pasos = [], [], 0
    for _ in range(n - 1):
        if not cadena:
            cadena = [int(np.flatnonzero(vivo)[0])]
        while True:
            a = cadena[-1]
            previo = cadena[-2] if len(cadena) > 1 else -1
            fila = np.where(vivo, W[a], np.inf)
            c = int(np.argmin(fila))
            if previo >= 0 and fila[previo] <= fila[c]:
                c = previo                               # con empates se prefiere el anterior: evita ciclos
            pasos += 1
            if c == previo:
                break                                    # a y previo son vecinos recíprocos
            cadena.append(c)
        cadena = cadena[:-2]                             # el resto de la cadena sigue siendo válido
        i, j = min(a, previo), max(a, previo)
        wij = W[i, j]
        nuevo = actualiza(metodo, W[i], W[j], wij, tam[i], tam[j], tam)
        W[i, :], W[:, i] = nuevo, nuevo
        W[i, i] = np.inf
        vivo[j] = False
        tam[i] += tam[j]
        fusiones.append((i, j, np.sqrt(wij) if cuadrado else wij))
    return fusiones, pasos

def a_Z(n, fusiones):
    """Ordena por altura (orden estable) y etiqueta los nodos como SciPy con union-find."""
    padre, ident, tam = np.arange(n), np.arange(n), np.ones(n)
    def raiz(x):
        while padre[x] != x:
            x = padre[x]
        return x
    Z = []
    for u, v, h in sorted(fusiones, key=lambda f: f[2]):
        ru, rv = raiz(u), raiz(v)
        Z.append([min(ident[ru], ident[rv]), max(ident[ru], ident[rv]), h, tam[ru] + tam[rv]])
        padre[rv] = ru
        ident[ru] = n + len(Z) - 1
        tam[ru] += tam[rv]
    return np.array(Z)

rng = np.random.default_rng(2)
X = rng.normal(size=(300, 2)) * [2, 1]
D = squareform(pdist(X))
print("n = 300")
for metodo in ["complete", "average", "ward", "centroid"]:
    fus, pasos = nn_chain(D, metodo)
    dc = np.abs(cophenet(a_Z(len(X), fus)) - cophenet(linkage(X, metodo))).max()
    print(f"{metodo:9s} pasos de la cadena / n = {pasos / len(X):.2f}   dif. máx. cofenética con SciPy = {dc:.1e}")
print("pasos / n con Ward:", {n: round(nn_chain(squareform(pdist(rng.normal(size=(n, 2)))), "ward")[1] / n, 2) for n in [100, 200, 400, 800]})

With complete, average and Ward, cophenetic distances match SciPy to rounding, and the chain takes between 2.90n2.90n and 2.99n2.99n steps for nn from 100 to 800, always below the 3n3n bound: steps are linear and time quadratic because each step scans a row. With centroid linkage the maximum cophenetic difference is 2.7, on the order of the distances themselves: the chain merges reciprocal-neighbor pairs that the naive algorithm never merges because an earlier merge brings a new cluster closer to one of them. This measures lack of reducibility.

Now with libraries. A table of cophenetic correlation, agreement between the cut and true groups (ARI, adjusted Rand index) and inversion count, for five linkages on two datasets.

[ ]Cophenetic fidelity, recovery and inversions with SciPyBrowser
import numpy as np
from scipy.cluster.hierarchy import linkage, cophenet, fcluster
from scipy.spatial.distance import pdist
from sklearn.datasets import make_blobs, make_moons
from sklearn.metrics import adjusted_rand_score

# inversión mínima: tres puntos casi equiláteros y enlace por centroides
tri = np.array([[0.0, 0.0], [1.0, 0.0], [0.5, 0.85]])
print("alturas con centroide en el triángulo:", np.round(linkage(tri, "centroid")[:, 2], 4))

conjuntos = {
    "tres nubes": make_blobs(n_samples=150, centers=[[0, 0], [5, 0], [2.5, 4]], cluster_std=[0.8, 0.8, 0.8], random_state=0),
    "dos lunas": make_moons(n_samples=150, noise=0.06, random_state=0),
}
print(f"{'datos':11s} {'enlace':9s} {'cofenética':>10s} {'ARI (k = real)':>15s} {'inversiones':>12s}")
for nombre, (X, y) in conjuntos.items():
    k = len(set(y))
    for metodo in ["single", "complete", "average", "ward", "centroid"]:
        Z = linkage(X, metodo)
        c = cophenet(Z, pdist(X))[0]
        ari = adjusted_rand_score(y, fcluster(Z, k, criterion="maxclust"))
        inv = int(np.sum(np.diff(Z[:, 2]) < -1e-12))
        print(f"{nombre:11s} {metodo:9s} {c:10.3f} {ari:15.3f} {inv:12d}")

What the table says. With three clouds, average linkage has the highest cophenetic correlation (0.862) and, along with complete and centroid, recovers all three groups (ARI 1.000); Ward reaches 0.941 and single linkage 0.566: chains of peripheral points hurt it. For moons the opposite occurs: single linkage alone separates them (ARI 1.000; others are between 0.294 and 0.441) and has the lowest cophenetic correlation (0.506 versus 0.701 or more). Cophenetic correlation is not a measure of correctness. The first row’s triangle shows the minimal inversion: heights 0.9862 and 0.862. Finally, centroid linkage had 4 inversions on the three clouds and 3 on moons, with 150 points: not a rarity of three deliberately selected points.

Measure the k-means connection as follows: inertia of the Ward partition into kk clusters, the sum of the n−kn - k smallest inertia increases (which must agree by the theorem), the result of starting Lloyd from it and k-means++ with 10 restarts.

[ ]Ward is greedy k-means: inertia as a sum of increasesBrowser
import numpy as np
from scipy.cluster.hierarchy import linkage, fcluster
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs

X, _ = make_blobs(n_samples=300, centers=6, cluster_std=1.6, random_state=3)
n = len(X)
sst = ((X - X.mean(0)) ** 2).sum()
Z = linkage(X, "ward")
aumento = Z[:, 2] ** 2 / 2                      # la altura de SciPy es sqrt(2 * aumento de inercia)

def inercia(etiquetas):
    return sum(((X[etiquetas == c] - X[etiquetas == c].mean(0)) ** 2).sum() for c in np.unique(etiquetas))

print(f"SST = {sst:.2f}   suma de los n - 1 aumentos = {aumento.sum():.2f}")
print(f"{'k':>2s} {'inercia de Ward':>16s} {'suma de los n-k menores aumentos':>34s} {'Ward + Lloyd':>13s} {'k-means++ (10)':>15s}")
for k in [2, 3, 4, 6, 8]:
    et = fcluster(Z, k, criterion="maxclust") - 1
    cen = np.array([X[et == c].mean(0) for c in range(k)])
    lloyd = KMeans(k, init=cen, n_init=1).fit(X).inertia_
    km = KMeans(k, n_init=10, random_state=0).fit(X).inertia_
    print(f"{k:2d} {inercia(et):16.2f} {aumento[: n - k].sum():34.2f} {lloyd:13.2f} {km:15.2f}")

The two middle columns agree to the cent, and the sum of all increases is SST\mathrm{SST}: that is the theorem. Ward partition inertia lies between 0.2% and 9.5% above k-means++ (for example 3603.61 versus 3400.84 with k=3k = 3), and starting Lloyd from it brings it within 1% of k-means++ for every kk tested (3422.80 with k=3k = 3).

And the divisive method: bisecting k-means from scratch, versus Ward and direct k-means.

[ ]Bisecting k-means versus Ward and k-meansBrowser
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
from scipy.cluster.hierarchy import linkage, fcluster

def dos_medias(P, semilla):
    return KMeans(2, n_init=3, random_state=semilla).fit_predict(P)

def kmeans_bisecante(X, k, semilla=0):
    """Divisivo: parte siempre el cluster de mayor inercia con 2-means hasta tener k clusters."""
    etiquetas = np.zeros(len(X), dtype=int)
    for nuevo in range(1, k):
        sse = [((X[etiquetas == c] - X[etiquetas == c].mean(0)) ** 2).sum() if (etiquetas == c).sum() > 1 else -1 for c in range(nuevo)]
        c = int(np.argmax(sse))
        idx = np.where(etiquetas == c)[0]
        mitad = dos_medias(X[idx], semilla)
        etiquetas[idx[mitad == 1]] = nuevo
    return etiquetas

def inercia(X, et):
    return sum(((X[et == c] - X[et == c].mean(0)) ** 2).sum() for c in np.unique(et))

X, y = make_blobs(n_samples=2000, centers=8, cluster_std=1.2, random_state=5)
print(f"{'k':>2s} {'bisecante':>11s} {'Ward':>11s} {'k-means++':>11s}")
Zw = linkage(X, "ward")
for k in [2, 4, 8, 12]:
    b = inercia(X, kmeans_bisecante(X, k))
    w = inercia(X, fcluster(Zw, k, criterion="maxclust") - 1)
    km = KMeans(k, n_init=10, random_state=0).fit(X).inertia_
    print(f"{k:2d} {b:11.1f} {w:11.1f} {km:11.1f}")

et8 = kmeans_bisecante(X, 8)
print("\nk = 8: puntos de cada nube verdadera (columnas) en cada cluster de la bisecante (filas)")
print(np.array([[np.sum((et8 == c) & (y == g)) for g in range(8)] for c in range(8)]))

With k=2k = 2 bisecting is k-means with k=2k = 2 (48171.6 versus 48171.7: the difference is restarts), and Ward is 2% higher. For k=4k = 4 and k=8k = 8 the opposite occurs: bisecting, which cannot undo cuts, is 15% and 25% above k-means inertia (15128.7 versus 13158.5; 6380.9 versus 5116.0), while Ward is closer (13368.7 and 5314.6). With k=12k = 12, more clusters than clouds, all three draw close again (4244.9, 4208.5 and 4007.2). This is the price of the top-down greedy scheme, as the final table shows: with k=8k = 8, bisecting leaves two entire clouds together in one cluster (229 and 238 points) and, to reach eight, splits two others (158 and 89 points of one; 66 and 180 of another). Early bisections cut between cloud groups in the wrong places, and a split-only method cannot reunite what it separated. Do not take this as a law: Steinbach, Karypis and Kumar (2000), clustering documents and measuring quality against true categories (not inertia), found bisecting outperformed k-means and matched or beat the agglomerative methods tested. What is certain is its cost, linear in nn and without a distance matrix.

An asset hierarchy from correlations

The case opening the lesson. Returns are simulated with a factor model: rit=b mt+c fs(i),t+εitr_{it} = b\,m_t + c\,f_{s(i),t} + \varepsilon_{it}, with market factor mtm_t, per-sector factor fs,tf_{s,t} and idiosyncratic noise εit\varepsilon_{it}, all independent standard normals, b=0.6b = 0.6, c=0.5c = 0.5, 40 assets in four sectors of sizes 14, 10, 8 and 8, and 250 days. Theoretical correlation between two assets is (b2+c2)/(b2+c2+1)=0.379(b^2 + c^2)/(b^2 + c^2 + 1) = 0.379 within a sector and b2/(b2+c2+1)=0.224b^2/(b^2 + c^2 + 1) = 0.224 between sectors. Distance dij=2(1−ρij)d_{ij} = \sqrt{2(1 - \rho_{ij})} (Mantegna, 1999) is Euclidean distance between standardized returns divided by T\sqrt{T} (checked in the cell), so Ward and centroid linkage are legitimate here: correlation has underlying coordinates. The same dendrogram is used by Hierarchical Risk Parity (López de Prado, 2016) to order assets before allocating risk.

[ ]Asset dendrogram: sector recovery and temporal stabilityBrowser
import numpy as np
from scipy.cluster.hierarchy import linkage, fcluster, leaves_list, cophenet
from scipy.spatial.distance import squareform, pdist
from sklearn.metrics import adjusted_rand_score

tamanos = [14, 10, 8, 8]                       # activos por sector
sector = np.repeat(np.arange(4), tamanos)
N, T, b, c = len(sector), 250, 0.6, 0.5
print("correlación teórica dentro del sector:", round((b**2 + c**2) / (b**2 + c**2 + 1), 3), "| entre sectores:", round(b**2 / (b**2 + c**2 + 1), 3))

def simular(semilla):
    rng = np.random.default_rng(semilla)
    m, f = rng.normal(size=T), rng.normal(size=(4, T))
    return b * m + c * f[sector] + rng.normal(size=(N, T))

def distancia(R):
    return np.sqrt(np.clip(2 * (1 - np.corrcoef(R)), 0, None))

def jerarquia(R, metodo):
    return linkage(squareform(distancia(R), checks=False), metodo)

# d^2 = 2 (1 - rho) es la distancia euclídea al cuadrado entre los rendimientos estandarizados divididos por sqrt(T)
R = simular(7)
Zs = (R - R.mean(1, keepdims=True)) / R.std(1, keepdims=True) / np.sqrt(T)
print("máx |d^2 - distancia euclídea^2 de los estandarizados| =", f"{np.abs(distancia(R) ** 2 - squareform(pdist(Zs)) ** 2).max():.1e}")

metodos = ["single", "complete", "average", "ward"]
print(f"\n{'enlace':9s} {'ARI (k=4)':>10s} {'cofenética':>11s} {'tramos de sector en las hojas':>30s}")
for me in metodos:
    Z = jerarquia(R, me)
    ari = adjusted_rand_score(sector, fcluster(Z, 4, criterion="maxclust"))
    s = sector[leaves_list(Z)]
    print(f"{me:9s} {ari:10.3f} {cophenet(Z, squareform(distancia(R), checks=False))[0]:11.3f} {1 + int(np.sum(s[1:] != s[:-1])):30d}")

print("\nARI medio con k=4 frente a los sectores, en 10 simulaciones de 250 días:")
print({me: round(float(np.mean([adjusted_rand_score(sector, fcluster(jerarquia(simular(s), me), 4, criterion="maxclust")) for s in range(10)])), 3) for me in metodos})

# estabilidad: 20 ventanas contiguas de 60 días de la simulación anterior
rng = np.random.default_rng(0)
inicios = rng.integers(0, T - 60 + 1, size=20)
print("\n20 ventanas de 60 días: ARI medio frente a los sectores | ARI medio entre pares de ventanas")
for me in metodos:
    et = [fcluster(jerarquia(R[:, a:a + 60], me), 4, criterion="maxclust") for a in inicios]
    ari_s = np.mean([adjusted_rand_score(sector, e) for e in et])
    ari_p = np.mean([adjusted_rand_score(et[i], et[j]) for i in range(20) for j in range(i + 1, 20)])
    print(f"{me:9s} {ari_s:6.3f} | {ari_p:6.3f}")

With 250 days, complete, average and Ward linkage recover the four sectors (ARI 1.000) and order leaves with each sector in one contiguous run (4 runs, the minimum possible), as HRP needs. Single linkage reaches ARI 0.771 and orders leaves into 5 runs (one sector split in two): earlier chaining, now with the market factor as bridge (assets in different sectors have correlation 0.224, not zero). Over 10 simulations, mean ARI with k=4k = 4 is 0.672 for single, 0.986 complete, 1.000 average and 0.992 Ward. With only 60 days per window, ARI against sectors drops to 0.046 (single), 0.548 (complete), 0.578 (average) and 0.710 (Ward), and agreement between windows is 0.109, 0.316, 0.384 and 0.524: Ward is most stable in this model, with the caveat that the windows use one simulation (seed 7, overlapping windows). Repeat the cell changing bb, cc and the number of days to see how differences change. Two things you cannot conclude: that Ward is generally “better,” or that cophenetic correlation (0.795 for Ward versus 0.855 for average) says which linkage best recovers sectors.

Cluster hierarchies are not exclusive to vectors: when data are already a graph, community detection also produces nested levels (for example, Louvain and Leiden clustering repeats greedy community merges maximizing modularity instead of a linkage criterion), and is read with the same cautions about height and order.

Common mistakes

Exercises

ProofThe trimmed MST and components of $G_t$
Prove: Let TT be a minimum spanning tree of the complete graph on the points with weights dijd_{ij}. For every t≥0t \ge 0, points uu and vv are connected in GtG_t (edges with d≤td \le t) if and only if they are connected in T≤tT_{\le t} (edges of TT with weight ≤t\le t).
0
Use that TT is a tree (removing an edge splits it into two components and there is a unique path between two vertices in TT) and that TT has minimum total weight among spanning trees.

Step 1 of 4. Which implication is immediate?

NumericThe last Ward merge on a line
Four points on a line, 00, 22, 77 and 1111, are clustered with Ward linkage. What is the final merge height in SciPy's convention, 2 Δ\sqrt{2\,\Delta}, with Δ\Delta the inertia increase?
QuizWhich linkages produce inversions and why
Which linkages can produce dendrogram inversions, and why?
CodeCophenetic correlation from Z
Implement cophenetic_correlation(Z, D), taking SciPy linkage matrix Z (shape (n - 1, 4)) and condensed original-distance vector D (returned by pdist), and returning Pearson correlation between D and Z's cophenetic distances. Construct the cophenetic distances yourself using each cluster's members (without calling scipy.cluster.hierarchy.cophenet): for each merge, all pairs formed by one member from each child receive the merge height. It must also work with inversions (centroid linkage).
import numpy as np
from scipy.spatial.distance import squareform

def cophenetic_correlation(Z, D):
  """Correlación de Pearson entre D (condensada) y las distancias cofenéticas de Z."""
  Z = np.asarray(Z)
  n = Z.shape[0] + 1
  # tu código: miembros de cada cluster, matriz cofenética (n, n), forma condensada y correlación
  return 0.0
Shift+Enter to run
QuizShape bias of each linkage
Associate each linkage with its shape bias: (a) single, (b) complete, (c) Ward. Biases: (i) elongated chains, (ii) compact clusters of similar diameter, (iii) spherical clusters of similar variance and size.
NumericWard update with Lance–Williams
II (2 points) and JJ (1 point), the closest pair, merge with Δ(I,J)=3\Delta(I, J) = 3. A third cluster KK of 3 points has Δ(K,I)=10\Delta(K, I) = 10 and Δ(K,J)=7\Delta(K, J) = 7 (on Ward's inertia-increase scale). What is Δ(K,I∪J)\Delta(K, I \cup J)?
QuizWard and k-means together
Cut a Ward dendrogram into kk clusters and calculate its inertia SWS_W. Let S∗S^* be the minimum possible inertia of any partition into kk clusters and SLS_L that of a randomly initialized Lloyd local optimum. Which claim is true?
NumericHow many points fit?
You have 16 GB (1 GB = 10910^9 bytes) solely for the condensed float64 distance matrix. What is the largest number of points nn that fits?
QuizWhat a dendrogram does and does not say
An average-linkage dendrogram of 5 points has linkage matrix ZZ with rows (0,1,1.0,2)(0, 1, 1.0, 2), (3,4,1.5,2)(3, 4, 1.5, 2), (2,5,2.5,3)(2, 5, 2.5, 3) and (6,7,6.4167,5)(6, 7, 6.4167, 5). Leaves are drawn in order 0,1,2,3,40, 1, 2, 3, 4. What is true?
NumericReading a cophenetic distance
With the same matrix ZZ as the previous exercise, (0,1,1.0,2)(0, 1, 1.0, 2), (3,4,1.5,2)(3, 4, 1.5, 2), (2,5,2.5,3)(2, 5, 2.5, 3), (6,7,6.4167,5)(6, 7, 6.4167, 5), what is the cophenetic distance between points 11 and 22?
QuizWhich implementation for which size?
You have 3⋅1053 \cdot 10^5 embeddings of dimension 64 and want a hierarchy of a few hundred topics with a compact criterion (Ward). What do you do?
QuizMixed data and Ward
A team clusters records with numeric and categorical variables using Gower distance and wants a criterion producing compact clusters. What is most reasonable?

Summary

Key idea
A dendrogram is an ultrametric on the data: hierarchical clustering chooses a scale rather than kk, and everything depends on what “close” means between two groups. The update formula matters: with it the five criteria are one algorithm, and its properties (reducibility, MST equivalence, inertia increase) determine both interpretation and viable algorithms.
  • Naive agglomerative clustering costs O(n3)\bigO(n^3) time and O(n2)\bigO(n^2) memory; the condensed matrix for n=105n = 10^5 points occupies about 40 GB.
  • Lance–Williams updates unify single, complete, average, centroid, median and Ward and recalculate a row in O(n)\bigO(n) without revisiting points. Centroid and Ward require Euclidean distances, and SciPy Ward heights are 2 Δ\sqrt{2\,\Delta}.
  • Ward cost is inertia increase: inertia with kk clusters is the sum of the n−kn - k smallest increases, and their total is total inertia. Ward is bottom-up greedy k-means and favors similar sizes.
  • Reducible criteria (single, complete, average, Ward) give monotone heights; centroid and median do not, producing inversions (even with 150 Gaussian points).
  • Components of GtG_t, the trimmed minimum spanning tree and single-linkage cuts give the same partition. A bridge of points closer than the group separation merges them, and single-linkage cophenetic distance is the greatest ultrametric below dd.
  • Read a dendrogram by common-ancestor height, not horizontal proximity. Cophenetic correlation measures fidelity to distances, not whether clusters are good: single linkage separates moons and has the lowest cophenetic correlation.
  • Each linkage has a bias (single: chains; complete: similar diameters; Ward: similarly sized spheres), and none is universally correct.
  • At scale: NN-chain for complete, average and Ward (Θ(n2)\Theta(n^2) and Θ(n)\Theta(n) extra); MST or SLINK for single; generic algorithm for centroid and median; bisecting k-means as a linear divisive method; and prior compression when the matrix will not fit.