Sub topic 8
Hierarchical clustering with scipy and scikit-learn
This chapter shows how to run agglomerative clustering in practice with two libraries. It assumes you know basic Python and NumPy, the idea of unsupervised learning, Euclidean distance, and scikit-learn's fit and fit_predict style. It also assumes you have met linkage criteria and dendrograms in earlier chapters. Here the focus is on the code, the data structures the libraries return, and the errors people commonly make.
Two libraries, two jobs
Both libraries implement the same bottom-up algorithm, but they expose it differently.
| Aspect | `scipy.cluster.hierarchy` | `sklearn.cluster.AgglomerativeClustering` |
|---|---|---|
| Main output | The full merge tree as a linkage matrix `Z` | Flat labels for a chosen number of clusters |
| Cutting the tree | Separate step with `fcluster` | Built in through `n_clusters` or `distance_threshold` |
| Dendrogram plot | `dendrogram(Z)` | Not provided directly |
| Pipeline fit | No estimator API | Works with `fit_predict` and pipelines |
| Linkage names | `single`, `complete`, `average`, `ward`, and others | `single`, `complete`, `average`, `ward` |
Use scipy when you want to inspect the tree and decide where to cut it. Use scikit-learn when you already know the number of clusters, or when you want a familiar estimator API.
Building the tree with scipy
The function linkage takes a data matrix and a linkage method, and returns the whole merge history.
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 samples, Z has shape (29, 4). A tree over n points always needs n - 1 merges.
How to read the linkage matrix
Each row describes one merge, in order from the smallest distance to the largest:
- Column 0 and column 1 hold the indices of the two clusters being merged.
- Column 2 holds the distance at which they merged.
- Column 3 holds the number of original points in the new cluster.
The indexing needs care. Indices from 0 to n - 1 refer to the original points. Each merge creates a new cluster with index n + i, where i is the row number. So in a 30-point dataset, row 0 creates cluster 30, row 1 creates cluster 31, and a later row can merge cluster 30 with a single point.
from scipy.cluster.hierarchy import linkage
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=30, centers=3, random_state=0)
Z = linkage(X, method="ward")
n = X.shape[0]
for i in range(3):
a, b, dist, size = Z[i]
print(f"row {i}: merge {int(a)} and {int(b)} at {dist:.3f}, new cluster {n + i} has {int(size)} points")Input forms and a common mistake
linkage accepts two kinds of input:
- A 2-D array of observations, with one row per sample. This is the usual case.
- A condensed distance matrix, which is a 1-D array holding the upper triangle of the pairwise distance matrix. You can build one with
scipy.spatial.distance.pdist.
Passing a full square distance matrix is a frequent error. scipy treats a 2-D array as observations, so it would silently compute distances between rows of distances. If you have a precomputed square matrix, convert it with squareform first.
import numpy as np
from scipy.cluster.hierarchy import linkage
from scipy.spatial.distance import pdist, squareform
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=20, centers=2, random_state=1)
condensed = pdist(X, metric="euclidean")
square = squareform(condensed)
Z_from_condensed = linkage(condensed, method="average")
Z_from_square = linkage(squareform(square), method="average")
print(np.allclose(Z_from_condensed, Z_from_square))Ward linkage is defined for Euclidean distance. In scipy, method="ward" with a condensed matrix assumes the distances are Euclidean, and it will not warn you if they are not. For other metrics, use average or complete.
Cutting the tree with fcluster
The function fcluster turns the tree into flat labels. Its criterion argument decides what t means.
| `criterion` | Meaning of `t` | Typical use |
|---|---|---|
| `maxclust` | Maximum number of clusters | You know how many groups you want |
| `distance` | Merge-distance threshold | You know how far apart groups must be |
| `inconsistent` | Inconsistency threshold | Cut relative to nearby merge heights |
Labels from fcluster start at 1, not 0. This differs from scikit-learn, which starts at 0. Remember this when you index into arrays by label.
from scipy.cluster.hierarchy import linkage, fcluster
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=60, centers=3, random_state=3)
Z = linkage(X, method="ward")
by_count = fcluster(Z, t=3, criterion="maxclust")
by_distance = fcluster(Z, t=10.0, criterion="distance")
print(sorted(set(by_count)))
print(len(set(by_distance)))A distance cut is tied to the scale of your data. The same threshold gives different results after you rescale features, so choose it by looking at the dendrogram.
Drawing the dendrogram
The dendrogram draws each merge at the height where it happened. Large vertical gaps suggest natural places to cut.
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import linkage, dendrogram
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=30, centers=3, random_state=0)
Z = linkage(X, method="average")
dendrogram(Z)
plt.xlabel("sample index")
plt.ylabel("merge distance")
plt.show()For hundreds of points the full plot is unreadable. Pass truncate_mode="lastp" with p=12 to show only the last 12 merged clusters. The leaf labels then show cluster sizes in parentheses.
Clustering with scikit-learn
AgglomerativeClustering wraps the same algorithm in an estimator. You give it the number of clusters and a linkage name.
from sklearn.cluster import AgglomerativeClustering
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=200, centers=3, random_state=42)
for link in ["single", "complete", "average", "ward"]:
model = AgglomerativeClustering(n_clusters=3, linkage=link)
labels = model.fit_predict(X)
print(link, sorted(set(labels)))This loop makes it easy to compare linkage criteria on the same data. Printing only the label set, as above, confirms that three clusters came out but says nothing about their quality. Compare sizes with np.bincount(labels) or use a metric from the evaluation chapter.
Getting the full tree from scikit-learn
If you set distance_threshold and n_clusters=None, the estimator builds the full tree and exposes the merge history. This lets you cut by distance without calling scipy.
from sklearn.cluster import AgglomerativeClustering
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=100, centers=3, random_state=5)
model = AgglomerativeClustering(n_clusters=None, distance_threshold=0, linkage="ward")
model.fit(X)
print(model.n_clusters_)
print(model.children_.shape)
print(model.distances_.shape)With distance_threshold=0, every point ends up in the tree and distances_ holds the merge distances. The children_ attribute plays the role of the first two columns of Z. You can only set one of n_clusters and distance_threshold. Setting both raises an error, and setting neither also raises an error.
The data flow
The diagram shows how the two libraries relate. Both start from the same data and the same linkage choice, and differ in where the cut happens.
Common errors
- Skipping scaling. Distances are dominated by the feature with the largest range. Standardize with
StandardScalerbefore clustering unless the features share units. - Using Ward with a non-Euclidean metric. In scikit-learn,
linkage="ward"requiresmetric="euclidean"and raises an error otherwise. In scipy it fails silently, as noted above. - Confusing label bases.
fclusterlabels start at 1, and scikit-learn labels start at 0. - Cutting at the wrong scale. A
distancethreshold chosen on unscaled data stops making sense after scaling. - Reading the dendrogram's leaf order as meaningful. The horizontal order of leaves is only chosen so that branches do not cross. Neighbors in the plot are not necessarily close in the data. Only the merge height carries distance information.
- Running on large data. Memory use is quadratic in the number of samples for the standard algorithm. Tens of thousands of points is a practical ceiling on ordinary hardware.
A short worked pipeline
This example puts scaling, tree construction, and cutting together, and checks that the two libraries agree.
import numpy as np
from scipy.cluster.hierarchy import linkage, fcluster
from sklearn.cluster import AgglomerativeClustering
from sklearn.datasets import make_blobs
from sklearn.metrics import adjusted_rand_score
from sklearn.preprocessing import StandardScaler
X, _ = make_blobs(n_samples=150, centers=3, random_state=11)
X = StandardScaler().fit_transform(X)
Z = linkage(X, method="ward")
scipy_labels = fcluster(Z, t=3, criterion="maxclust") - 1
sk_labels = AgglomerativeClustering(n_clusters=3, linkage="ward").fit_predict(X)
print(np.bincount(scipy_labels))
print(np.bincount(sk_labels))
print(adjusted_rand_score(scipy_labels, sk_labels))Subtracting 1 aligns the scipy labels with scikit-learn's base. The adjusted Rand index compares two labelings while ignoring how the clusters are numbered. A value of 1.0 means identical partitions, which is expected here because both libraries use Ward linkage on the same data.
Exercises
Exercise
You call linkage on 50 samples. What shape is Z, and what does a value of 52 in column 0 or 1 of some row mean?
Show answer
Z has shape (49, 4), because 50 points need 49 merges. An index of 52 is at least 50, so it refers to a cluster created by an earlier merge, not an original point. It is the cluster made by row 52 - 50 = 2, which is the third merge.
Exercise
You standardize your data, then cut the tree with fcluster(Z, t=5.0, criterion="distance") using a threshold you chose earlier on unscaled data. Why is the result unreliable, and what should you do instead?
Show answer
Scaling changes all pairwise distances, so merge heights in the new tree are on a different scale and 5.0 no longer corresponds to the same cut. Rebuild Z on the scaled data, look at its dendrogram, and choose a new threshold from the gaps in that plot, or use criterion="maxclust" if you know the number of clusters.
Exercise
Write the scikit-learn arguments that build the full tree for Ward linkage and expose the merge distances, and say what happens if you also pass n_clusters=3.
Show answer
Use AgglomerativeClustering(n_clusters=None, distance_threshold=0, linkage="ward"), then read distances_ after fitting. Passing n_clusters=3 together with a distance_threshold raises an error, because only one of the two may be set.