typestar

Hierarchical clustering in Python

linkage builds the tree, fcluster cuts it into groups.

import numpy as np
from scipy.cluster import hierarchy

points = np.array([[1.0, 1.0], [1.2, 0.9], [5.0, 5.1],
                   [5.3, 4.8], [9.0, 9.2]])

tree = hierarchy.linkage(points, method="ward")
print(tree.shape, tree[:, 2].round(2))

groups = hierarchy.fcluster(tree, t=3, criterion="maxclust")
print(groups)
print(hierarchy.fcluster(tree, t=2.0, criterion="distance"))
print(round(hierarchy.cophenet(tree)[0], 3))

How it works

  1. linkage takes observations and a method.
  2. fcluster cuts at a distance or a cluster count.
  3. dendrogram data comes out of the same linkage matrix.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
405
Tokens
138
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 75 seconds.

Type this snippet

Step 4 of 4 in Sparse & spatial, step 22 of 23 in Scientific computing with SciPy.

← Previous Next →