TExcelTAD
Home › Classical ML Algorithms: Supervised & Unsupervised › Hierarchical Clustering and Dendrograms

Hierarchical Clustering and Dendrograms

Biologists arrange species in a family tree; a shop might group products into departments, then aisles, then shelves. Hierarchical clustering builds such a tree from data: start with every point as its own cluster and repeatedly merge the two closest clusters until one remains. The result is a dendrogram, and cutting it at any height gives a flat clustering, so you do not have to fix the number of clusters in advance. The Machine Learning course draws one with SciPy; here you implement the merging loop and compare linkage rules.

Linkage: the distance between clusters

Points have a distance d(x,x′)d(\mathbf{x}, \mathbf{x}'); clusters need one too. The choice, called the linkage, decides the shape of the clusters you get:

Linkage D(A,B)D(A, B) Tends to give
single min⁡a∈A,b∈Bd(a,b)\min_{a \in A, b \in B} d(a, b) long chains; follows any shape, sensitive to bridges of noise
complete max⁡a∈A,b∈Bd(a,b)\max_{a \in A, b \in B} d(a, b) compact clusters of similar diameter
average 1∣A∣∣B∣∑a,bd(a,b)\frac{1}{\lvert A \rvert \lvert B \rvert} \sum_{a, b} d(a, b) a compromise
Ward increase in total within-cluster sum of squares when AA and BB merge compact, similar-size clusters; k-means' objective, greedily

Ward's merge cost is ∣A∣∣B∣∣A∣+∣B∣∥μA−μB∥2\frac{\lvert A \rvert \lvert B \rvert}{\lvert A \rvert + \lvert B \rvert} \lVert \boldsymbol{\mu}_A - \boldsymbol{\mu}_B \rVert^2, so it joins small clusters with close centroids first. SciPy reports Ward heights on the scale of a distance (the square root of twice that increase).

The merging loop from scratch

Eight points in three groups. The function merges the two closest clusters under a chosen linkage and records each merge as SciPy's linkage does: the two cluster ids, the merge distance and the new cluster's size. New clusters get ids n,n+1,…n, n + 1, \dots

python · try it yourself
import numpy as np
from scipy.cluster.hierarchy import linkage

pts = np.array([[1, 1], [1.5, 1.2], [1.2, 2.0], [5, 5], [5.5, 5.3], [6, 4.8], [9, 1], [9.4, 1.5]])

def agglomerative(X, method):
    """Merge the two closest clusters until one is left; record (a, b, distance, size) like SciPy."""
    clusters = {i: [i] for i in range(len(X))}
    D = np.sqrt(((X[:, None] - X[None]) ** 2).sum(axis=2))
    def dist(a, b):
        block = D[np.ix_(clusters[a], clusters[b])]
        return {"single": block.min(), "complete": block.max(), "average": block.mean()}[method]
    merges, next_id = [], len(X)
    while len(clusters) > 1:
        ids = sorted(clusters)
        a, b = min(((p, q) for i, p in enumerate(ids) for q in ids[i + 1:]), key=lambda pq: dist(*pq))
        merges.append((a, b, dist(a, b), len(clusters[a]) + len(clusters[b])))
        clusters[next_id] = clusters.pop(a) + clusters.pop(b)
        next_id += 1
    return np.array(merges)

for method in ["single", "complete", "average"]:
    ours = agglomerative(pts, method)
    scipy_Z = linkage(pts, method=method)
    print(f"{method:8s} merge heights {ours[:, 2].round(2)}  same as SciPy: {np.allclose(ours[:, 2], scipy_Z[:, 2])}")
print("first merges (single):", agglomerative(pts, "single")[:3, :2].astype(int).tolist())
single   merge heights [0.54 0.58 0.64 0.71 0.85 4.74 4.84]  same as SciPy: True
complete merge heights [0.54 0.58 0.64 1.02 1.02 5.66 8.41]  same as SciPy: True
average  merge heights [0.54 0.58 0.64 0.86 0.94 5.31 6.57]  same as SciPy: True
first merges (single): [[0, 1], [3, 4], [6, 7]]

All three linkages first join the closest pairs (points 0 and 1, then 3 and 4, then 6 and 7), finish the three groups below a height of about 1, and need a big jump (4.7 or more) to merge groups. That jump is what you look for in a dendrogram. Single linkage gives the lowest heights (it measures the closest pair), complete the highest. The naive loop costs O(n3)O(n^3) and more; SciPy uses smarter algorithms (O(n2)O(n^2) for single linkage), but the n×nn \times n distance matrix still limits hierarchical clustering to tens of thousands of points.

A dendrogram of iris flowers

Thirty iris flowers, standardised, clustered with Ward linkage. The figure is the dendrogram; leaves are labelled with the true species (set = setosa, ver = versicolor, vir = virginica), which the algorithm never saw. Cutting the tree at height 6 gives three clusters:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import linkage, dendrogram, fcluster
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics import adjusted_rand_score

X, y = load_iris(return_X_y=True)
rng = np.random.default_rng(0)
idx = np.sort(rng.choice(len(X), 30, replace=False))   # 30 flowers keep the tree readable
Xs = StandardScaler().fit_transform(X[idx])
Z = linkage(Xs, method="ward")

fig, ax = plt.subplots(figsize=(8, 3.5))
dendrogram(Z, labels=[f"{['set', 'ver', 'vir'][c]}" for c in y[idx]], ax=ax, color_threshold=6)
ax.axhline(6, color="grey", linestyle="--")
ax.set_ylabel("Ward merge distance")
ax.set_title("30 iris flowers, Ward linkage")
fig.tight_layout()

labels = fcluster(Z, t=6, criterion="distance")        # cut the tree at height 6
print("clusters at height 6:", len(set(labels)))
print("last three merge heights:", Z[-3:, 2].round(2))
sk = AgglomerativeClustering(n_clusters=3, linkage="ward").fit(Xs)
print("same partition as AgglomerativeClustering:", adjusted_rand_score(labels, sk.labels_) == 1.0)
print("agreement with the species (ARI):", round(adjusted_rand_score(y[idx], labels), 3))
clusters at height 6: 3
last three merge heights: [ 3.98  6.24 12.  ]
same partition as AgglomerativeClustering: True
agreement with the species (ARI): 0.645

Read the dendrogram from the top: the last merge (height 12) joins setosa with everything else, the clearest split in iris. The next (6.24) separates the two other species, imperfectly: some versicolor and virginica flowers are mixed, which is why the agreement with the species, measured by the adjusted Rand index (ARI, 1 for identical partitions, about 0 for random ones), is 0.645 rather than 1. A cut at height 6 lies between the merges at 3.98 and 6.24 and gives three clusters; AgglomerativeClustering(n_clusters=3) produces the same partition.

Strengths, weaknesses, when to use it

Strengths Weaknesses
no kk needed up front; one tree gives every kk O(n2)O(n^2) memory and at least O(n2)O(n^2) time
the dendrogram shows structure at all scales merges are greedy and never undone
any distance or similarity works (with single, complete, average) results depend strongly on the linkage
deterministic: no random start Ward needs Euclidean distances

Use it for small to medium data when the hierarchy itself is interesting (taxonomies, document or gene groupings), when you want to look at the data before fixing kk, or with a custom distance. AgglomerativeClustering with a connectivity graph clusters images or maps into spatially connected regions.

Pitfalls

  • Single linkage on noisy data. A few points between two groups chain them into one ("chaining").
  • Unscaled features. As with every distance-based method.
  • Over-reading the leaf order. Each merge can be drawn with its two branches swapped; only the heights carry information.

Practice

  1. Clusters A={0,1}A = \{0, 1\} and B={4}B = \{4\} on a line. Compute their single, complete and average linkage distances.
Answer

Distances from 4: to 0 is 4, to 1 is 3. Single: 3. Complete: 4. Average: (4+3)/2=3.5(4 + 3)/2 = 3.5.

  1. How do you get 2 clusters from the iris dendrogram above, and which flowers end up together?
Answer

Cut between the last two merges, at any height between 6.24 and 12 (for example fcluster(Z, t=2, criterion="maxclust")). Setosa forms one cluster, versicolor and virginica the other.

Test yourself

Which linkage defines the distance between two clusters as the distance between their closest members?

  1. complete
  2. single
  3. average
  4. Ward

How do you get a flat clustering from a dendrogram?

  1. Take the leaves
  2. Cut the tree at a height; each branch below the cut is a cluster
  3. Run k-means on the tree
  4. Use the root

Why is hierarchical clustering rarely used on a million points?

  1. It needs labels
  2. It needs the pairwise distance matrix, which grows with n2n^2
  3. It only works in 2-D
  4. It cannot use Euclidean distance