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 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 groups?” but “how are groups nested at every scale?”
k-means requires choosing before starting, and each different 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 or scale until the result is visible. The price: with an arbitrary dissimilarity, building that family costs at least time (all pairs must be inspected) and, except for single linkage, 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 grows, and the reverse, divisive approach.
The agglomerative scheme and its cost
Start from single-point clusters and at each step merge the two nearest according to a chosen between-cluster dissimilarity .
The reverse is divisive: start from all points and split. There is an immediate problem: a cluster of points admits splits into two nonempty parts; for that is over , 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 matrix of dissimilarities between current clusters. Each step searches for the minimum of entries and, after merging, recalculates the new cluster’s row. Summing the search over all steps gives comparisons: the naive algorithm costs time and memory. Improvement is possible because recalculation should not touch the points: if the new row comes from the two merged rows in , the whole algorithm except minimum search costs . 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, numbers) occupies bytes in float64: about 400 MB with , 10 GB with and 40 GB with . RAM sets the practical limit of distance-matrix hierarchical clustering well before time does.
Linkage criteria
We still need to say what is when and 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.
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 and merge, the new cluster’s dissimilarity to any other is obtained only from , and , with coefficients depending on sizes. Lance and Williams (1967) observed that all previous criteria fit one formula.
Proof
Single and complete. Since and , and the minimum (maximum) over is the minimum (maximum) of the two minima (maxima), the result follows directly. Average. The mean over pairs is the - and -weighted mean of pair averages with and . Weighted average. This is its recursive definition.
Centroid and Ward. We need two identities. The first, with and (the centroid of ), holds for any point and is the variance decomposition of a variable taking value with probability and with probability :
With and this is exactly the centroid update. For Ward, let . Then , and substituting (1) multiplied by that factor:
But , likewise with , and . This leaves . Median is the recursion defined by and (the midpoint of the two centroids).
∎The algorithmic consequence matters: the between-cluster dissimilarity matrix is updated without revisiting points, in 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 .
Proof
Let be the centroid of . By Steiner’s theorem (sum of squares around a point is the sum around the centroid plus times squared distance between them), , and similarly for . Since and , the two terms sum to . The second part is a telescoping sum: (each point is its own centroid), and each merge adds its to inertia. With 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 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 points costs , and joining two clusters of points costs , 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 in merge order, is always true? No. A property of the criterion is required.
Proof
Single, complete: the minimum (maximum) of and is at least . Average and weighted average: the update is a convex combination of and , at least the smaller. Ward: with and , Monotonicity: merged pair has the smallest of all, say . Unchanged pairs remain , and new pairs satisfy by reducibility . The next step’s minimum is therefore at least . For an equilateral triangle of side 1, all three distances are 1, a pair merges at height 1 and its centroid is 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 be the graph whose vertices are the points and which joins and when . Single linkage has a characterization that does not mention clusters.
Proof
Components of . We must check that after the last merge of height , two points are in the same cluster if and only if connected in . By induction over merges, each cluster is connected in (if and merge at height , there is a pair , with , a edge between connected sets). Conversely, if distinct clusters remain separated after the algorithm processes all heights , then for every pair (otherwise they would have merged before passing ), so no edge joins them. Each cluster is thus a union of components and no edge leaves it: it is a component.
Equivalence with is exercise 1 below, which guides you step by step: use the fact that if and are connected in but their path in contains an edge heavier than , the path must cross the cut defines in with a lighter edge , and 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.)
∎The theorem’s most useful part is algorithmic. The minimum spanning tree is obtained with Prim on the dense matrix in time, or with Kruskal and union-find in for a sparse graph; in the plane the Euclidean MST is a subgraph of Delaunay triangulation (with only edges), so for points in single linkage costs (in higher dimension triangulation can have 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 and join in single linkage is , the smallest “bottleneck” over all paths in the complete graph between and . It is the height of the heaviest edge on their unique path in . This follows directly: and are in the same component of if and only if a path exists with all edges , that is, if that minimum.
There is a consequence that names the property. Call that quantity . It satisfies (concatenate the two best paths) and (the direct path). Any function with the ultrametric inequality and satisfies, applying it along any path, of its edges’ , and hence . 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 and you place one point between them, the MST goes from an edge of weight to two of weight , and groups merge at height . With evenly spaced points, height is . 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 gives clusters formed by merges below (the number of clusters is the number of branches the line cuts). Cutting to 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 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 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 leaves has 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 , complete linkage height is a diameter, single linkage height a jump: they do not mean the same thing.
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 does have an interpretation. For single linkage always, as proved; for complete linkage, is the maximum distance between the clusters containing and when they merge, so . In average linkage (UPGMA), 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.
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:
- 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 the cut removes something else (sometimes a single isolated point in a distribution tail).
- 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.
- 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:
| Linkage | Bias | Fails when |
|---|---|---|
| Single | chains and elongated shapes | there is noise or bridges between groups |
| Complete | compact clusters of similar diameter | groups have very different diameters or are elongated; an outlier dominates diameter |
| Average | compromise: partly inherits both extremes’ biases | true shape is neither clearly compact nor elongated |
| Ward | spherical clusters of similar variance and size | groups are elongated, very different in size or distance is non-Euclidean |
Modern algorithms: when to use each
The naive scheme is . 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 ; worst-case , because it may need to recalculate neighbors in each of 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 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 insertions plus reciprocal-neighbor detections, about steps, each with linear neighbor search: time and 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 and 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 without writing to the input matrix. SLINK (Sibson, 1973) organizes it so the hierarchy is built point by point with memory: for each point store level at which it ceases to be last in its cluster and last element of the cluster it then joins (the pointer representation). Adding a point queries its distances to previous points, one row at a time. The pairs correspond to merges: sort by and merge with 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 | What to do |
|---|---|
| up to about | scipy.cluster.hierarchy.linkage on the condensed matrix (about 400 MB with ) |
| to about | single linkage without matrix (SLINK or MST with a spatial tree); others: linkage while the matrix fits in RAM (10 GB with ; 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 | compress 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 : 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 per Lloyd iteration and there are about levels; worst case (each split isolates few points), . It is linear in , 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.
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 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.
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 , 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 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.
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 and steps for from 100 to 800, always below the 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.
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 clusters, the sum of the smallest inertia increases (which must agree by the theorem), the result of starting Lloyd from it and k-means++ with 10 restarts.
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 : 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 ), and starting Lloyd from it brings it within 1% of k-means++ for every tested (3422.80 with ).
And the divisive method: bisecting k-means from scratch, versus Ward and direct k-means.
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 bisecting is k-means with (48171.6 versus 48171.7: the difference is restarts), and Ward is 2% higher. For and 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 , 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 , 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 and without a distance matrix.
An asset hierarchy from correlations
The case opening the lesson. Returns are simulated with a factor model: , with market factor , per-sector factor and idiosyncratic noise , all independent standard normals, , , 40 assets in four sectors of sizes 14, 10, 8 and 8, and 250 days. Theoretical correlation between two assets is within a sector and between sectors. Distance (Mantegna, 1999) is Euclidean distance between standardized returns divided by (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.
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 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 , 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
Step 1 of 4. Which implication is immediate?
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.0float64 distance matrix. What is the largest number of points that fits?Summary
- Naive agglomerative clustering costs time and memory; the condensed matrix for points occupies about 40 GB.
- Lance–Williams updates unify single, complete, average, centroid, median and Ward and recalculate a row in without revisiting points. Centroid and Ward require Euclidean distances, and SciPy Ward heights are .
- Ward cost is inertia increase: inertia with clusters is the sum of the 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 , 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 .
- 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 ( and 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.