Machine Learning Slides 📂 Introduction · 25 of 25 43 min read

Hierarchical Clustering: Build the Tree, Then Choose K

No need to pick K up front — hierarchical clustering merges the closest clusters over and over, building a dendrogram that encodes every grouping at once. Cut it at any height to read off your clusters. This tutorial covers agglomerative vs divisive, the four linkage methods, distance metrics, reading the tree by its biggest gap, choosing K, complexity limits, and K-Means comparison — with animated diagrams.

🌳

Hierarchical Clustering

Don't pick K up front — build a whole tree of nested groupings by repeatedly merging the closest clusters, then slice that dendrogram at any height to read off however many clusters you want.
Dendrogram Agglomerative Linkage Cut For K

Press Next → or use ← → arrow keys

Section 01

The Intuition — The Librarian's Bookshelf

Merging the closest piles, again and again
A librarian faces a table of loose books. She picks the two most similar books and sets them side by side. Then she finds the next-closest pair — maybe two books, maybe a book and the pair she just made — and merges them too. She keeps merging the closest piles until everything sits in one big stack.

Every merge is recorded, so the whole history forms a branching tree. Want four groups? Cut the tree where four branches exist. Want two? Cut higher. That tree is a dendrogram, and building it is hierarchical clustering.
💡
The Big Win: No K Up Front

Unlike K-Means, you don't commit to the number of clusters before running. One fit produces a full tree of every possible grouping — you decide K afterward by choosing where to cut.

Section 01 · Two Directions

Bottom-Up vs Top-Down

Agglomerative (AGNES) · bottom-up 5 singleton clusters merge closest pairs → one cluster Divisive (DIANA) · top-down one big cluster split most-mixed cluster → down to singletons
🔄
Same Tree, Opposite Directions

Agglomerative (AGNES) starts from singletons and merges upward — it's what people almost always mean by "hierarchical clustering." Divisive (DIANA) starts from one cluster and splits downward; it's elegant but O(2ⁿ) and rarely used in production.

Section 02 · Algorithm

Agglomerative Clustering — Five Steps

🔁 Merge The Closest, Then Recompute
1Start with every point as its own cluster — n points, n clusters.
2Compute the proximity matrix — pairwise distances between all clusters.
3Merge the two closest clusters into one.
4Update distances from the new cluster to all others using the chosen linkage.
5Repeat steps 3–4 until a single cluster remains — recording every merge as the dendrogram.
🧮
The Linkage Choice Drives Everything

Step 4 is where the personality of the algorithm lives. "Distance between two clusters" isn't one thing — it depends on the linkage rule (single, complete, average, Ward…), and that choice can completely change the shape of the clusters you get.

Section 02 · Diagram

Building The Dendrogram — Five Cities

10 20 30 55 merge distance A B C D E cut → 2 clusters {A,B} {C,D,E}
🏙️
Merge Height = Dissimilarity

A and B merge first (distance 10), then C and D (20), then E joins them (30), and finally the two groups fuse at the top (55). The height of each bar is how different the merged clusters were. Slide a cut line to d≈40 and it crosses two branches → two clusters: {A,B} and {C,D,E}.

Section 03 · Linkage

How To Measure Distance Between Clusters

Single = MIN closest pair Complete = MAX farthest pair Average = MEAN avg of all pairs Ward = VARIANCE ⭐ merge = least ↑ spread
🔗
Four Ways To Define "Cluster Distance"

Single uses the closest pair (can chain into long straggly clusters). Complete uses the farthest pair (tight, compact). Average takes the mean of all pairs (a balanced compromise). Ward merges whichever pair adds the least within-cluster variance — the go-to default for tabular data.

Section 03 · Reference

Linkage Methods — Behaviour & Best Fit

