Lesson 40
Hierarchical Clustering
Merge the closest points into clusters step by step, and cut the tree when you want a set of groups. One example is on this page.
Intermediate12 min
What You Will Learn
- Idea
- Example
- When to use it
Idea
Agglomerative clustering starts with one cluster per point. Each step merges the two closest clusters. The history of merges is a tree. Choosing a number of clusters is a cut through that tree, so you can inspect several cuts without refitting from scratch.
Example
import numpy as np
from sklearn.cluster import AgglomerativeClustering
X = np.array([[1, 1], [1.2, 0.8], [5, 5], [5.3, 4.7]], dtype=float)
labels = AgglomerativeClustering(n_clusters=2).fit_predict(X)
print(labels.tolist())Output:
[1, 1, 0, 0]When to use it
- Use it when you want to see which groups join if you ask for fewer clusters.
- It is comfortable on hundreds or a few thousand rows, not on millions.
- The linkage choice changes whether big groups swallow small ones.
Loading playground…