TExcelTAD
Home › SciPy › SciPy Hierarchical Clustering

SciPy Hierarchical Clustering

K-means needs the number of clusters up front. Hierarchical clustering doesn't: it builds a whole tree of nested groupings, from every point on its own up to one big cluster, and you decide afterwards where to cut it. The tree is drawn as a dendrogram, which is often the most informative picture of how your data is structured.

The most common variant is agglomerative (bottom-up) clustering:

  1. Start with each point as its own cluster.
  2. Merge the two closest clusters.
  3. Repeat until only one cluster is left.

scipy.cluster.hierarchy implements this with linkage(), and turns the tree into flat clusters with fcluster().

Building the tree

linkage() returns an (n − 1) × 4 matrix: each row records one merge — the two clusters joined, the distance between them, and the size of the new cluster. New clusters get ids starting at n:

python · try it yourself
import numpy as np
from scipy.cluster.hierarchy import linkage

points = np.array([[1, 1], [1.5, 1], [5, 5], [5, 5.5], [9, 1]])
Z = linkage(points, method="single")
print("merge  a  b   distance  size")
for i, (a, b, d, size) in enumerate(Z):
    print(f"{i:5d}  {int(a)}  {int(b)}   {d:8.3f}  {int(size)}")
merge  a  b   distance  size
    0  0  1      0.500  2
    1  2  3      0.500  2
    2  5  6      5.315  4
    3  4  7      5.657  5

Points 0 and 1 merge first (they're 0.5 apart), then 2 and 3. Cluster 5 is the first merged pair, cluster 6 the second, and so on.

Linkage methods

How do you measure the distance between two clusters? The method argument decides:

Method Cluster distance Tends to produce
single closest pair of points long chains; finds odd shapes
complete farthest pair of points compact, similar-sized clusters
average mean of all pairwise distances a compromise
ward increase in within-cluster variance compact, round clusters (like k-means)
centroid / median distance between centres needs Euclidean data

Cutting the tree into clusters

fcluster() turns the tree into flat labels. Cut either at a distance threshold or by asking for a fixed number of clusters:

python · try it yourself
import numpy as np
from scipy.cluster.hierarchy import linkage, fcluster

rng = np.random.default_rng(21)
data = np.vstack([rng.normal([0, 0], 0.4, size=(10, 2)),
                  rng.normal([4, 0], 0.4, size=(10, 2)),
                  rng.normal([2, 4], 0.4, size=(10, 2))])

Z = linkage(data, method="ward")
by_count = fcluster(Z, t=3, criterion="maxclust")
by_distance = fcluster(Z, t=2.0, criterion="distance")
print("3 clusters      :", by_count)
print("cut at height 2 :", np.unique(by_distance).size, "clusters")
print("cluster sizes   :", np.bincount(by_count)[1:])
3 clusters      : [3 3 3 3 3 3 3 3 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1]
cut at height 2 : 4 clusters
cluster sizes   : [10 10 10]

Dendrograms

A dendrogram draws each merge as a bracket at the height of the merge distance. Long vertical gaps mean well-separated clusters — the natural place to cut:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import linkage, dendrogram

cities = ["Hanoi", "Hai Phong", "Da Nang", "Hue", "Ho Chi Minh", "Can Tho", "Vung Tau"]
coords = np.array([[21.03, 105.85], [20.84, 106.69], [16.05, 108.20], [16.46, 107.59],
                   [10.82, 106.63], [10.05, 105.75], [10.35, 107.08]])   # lat, lon

Z = linkage(coords, method="average")
plt.figure(figsize=(7, 4))
info = dendrogram(Z, labels=cities, color_threshold=4, leaf_rotation=30)
plt.ylabel("distance (degrees)")
plt.title("Cities grouped by location")
plt.tight_layout()
plt.show()
print("leaf order:", info["ivl"])
leaf order: ['Can Tho', 'Ho Chi Minh', 'Vung Tau', 'Da Nang', 'Hue', 'Hanoi', 'Hai Phong']

The three regions of Vietnam — north, centre and south — appear as three clear branches.

Is the tree faithful?

The cophenetic correlation measures how well the tree preserves the original pairwise distances (1.0 = perfectly). It's a handy way to compare linkage methods on your data:

python · try it yourself
import numpy as np
from scipy.cluster.hierarchy import linkage, cophenet
from scipy.spatial.distance import pdist

rng = np.random.default_rng(21)
data = np.vstack([rng.normal([0, 0], 0.4, size=(10, 2)),
                  rng.normal([4, 0], 0.4, size=(10, 2)),
                  rng.normal([2, 4], 0.4, size=(10, 2))])
distances = pdist(data)

for method in ["single", "complete", "average", "ward"]:
    c, _ = cophenet(linkage(data, method=method), distances)
    print(f"{method:8}: cophenetic correlation {c:.3f}")
single  : cophenetic correlation 0.956
complete: cophenetic correlation 0.956
average : cophenetic correlation 0.960
ward    : cophenetic correlation 0.958

Tip: linkage() accepts either raw observations or a condensed distance matrix from pdist(). Passing distances lets you cluster with any metric — for example pdist(X, "cosine") for text vectors or pdist(X, "hamming") for binary features.

Test yourself

What is an advantage of hierarchical clustering over k-means?

  1. It's always faster
  2. You don't need to choose the number of clusters before running it
  3. It only works in 2-D
  4. It never needs a distance metric

Which linkage method uses the closest pair of points between two clusters?

  1. complete
  2. average
  3. single
  4. ward

What does fcluster(Z, t=4, criterion='maxclust') do?

  1. Cuts the tree at height 4
  2. Forms at most 4 flat clusters
  3. Computes 4 linkages
  4. Returns the 4th merge