Lesson 5 of 9
Hierarchical Agglomerative Clustering & Dendrogram Interpretation
Hierarchical Agglomerative Clustering (HAC) builds a bottom-up nested tree of clusters. Starting with each sample in its own singleton cluster, HAC iteratively merges the two closest clusters based on a Linkage Criterion: Ward's Linkage (minimizes within-cluster variance increase), Complete Linkage (maximum pairwise distance), Average Linkage (mean pairwise distance), or Single Linkage (minimum pairwise distance). The resulting Dendrogram visualizes data hierarchies across all scales.
Hierarchical Clustering & Dendrogram Linkage Analysis
import numpy as np
import pandas as pd
from scipy.cluster.hierarchy import dendrogram, linkage, fcluster
from sklearn.cluster import AgglomerativeClustering
from sklearn.preprocessing import StandardScaler
# Ingest sample customer purchase attributes
np.random.seed(42)
X_raw = np.array([
[10, 5], [12, 6], [11, 4], # Cohort 1: Low spend, low visits
[80, 85], [85, 90], [78, 88], # Cohort 2: High spend, high visits
[20, 80], [25, 85], [22, 82], # Cohort 3: Low spend, high visits
])
scaler = StandardScaler()
X = scaler.fit_transform(X_raw)
# 1. COMPUTE HIERARCHICAL LINKAGE MATRIX USING SCIPY
# Ward linkage: minimizes the sum of squared differences within all clusters
Z = linkage(X, method='ward')
print("=== HIERARCHICAL LINKAGE MATRIX (Z) ===")
# Z columns: [cluster_idx_1, cluster_idx_2, distance, new_cluster_sample_count]
print("Last 3 Merges:")
for i, merge in enumerate(Z[-3:], 1):
print(f" Step {i}: Merged cluster {int(merge[0])} & {int(merge[1])} at distance {merge[2]:.4f} (Size: {int(merge[3])})")
# 2. CUTTING THE TREE AT DISTANCE THRESHOLD OR CLUSTER COUNT
# Cut dendrogram to form exactly 3 clusters
cluster_labels = fcluster(Z, t=3, criterion='maxclust')
print(f"\nExtracted Cluster Assignments for 9 points: {cluster_labels}")
# 3. SCIKIT-LEARN AGGLOMERATIVE CLUSTERING
hac = AgglomerativeClustering(n_clusters=3, linkage='ward')
hac_labels = hac.fit_predict(X)
print(f"Scikit-Learn HAC Labels: {hac_labels}")Pro Tip: When to Use Ward's Linkage
Default to `linkage='ward'`. Ward's method is the agglomerative analogue of K-Means: it minimizes the variance increase at each step, yielding compact, well-separated, balanced clusters. Complete linkage produces spherical clusters of equal diameter; single linkage produces elongated chain-like clusters.
MlHierarchicalClustering Visual Representation
Hands-On Challenge: Plotting a Scipy Dendrogram
Using `scipy.cluster.hierarchy.dendrogram`, render an annotated dendrogram tree plot with horizontal color thresholds highlighting the natural 3-cluster partition.
Quick Quiz & Key Concept Checks
Common Pitfall: Cutting the Dendrogram Manually Without Validation
Visually choosing where to slice a dendrogram introduces human bias. Always compute quantitative cluster validation metrics (Silhouette score, Davies-Bouldin index) across multiple slice thresholds to objectively determine the optimal cluster count.