Sub topic 4
Agglomerative clustering: merging from the bottom up
This chapter assumes you know Euclidean distance, basic NumPy, and the scikit-learn fit style of API. You should also know that clustering is unsupervised, so there are no labels to learn from. Linkage criteria, dendrograms, and cutting the tree each get their own chapter. Here the focus is the merging procedure itself and what it implies.
The idea in one sentence
Agglomerative clustering starts with every point as its own cluster. It then repeatedly merges the two closest clusters until one cluster contains everything. The sequence of merges is the result. It is a hierarchy (a tree of nested clusters), not a single partition.
"Bottom-up" describes the direction. The opposite approach, divisive clustering, starts with one big cluster and splits it. Divisive methods are much less common, and the rest of this tutorial covers only the agglomerative kind.
The algorithm
Given n points, the procedure is:
- Compute the pairwise distances between all points.
- Start with n singleton clusters.
- Find the two clusters with the smallest distance between them.
- Merge them into one cluster and record the merge and its distance.
- Update the distances from the new cluster to every remaining cluster.
- Repeat from step 3 until one cluster remains. This takes n − 1 merges.
Step 3 needs a definition of the distance between two clusters. Point-to-point distance (the previous chapter) does not say how to compare groups of points. That definition is the linkage criterion. This chapter uses single linkage, where the cluster distance is the smallest point-to-point distance between the two clusters. Other criteria change which pair gets merged, but the loop above stays the same.
A worked example by hand
Take five points on a line: 0, 1, 5, 6, and 14.
| Step | Merge | Distance | Reason |
|---|---|---|---|
| 1 | {0} and {1} | 1 | Closest pair (tied with 5 and 6). |
| 2 | {5} and {6} | 1 | The remaining tie. |
| 3 | {0,1} and {5,6} | 4 | The closest members are 1 and 5. |
| 4 | {14} and {0,1,5,6} | 8 | The closest members are 6 and 14. |
Merge distances never decrease here. They go 1, 1, 4, 8. The point 14 joins last because it is far from everything, which is how outliers show up in a hierarchy.
The same procedure in code
This is a deliberately naive implementation. It recomputes every cluster distance on each pass, which is slow but easy to follow.
import numpy as np
from scipy.spatial.distance import pdist, squareform
X = np.array([[0.0], [1.0], [5.0], [6.0], [14.0]])
D = squareform(pdist(X)) # full n x n distance matrix
clusters = {i: [i] for i in range(len(X))}
next_id = len(X)
while len(clusters) > 1:
best = None
ids = list(clusters)
for a in range(len(ids)):
for b in range(a + 1, len(ids)):
# Single linkage: smallest point-to-point distance between clusters.
d = D[np.ix_(clusters[ids[a]], clusters[ids[b]])].min()
if best is None or d < best[0]:
best = (d, ids[a], ids[b])
d, i, j = best
clusters[next_id] = clusters.pop(i) + clusters.pop(j)
print(f"merge {i} and {j} at {d} -> cluster {next_id}")
next_id += 1It prints:
merge 0 and 1 at 1.0 -> cluster 5
merge 2 and 3 at 1.0 -> cluster 6
merge 5 and 6 at 4.0 -> cluster 7
merge 4 and 7 at 8.0 -> cluster 8Each merge creates a new cluster with the next unused integer id. The original points use ids 0 to n − 1, and merged clusters use n, n + 1, and so on.
The same result from scipy
scipy.cluster.hierarchy.linkage returns the merge history as an (n − 1) × 4 array called the linkage matrix.
import numpy as np
from scipy.cluster.hierarchy import linkage
X = np.array([[0.0], [1.0], [5.0], [6.0], [14.0]])
Z = linkage(X, method="single")
print(Z)The output is:
[[ 0. 1. 1. 2.]
[ 2. 3. 1. 2.]
[ 5. 6. 4. 4.]
[ 4. 7. 8. 5.]]Each row Z[k] describes merge number k:
- Columns 0 and 1 are the ids of the two clusters merged.
- Column 2 is the distance between them at the merge.
- Column 3 is the number of original points in the new cluster.
The new cluster gets id n + k. Row 2 merges clusters 5 and 6, which are the results of rows 0 and 1. This matches the hand-written loop exactly.
scikit-learn exposes the same information. Setting distance_threshold=0 with n_clusters=None builds the full tree and stores the merge distances.
import numpy as np
from sklearn.cluster import AgglomerativeClustering
X = np.array([[0.0], [1.0], [5.0], [6.0], [14.0]])
model = AgglomerativeClustering(n_clusters=None, distance_threshold=0, linkage="single")
model.fit(X)
print(model.children_)
print(model.distances_)Here children_ holds the pairs merged at each step, using the same id scheme as scipy. distances_ holds the merge distances, which are [1. 1. 4. 8.] for this data.
What the procedure implies
Merges are final. Once two clusters merge, nothing can undo it. The algorithm is greedy, so an early merge made on local information can look wrong once more data is merged around it. K-means can reassign points on later iterations, but agglomerative clustering cannot.
It is deterministic. There is no random initialization, so the same data and settings give the same tree. The exception is ties, as in steps 1 and 2 above. Tie-breaking depends on the implementation and on row order, so reordering rows can change which tied pair merges first.
You do not pick k in advance. The full tree is built first. The number of clusters is chosen afterwards by cutting the tree, which is a later chapter.
Cost grows quickly with n. The naive loop above takes O(n³) time. Library implementations are faster, down to O(n²) time for the standard linkage criteria, but they still hold O(n²) distances in memory. For 10,000 points, the condensed distance vector holds about 50 million 8-byte floats, roughly 400 MB. Tens of thousands of points is a practical ceiling without extra tools.
Common errors
- Forgetting to scale features. Distances drive every merge, so a feature with a large numeric range dominates the tree. Scale first, as covered earlier in this tutorial.
- Using a method that needs Euclidean distance with another metric. Ward linkage is defined in terms of squared Euclidean distance. In scikit-learn,
linkage="ward"only works with Euclidean distance. In scipy,method="ward"assumes Euclidean observations. - Misreading ids in the linkage matrix. A value of n or higher in columns 0 or 1 refers to row
value - nofZ, not to a data point. - Treating the tree as the answer. The merge history is not a set of labels. You must cut it, or use
n_clustersin scikit-learn, to get flat clusters.
Exercise
Using single linkage on the points 0, 2, 3, 10, and 11 (one feature), list the merges in order with their distances, and give the linkage matrix row for the last merge.
Show answer
The merges are {2} and {3} at 1, {10} and {11} at 1, {0} and {2,3} at 2, and finally {0,2,3} and {10,11} at 7. The tie between the first two merges can go in either order. The last row is [5, 6, 7, 5] if the first two merges are rows 0 and 1, because the new clusters then have ids 5 and 6 and the final cluster has 5 points. The ids 5 and 6 are those two merged clusters. The third merge is a different matter. It joins cluster {0} (id 0) with cluster 5, so row 2 is [0, 5, 2, 3], creates cluster 7, and the last row is [6, 7, 7, 5].
Exercise
Why can a 100,000-point dataset be a problem for standard agglomerative clustering even if the algorithm itself is fast enough?
Show answer
The method needs all pairwise distances, which is about 5 billion values for 100,000 points. At 8 bytes each, that is about 40 GB of memory, so memory runs out before time does.