Sub topic 5
Linkage criteria and the clusters they favor
Agglomerative clustering repeatedly merges the two closest clusters. The open question is what "closest" means when a cluster holds many points. The linkage criterion answers it, and it often matters more than any other setting you choose. This chapter assumes you know how the bottom-up merge loop works, and that you can compute Euclidean distance between points. It also assumes you can call scikit-learn's fit_predict.
What a linkage criterion is
A distance metric compares two points. A linkage criterion extends that to two clusters, A and B, by turning the point-to-point distances into one number. At every step the algorithm merges the pair of clusters with the smallest linkage value.
The same data and metric can give very different trees under different linkages. The linkage decides which shapes the algorithm can recover and which it breaks apart.
The four common criteria
Single linkage
Single linkage uses the minimum distance between any point in A and any point in B:
d(A, B) = min over a in A, b in B of d(a, b)
Two clusters are close if they have any pair of nearby points. A chain of points, each close to the next, therefore merges into one cluster even if its two ends are far apart. This lets single linkage follow elongated or curved shapes such as two interleaved half-moons. It also causes chaining: a thin bridge of noisy points can join two otherwise separate groups.
Complete linkage
Complete linkage uses the maximum distance between any point in A and any point in B:
d(A, B) = max over a in A, b in B of d(a, b)
Two clusters merge only if all their points are reasonably close. This keeps clusters compact, with a small diameter, and resists chaining. The cost is that it splits large or elongated clusters, and a single outlier can inflate a cluster's distance to everything else.
Average linkage
Average linkage uses the mean of all pairwise distances between A and B:
d(A, B) = (1 / (|A| |B|)) × sum of d(a, b)
This is a compromise. One close pair or one far pair cannot decide the result alone. It is less prone to chaining than single linkage and less sensitive to outliers than complete linkage. It works with any metric, not only Euclidean.
Ward linkage
Ward linkage does not compare points directly. It merges the pair of clusters that causes the smallest increase in total within-cluster sum of squares. For clusters with sizes nA and nB and centroids cA and cB, that increase is:
Δ(A, B) = (nA nB / (nA + nB)) × ‖cA − cB‖²
The size factor penalizes merging large clusters, so Ward tends to produce clusters of similar size and round shape. This is the same objective k-means minimizes, which is why the two methods often agree on blob-like data. Ward is defined only for Euclidean distance. scipy and scikit-learn both enforce this.
Summary table
| Linkage | Cluster distance | Favors | Typical failure |
|---|---|---|---|
| single | nearest pair | elongated, non-convex shapes | chaining through noise bridges |
| complete | farthest pair | compact clusters of similar diameter | splits large clusters, outlier-sensitive |
| average | mean of all pairs | moderately compact clusters | sits between the extremes, so it has no sharp strength |
| ward | increase in variance | round, similar-sized clusters | needs Euclidean distance, splits non-convex shapes |
Seeing the difference in code
The following script runs all four linkages on two datasets. Moons are non-convex. Blobs are round and overlapping. Because we know the true labels, the adjusted Rand index (ARI) shows how closely each linkage recovers them. An ARI of 1.0 means a perfect match, and values near 0 mean the result is no better than random.
from sklearn.cluster import AgglomerativeClustering
from sklearn.datasets import make_blobs, make_moons
from sklearn.metrics import adjusted_rand_score
datasets = {
"moons": make_moons(n_samples=200, noise=0.05, random_state=0),
"blobs": make_blobs(n_samples=200, centers=3, cluster_std=1.5, random_state=0),
}
for name, (X, y) in datasets.items():
k = len(set(y))
for link in ["single", "complete", "average", "ward"]:
labels = AgglomerativeClustering(n_clusters=k, linkage=link).fit_predict(X)
ari = adjusted_rand_score(y, labels)
print(f"{name:6s} {link:9s} ARI = {ari:.2f}")Expect single linkage to do best on the moons and Ward or complete linkage to do best on the blobs. Single linkage on overlapping blobs often performs poorly. Exact numbers depend on your library version, so check them rather than assuming.
Chaining and cluster sizes
Chaining shows up in the cluster sizes. A linkage that chains tends to produce one huge cluster plus tiny ones. This scipy example adds a few scattered noise points to three blobs and cuts each tree into three clusters.
import numpy as np
from scipy.cluster.hierarchy import fcluster, linkage
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=150, centers=3, cluster_std=1.0, random_state=1)
rng = np.random.default_rng(1)
noise = rng.uniform(low=X.min(axis=0), high=X.max(axis=0), size=(10, 2))
X = np.vstack([X, noise])
for method in ["single", "complete", "average", "ward"]:
Z = linkage(X, method=method)
labels = fcluster(Z, t=3, criterion="maxclust")
sizes = sorted(np.bincount(labels)[1:], reverse=True)
print(f"{method:9s} cluster sizes: {sizes}")Single linkage usually reports something like one cluster holding nearly every point, with the other two holding one or two points each. The noise points lie between the blobs and act as stepping stones. Ward typically gives three balanced groups.
How the choice shows up in the dendrogram
Linkage changes the shape of the tree as well as the final labels. In a single-linkage dendrogram, merges often happen at gradually increasing heights, so the tree looks like a staircase. The heights are also small, because each merge needs only one close pair. Complete and Ward trees show larger jumps at the top, and those jumps are easier to use when choosing where to cut. Merge heights from different linkages are not comparable, because they measure different quantities. The next chapter covers reading these trees.
Gotchas
- Ward needs Euclidean distance. Passing
metric="manhattan"withlinkage="ward"in scikit-learn raises an error. With scipy,method="ward"assumes Euclidean input and gives meaningless results otherwise. - Centroid and median linkage can invert. scipy also offers
centroidandmedian. They can produce a merge at a lower height than an earlier merge, which breaks the monotone tree that dendrograms assume. Prefer the four criteria above unless you have a reason. - Ward's scipy heights are scaled. The merge distances scipy reports for Ward are not the raw Δ above. Use them to compare merges within one tree, not as variance values.
- Scaling still matters. Every linkage inherits the distance metric. An unscaled feature with a large range dominates all four criteria.
- Ties and ordering. With duplicate points or exact ties in distance, the merge order can depend on input order. The final tree is usually equivalent, but labels may be numbered differently.
Choosing in practice
Start with Ward for numeric, scaled, roughly round data, because it is the most stable default. Use single linkage when you expect thin or curved structures and the data has little noise. Use average linkage when the metric is not Euclidean, such as cosine distance on text vectors, or when you want a middle ground. Use complete linkage when you specifically want compact clusters of bounded diameter. If single linkage looks right but noise breaks it, that is a signal to try DBSCAN, which handles noise explicitly and is covered later in this tutorial.
Exercise
You have a 2-D dataset of two long, curved, interleaved bands with a few scattered noise points between them. You run agglomerative clustering with n_clusters=2. Ward linkage cuts each band in half. Single linkage returns one huge cluster and one or two tiny ones. Explain both results and suggest what to try next.
Show answer
Ward minimizes within-cluster variance, so it prefers round, similar-sized groups and splits long bands across their length. Single linkage can follow the bands, but the noise points between them act as bridges. The nearest-pair distance through a bridge is small, so the bands merge into one chain and the outliers remain as tiny clusters. Next, try average linkage, which is less sensitive to a few bridging points. If it still fails, remove or flag the noise first. Alternatively, switch to DBSCAN, which labels isolated points as noise and follows curved dense regions.