← Master Index
Vol. 05 Module 5.3 Lecture

Hierarchical Clustering

Unsupervised Learning

How This Lesson Fits the Module

K-Means asks you to choose k before fitting. DBSCAN discovers dense regions and noise. Hierarchical clustering gives a third lens: it builds a tree of nested groups so you can inspect structure at multiple levels.

This lesson is useful when stakeholders want an explainable segmentation path, not just final labels. The dendrogram shows which observations merge, when they merge, and how far apart groups are.

Learning Objectives

By the end of this lesson, students should be able to:

  • Explain agglomerative hierarchical clustering as a bottom-up merge process.
  • Interpret a dendrogram and choose a cut height for cluster labels.
  • Compare linkage strategies: single, complete, average, and Ward.
  • Implement hierarchical clustering with sklearn and scipy.
  • Recognize scale, distance metric, and computational constraints.
  • Decide when hierarchical clustering is more useful than K-Means or DBSCAN.

How Hierarchical Clustering Works

The most common version is agglomerative clustering. It starts with every observation as its own cluster, then repeatedly merges the two closest clusters until everything belongs to one tree. The sequence of merges is displayed as a dendrogram.

The distance between individual points is controlled by the metric, while the distance between groups is controlled by linkage. Linkage choice changes the shape and stability of the resulting clusters.

LinkageHow distance is measuredBest use
SingleClosest pair between clustersCan find chains; sensitive to noise
CompleteFarthest pair between clustersCompact clusters with clear separation
AverageAverage pairwise distanceBalanced default for many exploratory tasks
WardMerge that minimizes variance increaseNumeric Euclidean data; K-Means-like compact groups

sklearn and scipy Implementation

Scale numeric features before distance-based clustering. Use sklearn to create labels and scipy to plot a dendrogram for explanation.

from sklearn.cluster import AgglomerativeClustering from sklearn.preprocessing import StandardScaler from scipy.cluster.hierarchy import linkage, dendrogram import matplotlib.pyplot as plt X_scaled = StandardScaler().fit_transform(X) model = AgglomerativeClustering( n_clusters=4, linkage="ward" ) labels = model.fit_predict(X_scaled) df["cluster"] = labels # Dendrogram for a sample or small dataset Z = linkage(X_scaled, method="ward") plt.figure(figsize=(10, 5)) dendrogram(Z, truncate_mode="level", p=5) plt.title("Hierarchical clustering dendrogram") plt.xlabel("Sample index or merged cluster") plt.ylabel("Merge distance") plt.show()
Engineering Habit — Sample Before Plotting

Dendrograms become unreadable with thousands of rows. For large datasets, plot a representative sample, then fit labels on the full scaled matrix if the algorithm is computationally feasible.

Choosing Cluster Labels

A dendrogram does not force a single answer. You choose a horizontal cut height or specify n_clusters. A good cut usually crosses long vertical branches, meaning groups remain separate until a large merge distance.

Choose by n_clusters

  • Simple for reporting and dashboards
  • Matches business constraints
  • Easy to compare against K-Means
  • Can hide natural nested structure

Choose by distance_threshold

  • Lets the data decide cluster count
  • Useful when merge distances have clear gaps
  • Supports anomaly-like small groups
  • Requires careful visual inspection
Critical Mistake — Treating the Dendrogram as Exact Truth

Hierarchical clustering is deterministic for a fixed setup, but the tree can change when you scale features, change distance metrics, sample rows, or switch linkage. Validate clusters with profiles, stability checks, and domain review.

When to Use Hierarchical Clustering

Use it when…Be careful when…
You need explainable nested groupsThe dataset is very large
The number of clusters is uncertainFeature scales are inconsistent
Stakeholders want to inspect merge historyNoise points create misleading chains
You can afford pairwise distance computationYou need real-time prediction for new points

Knowledge Check

  1. Short Answer: What does agglomerative clustering start with? Answer: Each observation as its own cluster.
  2. True/False: A dendrogram can be cut at different heights to produce different cluster counts. Answer: True.
  3. Multiple Choice: Ward linkage minimizes: (a) variance increase, (b) classification error, (c) entropy. Answer: (a).
  4. Short Answer: Why scale before hierarchical clustering? Answer: Distance calculations are distorted by unequal feature scales.
  5. Short Answer: Name one limitation. Answer: It can be expensive for large datasets and does not naturally predict new points.
  6. True/False: Single linkage is prone to chaining elongated clusters. Answer: True.
  7. Multiple Choice: Complete linkage uses: (a) min pairwise distance, (b) max pairwise distance between clusters, (c) centroid only. Answer: (b).
  8. Short Answer: What is a dendrogram? Answer: A tree diagram showing the order and distance of cluster merges.
  9. True/False: Agglomerative clustering assigns new rows as easily as K-Means centroids. Answer: False—you typically recut or refit; no simple centroid assign.
  10. Multiple Choice: Average linkage: (a) uses mean pairwise distance, (b) is only Ward, (c) ignores scale. Answer: (a).

Key Takeaways

  • Hierarchical clustering builds a tree of nested groups rather than one fixed partition.
  • Dendrograms make cluster structure explainable, but cut height is still a modeling decision.
  • Linkage choice matters: Ward is compact, single can chain, complete is stricter.
  • Scale features and validate clusters with profiles and stability checks.
  • Next: PCA—reduce high-dimensional data into principal components.
Trainer’s Guide

Hands-on idea: Cluster a small customer or Iris dataset with Ward linkage. Have students draw a horizontal cut on the dendrogram, then compare their chosen cut to n_clusters=3 labels.

Discussion prompt: If a business team wants a two-level taxonomy, how would a dendrogram help them explain both broad groups and subgroups?

Recap: Hierarchical clustering builds a dendrogram of nested groups; cut height and linkage are modeling choices. Continue with PCA.