Sub topic 8
Hierarchical clustering with scipy and scikit-learn
This chapter assumes you know how linkage criteria work, what a dendrogram shows, and why features should be scaled before clustering. It covers the two main Python interfaces and the mistakes people make with them.
Two libraries, two roles
scipy builds the full merge tree. scikit-learn returns flat cluster labels directly.
| Task | scipy | scikit-learn |
|---|---|---|
| Build the tree | `linkage` | Done internally |
| Plot the tree | `dendrogram` | Not provided |
| Get flat labels | `fcluster` | `fit_predict` |
| Label numbering | Starts at 1 | Starts at 0 |
Use scipy when you want to inspect the tree and choose a cut. Use scikit-learn when you already know the number of clusters or want a pipeline-friendly estimator.
The scipy workflow
linkage returns a matrix Z with n − 1 rows, one per merge. Each row holds the two merged cluster indices, the merge distance, and the size of the new cluster. fcluster then cuts the tree.
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.shape is (29, 4).
The scikit-learn workflow
AgglomerativeClustering takes n_clusters and a linkage name. It has fit_predict but no predict, so it cannot label new points. The two libraries should agree when they use the same linkage and metric. The next example checks that with the adjusted Rand index, which is 1.0 when two labelings describe the same partition.
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=200, centers=3, random_state=42)
X = StandardScaler().fit_transform(X)
Z = linkage(X, method="ward")
scipy_labels = fcluster(Z, t=3, criterion="maxclust")
sk_labels = AgglomerativeClustering(n_clusters=3, linkage="ward").fit_predict(X)
print(adjusted_rand_score(scipy_labels, sk_labels))The score should print 1.0. The label numbers differ, which is why the example compares partitions and not raw labels.
Cutting by distance instead of count
If you do not know the cluster count, cut at a merge distance. In scipy, use criterion="distance". In scikit-learn, set n_clusters=None and pass distance_threshold.
from scipy.cluster.hierarchy import fcluster
from sklearn.cluster import AgglomerativeClustering
labels_scipy = fcluster(Z, t=5.0, criterion="distance")
model = AgglomerativeClustering(n_clusters=None, distance_threshold=5.0, linkage="ward")
labels_sk = model.fit_predict(X)Pick the threshold from the dendrogram, in a large vertical gap. Ward distances depend on the data's scale, so a threshold that works on one dataset will not transfer to another.
Common errors
- Passing a square distance matrix to
linkage. scipy reads a 2-D array as raw observations. For precomputed distances, convert withscipy.spatial.distance.squareformto get the condensed form. - Using Ward with a non-Euclidean metric. Ward assumes Euclidean distance. In scikit-learn,
linkage="ward"only works with the default Euclidean metric. - Skipping scaling. A feature with a large range dominates every merge.
- Mixing up label bases.
fclusterlabels start at 1 and scikit-learn labels start at 0. Subtract 1 before indexing arrays by label.
Exercise
You call linkage(D, method="average") where D is a 100×100 symmetric matrix of pairwise distances, and the result has the wrong number of rows. What went wrong, and how do you fix it?
Show answer
scipy treated D as 100 observations with 100 features each, not as distances. Convert it with squareform(D) to the condensed form and pass that to linkage. The result then has 99 rows.