LinkageDistance ruleBehaviourBest for
SingleMin pairwiseChaining → elongatedManifolds, irregular shapes
CompleteMax pairwiseTight; outlier-sensitiveEqual-size, compact clusters
Average (UPGMA)Mean pairwiseBalanced compromiseGeneral purpose, bioinformatics
Ward ⭐Min variance increaseCompact, balancedMost tabular tasks (default)
Centroid / MedianCentroid distanceCan invert dendrogramRarely used today
📐
Ward Needs Euclidean Distance

Ward's method is built on minimizing squared-error variance, so it's only mathematically meaningful with Euclidean distance. If you need cosine or Manhattan distance (text, sparse, or profile data), use average or complete linkage instead.

Section 04 · Distance

Choosing The Distance Metric

Euclidean (L2) · default
√ Σ (aᵢ − bᵢ)²
Straight-line distance for continuous numeric data. Requires scaling. Pairs with Ward.
Manhattan (L1)
Σ | aᵢ − bᵢ |
City-block distance — more robust to outliers and good for high-dimensional / sparse data.
Cosine
1 − (a · b)/(‖a‖‖b‖)
Angle-based; ignores magnitude, captures direction. The choice for text / NLP embeddings.
Correlation / Hamming
1 − r · count of differing bits
Correlation for profile/time-series (genomics); Hamming for binary / categorical.
🧭
Match The Metric To The Meaning

Ask what "similar" means for your data. Similar values → Euclidean. Similar direction regardless of scale → cosine. Similar shape over time → correlation distance. Similar categories → Hamming. The metric encodes your definition of similarity.

Section 05 · Reading

Reading The Tree — The Biggest-Gap Rule

longest gap cut → 3 clusters
✂️
Cut Across The Tallest Uninterrupted Gap

Find the longest vertical stretch that no horizontal merge crosses — the biggest jump in dissimilarity — and cut just below where it ends. The number of vertical lines your cut crosses is the natural K. Here the tall gap before the final merge gives a clean 3 clusters.

Section 05 · Validating K

Back Up The Cut With Numbers

📏
Silhouette
−1 … +1 · higher better
s = (b−a)/max(a,b). Sweep K=2–10 and keep the peak; > 0.5 signals solid structure.
📈
Calinski–Harabasz
higher better
Ratio of between-cluster to within-cluster dispersion. Fast, and rewards well-separated, tight clusters.
📉
Davies–Bouldin
lower better
Average ratio of cluster scatter to separation. Lower means clusters are compact and far apart.
🎯
Eye The Gap, Confirm With A Metric

The dendrogram gives you a visual candidate K; the metrics confirm it objectively. In a typical 150-sample run, K=3 topped the silhouette at 0.72 — matching the biggest visual gap. When the two disagree, trust the metric and re-examine the tree.

Section 06 · Preprocessing

Scale Before You Cluster

⚠️
Unscaled Features Hijack The Distances

Hierarchical clustering is built entirely on distances, and distance is dominated by whichever feature has the largest range. If income spans 0–100,000 and age spans 0–100, the tree forms on income alone. StandardScaler (or MinMaxScaler) first puts every feature on an equal footing.

Before building the linkage matrix: scale numeric features, encode categoricals (or use Hamming distance), vectorize text with TF-IDF and cosine distance, and — for time-series or gene profiles — use correlation distance so clusters form on the shape of the signal rather than its absolute level. Never feed raw, mixed-scale data straight in.
Section 07 · Code

scipy To Explore · sklearn To Ship

# ── scipy: build + visualize the tree ──
from scipy.cluster.hierarchy import linkage, dendrogram, fcluster
from sklearn.preprocessing import StandardScaler

X_scaled = StandardScaler().fit_transform(X)   # always scale first
Z = linkage(X_scaled, method='ward', metric='euclidean')
dendrogram(Z, color_threshold=5.0)          # inspect the gaps
labels = fcluster(Z, t=3, criterion='maxclust')

# ── sklearn: production clustering ──
from sklearn.cluster import AgglomerativeClustering
hac = AgglomerativeClustering(n_clusters=3, linkage='ward')
labels = hac.fit_predict(X_scaled)
🛠️
Two Libraries, Two Jobs

