What is hierarchical clustering?
Hierarchical clustering is an unsupervised learning method that organizes data into a nested tree of clusters without requiring a fixed cluster count up front. It operates either bottom-up (agglomerative, merging closest pairs from individual points) or top-down (divisive, recursively splitting one global cluster), visualizing merges in a dendrogram. While flexible in cluster shape via linkage choice, standard agglomerative clustering requires O(n^2) memory and O(n^2 log n) to O(n^3) time, limiting scale to large datasets.
Study Card: Hierarchical Clustering
Direct Answer
Hierarchical clustering is an unsupervised learning technique that constructs a multi-level hierarchy of clusters. In agglomerative (bottom-up) clustering, every data point starts in its own singleton cluster and the closest pair of clusters is iteratively merged according to a linkage criterion until all points belong to a single root cluster. In divisive (top-down) clustering, all points begin in one cluster and are recursively split.
The merge history is visualized as a dendrogram, allowing practitioners to choose any desired number of clusters afterward by cutting the tree at a chosen height. Standard agglomerative algorithms have space complexity (storing pairwise distances) and naive time complexity ( with priority queues or for specialized algorithms such as SLINK/CLINK), making them best suited for small-to-medium datasets in domains like bioinformatics, document taxonomy, and customer segmentation.
Key Terms
- Agglomerative Clustering: Bottom-up merging from singleton clusters to cluster.
- Divisive Clustering: Top-down recursive splitting from cluster down to singletons.
- Dendrogram: Tree diagram encoding merge order and inter-cluster distance at each step.
- Linkage Criteria: Rules defining cluster-to-cluster dissimilarity—single (minimum pairwise distance), complete (maximum), average (UPGMA), and Ward (minimum increase in total within-cluster sum of squares, requiring Euclidean distance).
- Distance Metric: Measure between individual observations (e.g., Euclidean, Manhattan, cosine).
Example
Consider organizing news articles into a topic tree. Agglomerative clustering first merges closely related articles about a single playoff game, then merges those into "Basketball", groups "Basketball" and "Baseball" under "Sports", and only at a much higher dendrogram distance merges "Sports" with "Finance". Cutting the dendrogram near the top produces broad categories, while cutting lower yields granular subtopics.
Code Implementation
import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage
from sklearn.cluster import AgglomerativeClustering
from sklearn.datasets import make_blobs
from sklearn.preprocessing import StandardScaler
# Generate synthetic 2D blobs and standardize features
X, _ = make_blobs(n_samples=150, centers=3, cluster_std=0.8, random_state=0)
X_scaled = StandardScaler().fit_transform(X)
# Build linkage matrix using Ward linkage (minimizes within-cluster variance)
Z = linkage(X_scaled, method="ward")
# Height halfway between the 2-cluster and 3-cluster merges gives 3 clusters
cut_height = 0.5 * (Z[-2, 2] + Z[-3, 2])
plt.figure(figsize=(10, 5))
dendrogram(Z, truncate_mode="lastp", p=30)
plt.axhline(y=cut_height, color="r", linestyle="--", label=f"Cut for 3 clusters (y={cut_height:.2f})")
plt.title("Hierarchical Clustering Dendrogram (Ward Linkage)")
plt.xlabel("Cluster size / sample index")
plt.ylabel("Ward distance")
plt.legend()
plt.show()
# Fit AgglomerativeClustering (modern sklearn uses `metric`, not deprecated `affinity`)
hc = AgglomerativeClustering(n_clusters=3, metric="euclidean", linkage="ward")
labels = hc.fit_predict(X_scaled)
plt.figure(figsize=(7, 5))
plt.scatter(X_scaled[:, 0], X_scaled[:, 1], c=labels, s=40, cmap="viridis")
plt.title("Agglomerative Clustering (3 Clusters)")
plt.xlabel("Standardized Feature 1")
plt.ylabel("Standardized Feature 2")
plt.grid(True)
plt.show()
Related Concepts
- K-means Clustering: Partitioning method with complexity that scales far better to large datasets than hierarchical clustering, but requires specifying ahead of time and favors spherical clusters.
- DBSCAN / HDBSCAN: Density-based clustering methods capable of finding arbitrary-shape clusters and rejecting noise/outliers; HDBSCAN blends density-based clustering with hierarchical dendrogram extraction.
- Linkage Tradeoffs: Single linkage detects elongated shapes but suffers from chaining; complete and Ward linkages form compact clusters; average linkage compromises between them.
- Cophenetic Correlation: Measures how faithfully dendrogram merge heights preserve original pairwise distances.