Sub topic 4
Agglomerative clustering: merging from the bottom up
This chapter assumes you know basic Python and NumPy, Euclidean distance, and scikit-learn's fit and predict style API. It also assumes you know what unsupervised learning is.
The core idea
Agglomerative clustering builds clusters from the bottom up. It starts with every point as its own cluster. It then repeatedly merges the two closest clusters until one cluster holds all the points.
The result is a hierarchy, not a single set of labels. Each merge is one step in a tree, and you decide later how many clusters you want.
The algorithm
- Compute the distance between every pair of points.
- Put each point in its own cluster. For n points, you start with n clusters.
- Find the two closest clusters and merge them into one.
- Update the distances between the new cluster and all the others.
- Repeat steps 3 and 4 until one cluster remains. This takes n − 1 merges.
Step 4 raises a question. Distance between two points is easy, but how far apart are two clusters that each contain many points? The rule you choose is called the linkage criterion. The next chapter covers the options. For now, the examples use Ward linkage, which merges the pair of clusters that least increases the total within-cluster variance.
What the merge record looks like
SciPy's linkage function runs the whole procedure and returns a matrix Z. Each row describes one merge: the indices of the two clusters, the distance between them, and the size of the new cluster. New clusters get indices starting at n, so the cluster created by row 0 has index n.
import numpy as np
from scipy.cluster.hierarchy import linkage, fcluster
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=30, centers=3, random_state=0)
# Each row of Z records one merge: the two cluster indices, their distance, and the new cluster size.
Z = linkage(X, method="ward")
# Cut the tree so that at most 3 flat clusters remain.
labels = fcluster(Z, t=3, criterion="maxclust")
print(Z.shape)
print(np.unique(labels))With 30 points, Z.shape is (29, 4): 29 merges, 4 values per merge. The last line prints the three cluster labels [1 2 3]. fcluster turns the tree into flat labels by stopping the merging early. Later chapters cover how to choose where to stop.
Common errors
- Forgetting that merges are final. Agglomerative clustering is greedy. Once two clusters merge, the algorithm never undoes it. An early bad merge stays in the tree.
- Passing a distance matrix to
linkageas if it were data.linkageexpects either raw observations or a condensed distance matrix, such as the output ofpdist. A square matrix is read as observations and gives wrong results. - Using Ward linkage with a non-Euclidean metric. Ward is defined for Euclidean distance only.
- Ignoring scale. Merges depend on distances, so a feature with a large range dominates. Scale your features first.
Exercise
You run linkage on 50 points. How many rows does Z have, and why?
Show answer
49 rows. Each merge reduces the number of clusters by one, so going from 50 clusters to 1 takes 50 − 1 = 49 merges, and each merge is one row.