Use scipy's linkage + dendrogram to explore the tree and pick K, then switch to sklearn's AgglomerativeClustering for the production fit. Prefer distance_threshold over n_clusters when you'd rather cut by a dissimilarity height than a fixed count.

Section 08 · Scalability

The Cost — And When To Stop

MethodTimeSpacePractical limit
Naive agglomerativeO(n³)O(n²)~1,000 rows
Optimized (NN-chain)O(n²)O(n²)~10,000 rows
sklearnO(n² log n)O(n²)~50,000 rows
K-Means (for contrast)O(nKt)O(nK)Millions
💾
The n × n Distance Matrix Is The Bottleneck

Storing all pairwise distances for 10,000 points is 100 million values (~800 MB); it grows with the square of your data. Past ~50,000 rows, cluster a random 5,000–10,000 sample to find K and the structure, then run K-Means (or DBSCAN) on the full dataset.

Section 09 · Comparison

Hierarchical vs K-Means

PropertyHierarchicalK-Means
Pre-specify K?No — cut afterYes — up front
Cluster shapesArbitrary (linkage-dependent)Spherical only
Scalability≤ ~50K rowsMillions
Deterministic?YesNo (random init)
InterpretabilityVery high (dendrogram)Moderate
Best use caseExploration, unknown K, small dataLarge data, known K, speed
🧭
The Decision Rule

Choose hierarchical when the dataset is under ~50K rows, K is unknown, and you want the interpretable story a dendrogram tells. Choose K-Means when data is large, K is known, clusters are roughly round, and speed matters most.

Section 10 · Applications

Where The Dendrogram Earns Its Keep

🛍️
Customer Segmentation
On 800 bank customers, Ward linkage + silhouette found K=4 — High-Value Professionals, Budget-Conscious, Digital-Native, and Pre-Retirement segments, each with tailored offers.
🧬
Gene Expression
50 genes × 8 conditions with correlation distance + average linkage → 3 co-expression groups (silhouette 0.88), grouping genes by how they move together, not their raw level.
📑
Docs & Taxonomies
TF-IDF + cosine distance groups articles or tickets into topic trees — and the dendrogram itself becomes a browsable hierarchy.
🔬
The Tree Is Part Of The Answer

In genomics, taxonomy, and phylogenetics, the nesting itself is the insight — which groups are sub-groups of which. That's a story K-Means can't tell, and it's why hierarchical clustering remains the default in these fields.

Section 11 · Golden Rules

Seven Rules For Hierarchical Clustering

🏅 Hierarchical Clustering, Distilled
1Always scale features first — unscaled columns dominate every distance.
2Default to Ward + Euclidean for tabular data — the most battle-tested combination.
3Always plot the dendrogram before choosing K, then confirm with silhouette across K=2–10.
4Use correlation distance for time-series / profile data where signal shape matters.
5Encode text & categoricals first — TF-IDF + cosine for text; never feed raw strings.
6Above ~50K rows, sample to find K, then switch to K-Means on the full data.
7Report quality metrics (silhouette, Davies–Bouldin) alongside the business interpretation.
Wrap-Up

You Now Own Hierarchical Clustering

mergeClosest clusters
treeDendrogram of all K
WardDefault linkage
gapCut the tallest
σ=1Scale first
≤50KRow limit
🎯
The Through-Line

Hierarchical clustering merges the closest clusters over and over, recording a dendrogram that encodes every possible K at once. Pick a linkage (usually Ward), scale your features, read the tree by its biggest gap, and confirm K with a silhouette — no cluster count needed up front.

📚
Where To Go Next

Build dendrograms on Iris and a customer dataset with scipy, try Ward vs average vs complete on the same data to feel the difference, then compare against K-Means and DBSCAN to know when each is the right tool.

🌳 End of tutorial · Press to review, or click Restart

You have completed Introduction. View all sections →