2.5.4Unsupervised Learning

Hierarchical clustering (agglomerative - divisive)

3,070 words14 min readdifficulty · medium4 backlinks

What is Hierarchical Clustering?

Why This Matters

Problem K-Means solves poorly: You have customer data but don't know if you should segment into 3, 5, or 10 groups. K-Means forces you to guess K, then start over if wrong.

Hierarchical solution: Build the full tree ONCE, then examine it to choose the natural number of clusters. The tree shows you WHERE the big separations occur.

The Two Approaches

1. Agglomerative Clustering (Bottom-Up)

Derivation of Complexity:

  • nn points, iteration kk has (nk+1)(n-k+1) clusters
  • Computing all pairwise distances: (nk+12)=O((nk)2)\binom{n-k+1}{2} = O((n-k)^2) comparisons
  • Total: k=1n1(nk)2=O(n3)\sum_{k=1}^{n-1} (n-k)^2 = O(n^3) for naive implementation
  • With priority queue (heap): O(n2logn)O(n^2 \log n)

2. Divisive Clustering (Top-Down)

Linkage Criteria (The Heart of Aglomerative)

The linkage criterion L(Cp,Cq)L(C_p, C_q) defines "distance between clusters". This choice drastically changes cluster shapes.

Derivation of Ward's Formula:

Within-cluster sum of squares for merged cluster CpCqC_p \cup C_q: SSmerged=xCpCqxμmerged2SS_{merged} = \sum_{x \in C_p \cup C_q} ||x - \mu_{merged}||^2

where μmerged=Cpμp+CqμqCp+Cq\mu_{merged} = \frac{|C_p|\mu_p + |C_q|\mu_q}{|C_p| + |C_q|}

Expanding: SSmerged=xCpxμmerged2+xCqxμmerged2SS_{merged} = \sum_{x \in C_p} ||x - \mu_{merged}||^2 + \sum_{x \in C_q} ||x - \mu_{merged}||^2

Using parallel axis theorem: xμnew2=xμold2+nμoldμnew2\sum ||x - \mu_{new}||^2 = \sum ||x - \mu_{old}||^2 + n|\mu_{old} - \mu_{new}||^2

After algebra: ΔSS=merged(SSp+SSq)=CpCqCp+Cqμpμq2\Delta SS =_{merged} - (SS_p + SS_q) = \frac{|C_p| |C_q|}{|C_p| + |C_q|} |\mu_p - \mu_q||^2

Why this matters: Ward's minimizes the INCREASE in total within-cluster variance from merging, producing compact, roughly equal-sized clusters.

The Dendrogram: Reading the Tree

How to choose number of clusters:

  1. Look for large vertical gaps (big increase in merge distance)
  2. Cut at height just before a large jump
  3. The number of vertical lines you cut through = number of clusters

Implementation Details

Distance Metric (usually Euclidean): d(xi,xj)=xixj2=k=1d(xikxjk)2d(x_i, x_j) = ||x_i - x_j||_2 = \sqrt{\sum_{k=1}^d (x_{ik} - x_{jk})^2}

For high-dimensional data, consider:

  • Manhattan: d=xikxjkd = \sum |x_{ik} - x_{jk}| (robust to outliers)
  • Cosine: d=1xixjxixjd = 1 - \frac{x_i \cdot x_j}{||x_i|| ||x_j|} (angle-based, good for text)

Update Formula (Lance-Williams): After merging clusters CiC_i and CjC_j into CkC_k, update distances to remaining cluster CmC_m:

d(Ck,Cm)=αid(Ci,Cm)+αjd(Cj,Cm)+βd(Ci,Cj)+γd(Ci,Cm)d(Cj,Cm)d(C_k, C_m) = \alpha_i d(C_i, C_m) + \alpha_j d(C_j, C_m) + \beta d(C_i, C_j) + \gamma |d(C_i, C_m) - d(C_j, C_m)|

