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
linkagetakes observations and a method.fclustercuts at a distance or a cluster count.dendrogramdata comes out of the same linkage matrix.
Keywords and builtins used here
asprintround
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.
Step 4 of 4 in Sparse & spatial, step 22 of 23 in Scientific computing with SciPy.