Skip to main content
MahiDev — Learn. Build. Become AI-ready.

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
Hierarchical Clustering MahiDev

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

python
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:

text
[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…