Parameters for different linkages:

  • Single: αi=αj=0.5,β=0,γ=.5\alpha_i = \alpha_j = 0.5, \beta = 0, \gamma = -.5 (min of two distances)
  • Complete: αi=αj=0.5,β=0,γ=0.5\alpha_i = \alpha_j = 0.5, \beta = 0, \gamma = 0.5 (max of two distances)
  • Average: αi=CiCi+Cj,αj=CjCi+Cj,β=γ=0\alpha_i = \frac{|C_i|}{|C_i|+|C_j|}, \alpha_j = \frac{|C_j|}{|C_i|+|C_j|}, \beta = \gamma = 0

Advantages & Disadvantages

Advantages:

  1. No need to specify K upfront — explore multiple granularities from one tree
  2. Interpretable output — dendrogram shows cluster relationships and hierarchy
  3. Deterministic — same data always gives same tree (unlike K-Means' random init)
  4. Works with any distance metric — not limited to Euclidean space

Disadvantages:

  1. Computational cost: O(n2logn)O(n^2 \log n) time, O(n2)O(n^2) space (distance matrix)
    • K-Means is O(nkdi)O(nkd \cdot i) where ii = iterations, usually much faster
  2. Gredy and irreversible — early merge mistakes can't be undone
  3. Sensitive to outliers (especially single linkage)
  4. Not scalable — impractical for n>10,000n > 10,000 points without approximations

When to use hierarchical:

  • Small-to-medium datasets (n<10,000n < 10,000)
  • Need cluster hierarchy, not just flat partition
  • Exploratory analysis to determine natural K
  • Biological taxonomy, document hierarchies (true hierarchical structure)

When to avoid:

  • Large datasets (use K-Means, DBSCAN, or mini-batch variants)
  • Clusters with complex shapes (use DBSCAN instead)
  • Need to update clusters as new data arrives (hierarchical requires full rebuild)
Recall Explain to a 12-year-old

Imagine you have a bunch of LEGO bricks scattered on the floor, different colors and sizes. Hierarchical clustering is like organizing them into groups.

Aglomerative (bottom-up): You start by picking up each brick. Then you look for two bricks that are MOST similar (maybe both red, or both 2x4 size) and put them together. Then you keep doing this: find the two groups that are most similar and combine them. Maybe you combine two red piles, or a red pile with a pink pile (they're kinda similar!). Eventually, all your bricks are in one giant pile.

The cool part? You took a video the whole time. Now you can rewind and stop at ANY point to see different groupings. Maybe you want3 piles (primary colors), or 10 piles (every shade), or 100 piles (nearly every brick separate). You don't have to choose until you see the video!

Divisive (top-down): This is like doing it backwards. Start with all bricks in one pile, then split it into two groups (maybe "red-ish" vs "blue-ish"). Then split each of those groups again, and again, until every brick is alone.

The "dendrogram" is like a family tree of your LEGO bricks, showing which bricks are "related" (similar) and which are "distant cousins" (very different). The height of each branch shows HOW different the groups were when you combined them.

Connections

  • K-Means Clustering — flat clustering requiring K upfront; hierarchical helps choose K
  • DBSCAN — density-based alternative; better for non-convex clusters, hierarchical better for interpretability
  • Distance Metrics — Euclidean, Manhattan, Cosine choice drastically affects clustering
  • Dendrogram Visualization — tree representation of cluster hierarchy
  • Elbow Method — used to determine optimal K; applied to dendrogram merge heights
  • Single-Link vs Complete-Link — trade-off between sensitivity to chaining vs outliers
  • Time Complexity AnalysisO(n3)O(n^3) naive, O(n2logn)O(n^2 \log n) optimized vs K-Means O(nkd)O(nkd)
  • Gredy Algorithms — hierarchical uses gredy merging, not globally optimal
  • Within-Cluster Sum of Squares — Ward's method minimizes WCSS increase

#flashcards/ai-ml

What are the two main types of hierarchical clustering? :: Agglomerative (bottom-up merging) and Divisive (top-down splitting)

What is the output of hierarchical clustering?
A dendrogram (tree structure) showing cluster relationships at all levels of granularity, not just a single partition
What is the time complexity of aglomerative clustering with a priority queue?
O(n2logn)O(n^2 \log n) time and O(n2)O(n^2) space for the distance matrix
What is single linkage criterion?
Distance between clusters = minimum distance between any two points from the two clusters: minxiCp,xjCqd(xi,xj)\min_{x_i \in C_p, x_j \in C_q} d(x_i, x_j)
What is complete linkage criterion?
Distance between clusters = maximum distance between any two points from the two clusters: maxxiCp,xjCqd(xi,xj)\max_{x_i \in C_p, x_j \in C_q} d(x_i, x_j)
What is Ward's linkage criterion?
Merges clusters that minimize the increase in total within-cluster variance: CpCqCp+Cqμpμq2\frac{|C_p||C_q|}{|C_p|+|C_q|}|\mu_p - \mu_q||^2
What is the chaining effect in single linkage?
Single linkage connects clusters through outlier bridges or noise points, creating elongated chains instead of compact clusters
How do you choose the number of clusters from a dendrogram?
Look for large vertical gaps (big jumps in merge height) and cut the dendrogram horizontally just before a large jump
What is the main advantage of hierarchical clustering over K-Means?
No need to specify K upfront — you get cluster structure at all granularities and can choose K by examining the dendrogram
Why is hierarchical clustering not globally optimal?
It uses gredy local decisions at each merge step. Once two clusters are merged, they never split, so early mistakes propagate
When should you use complete linkage over single linkage?
Use complete linkage when you want compact, well-separated clusters and your data has noise or outliers. Single linkage sufers from chaining in these cases
What is the main disadvantage of hierarchical clustering for large datasets?
O(n2)O(n^2) space for distance matrix and O(n2logn)O(n^2 \log n) time makes it impractical for n>10,000n > 10,000 points
What does the height of a merge in a dendrogram represent?
The distance or dissimilarity between the two clusters being merged at that step
How does average linkage differ from single and complete linkage?
Average linkage uses the mean of all pairwise distances between clusters, providing a compromise between single (minimum) and complete (maximum)
Why is Ward's method good for creating balanced clusters?
It minimizes within-cluster variance increase, which naturally produces compact clusters of similar size and low internal variance

Concept Map

builds

bottom-up

top-down

uses

repeatedly

records

repeatedly

uses

records

big jump marks

choose K by

naive cost

Hierarchical Clustering

Dendrogram Tree

Agglomerative AGNES

Divisive DIANA

Linkage Criterion L

Merge Nearest Clusters

Split Largest Cluster

Merge/Split Height

K-Means Split K=2

Cut Tree Later

Complexity O n cubed

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Hierarchical clustering ek bahut powerful technique hai jisme hum data points ko tree structure mein organize karte hain. Socho jaise family tree hota hai — sabse niche individual log, phir chhote families, phir bade families, aur top peura extended family. Isi tarah, hierarchical clustering mein hum data points ko gradually merge ya split karte hain.

Do main approaches hain: Agglomerative (bottom-up) aur Divisive (top-down). Agglomerative mein hum har point ko alag cluster consider karte hain, phir sabse similar clusters ko merge karte jate hain jab tak sab ek cluster mein na aa jaayein. Divisive mein ulta — sabhi points ek cluster mein start karte hain, phir split karte karte individual points tak pahunchte hain. Agglomerative zyada common hai kyunki computationally efficient hai.

Sabse interesting part hai linkage criterion — yeh decide karta hai ki do clusters ke bech distance kaise measure karein. Single linkage (nearest points), complete linkage (farthest points), average linkage (sabka average), aur Ward's method (variance minimize karo) — harek different shape ke clusters banata hai. Output ek

Go deeper — visual, from zero

Test yourself — Unsupervised Learning

Connections