Hierarchical Clustering
Hierarchical Clustering is an unsupervised learning method that builds a tree of nested groups from similarities or distances between data points.
Hierarchical Clustering in Simple Words
Imagine every student starts alone. We repeatedly join the most similar students or groups until one large hierarchy is formed. Later, we can cut that hierarchy at a chosen height to obtain clusters.
Start Alone
A B C D
Merge Closest
(A B) C D
Merge Again
(A B) (C D)
Build Tree
((A B) (C D))
Key idea: the hierarchy depends on the distance metric and linkage rule we choose. It is a model of grouping structure, not proof that the groups are objectively “natural.”
Unlike K-Means, which directly produces a flat partition for a chosen number of clusters, hierarchical clustering can build a nested sequence of merges or splits.
A complete tree-like structure of clusters, showing how groups are formed gradually. This tree structure is mathematically called a Dendrogram.
The hierarchy can help us inspect nested grouping structure, compare merge levels, and choose a useful clustering at different resolutions.
Hierarchical clustering is used in areas such as bioinformatics, gene-expression analysis, document grouping, customer analysis, image analysis, and exploratory scientific research. The resulting dendrogram shows similarity under the chosen method; it should not automatically be interpreted as a true evolutionary or causal tree.
Why Use Hierarchical Clustering?
K-Means asks us to choose K before fitting. Hierarchical clustering offers a different view: build a hierarchy first, inspect it, and then choose a useful cut when appropriate.
This is useful when we want to:
- Automatically reveal grouping structure
- Show relationships between clusters
- Allow flexible cluster selection later
- Preserve hierarchy information
It is therefore best viewed as an alternative clustering strategy, not as a method that historically appeared simply because K-Means required K.
Real-Life Analogy of Hierarchical Clustering
Imagine organizing books inside a giant library. Initially, all books are separate. Then gradually, books about similar topics are grouped together. For example: Science books together, History books together, Mathematics books together.
Library Hierarchy Example
- └─ Science
- ├─ Physics
- ├─ Chemistry
- └─ Biology
- ├─ Genetics
- ├─ Zoology
- └─ Botany
Notice something important: Groups form at multiple levels. This creates a hierarchy. Hierarchical Clustering works exactly like this. It forms Small clusters, Medium clusters, and Large clusters, creating a complete hierarchy of relationships.
Types of Hierarchical Clustering
1. Agglomerative Clustering
Bottom-Up Approach
Initially: Every point is its own cluster. Then clusters gradually merge. Small clusters combine into larger clusters.
Step 1: Initialization
The process starts bottom-up. Every data point is treated as its own independent cluster. Here we have four distinct points: A, B, C, and D.
Step 2: First Merge
The algorithm evaluates pairwise distances. Points A and B are the closest to each other, so they merge into a new cluster: AB.
Step 3: Second Merge
Cluster AB is found to be closer to point C than to D. Thus, C is enveloped into the group, forming cluster ABC.
Step 4: Final Merge
The remaining group ABC is finally merged with the remaining point D. The algorithm terminates as all data points form a single root cluster ABCD.
2. Divisive Clustering
Top-Down Approach
Initially: All data points belong to one giant cluster. Then the cluster gradually splits. Large clusters divide into smaller groups.
Step 1: Initialization
The process starts top-down. All data points are initially assumed to belong to one giant, single cluster ABCD.
Step 2: First Split
The algorithm identifies the furthest point in the dataset. D is isolated into its own cluster, separating from the ABC group.
Step 3: Second Split
Cluster ABC is further divided. Point C is isolated, leaving points A and B together in cluster AB.
Step 4: Final Split
Cluster AB splits into A and B. The algorithm terminates because every point is now in its own separate cluster.
Which type will we focus on? Most standard machine-learning libraries, including Scikit-learn's AgglomerativeClustering, focus on the bottom-up agglomerative approach. Divisive methods also exist, but their exact splitting strategy depends on the algorithm used.
Understanding Agglomerative Clustering Deeply
Agglomerative clustering starts with Every point as an independent cluster.
Then repeatedly: Find nearest clusters ➔ Merge them ➔ Recalculate distances ➔ Repeat until all points merge.
What Determines "Closest Clusters"? (Linkage Methods)
This is an important concept in Hierarchical Clustering. The algorithm needs a method to measure distance between clusters. This is called Linkage Criteria.
1. Single Linkage
Measures: Minimum distance between two clusters. D(A,B) = min(d(a,b))
If even one pair of points is close: Clusters merge.
2. Complete Linkage
Measures: Maximum distance between clusters. D(A,B) = max(d(a,b))
The farthest cross-cluster pair determines the linkage distance. This often favors tighter groups than single linkage, but the result still depends on the data.
3. Average Linkage
Measures: Average pairwise distance between clusters.
It uses all cross-cluster pairs rather than only the closest or farthest pair. Whether it is preferable depends on the dataset and metric.
4. Ward Linkage
Ward linkage chooses the merge that produces the smallest increase in within-cluster sum of squares.
It often favors compact groups, but it is not universally the best linkage.
Important: in Scikit-learn, Ward linkage is used with Euclidean distance.
Distance Metrics & Mathematical Calculation
The algorithm needs a way to measure dissimilarity between points. A common choice is Euclidean distance. For A(2,3) and B(6,7):
d = √((6−2)² + (7−3)²)
= √(4² + 4²)
= √32
≈ 5.66
Common Distance Metrics
- ├─ Euclidean Distance (Straight-line distance)
- ├─ Manhattan Distance (Sum of absolute differences)
- ├─ Minkowski Distance (Generalized form of Euclidean and Manhattan)
- └─ Cosine Distance (Based on angle between vectors, highly used for text/documents)
Why Feature Scaling Can Matter
| Feature | Difference |
|---|---|
| Age | 5 years |
| Salary | 20,000 rupees |
With a distance-based method, a large numerical scale can dominate the calculation. Standardizing numerical features is often useful when units differ substantially. Whether scaling is appropriate still depends on what the features mean and on the chosen metric.
Metric and Linkage Must Be Compatible
Scikit-learn supports several metrics for agglomerative clustering, but not every metric works with every linkage.
Example: linkage='ward' requires Euclidean distance. For single, complete, or average, other supported metrics may be used.
Complete Numerical Example (Single Linkage)
Let's solve a simple agglomerative clustering problem. We have 3 points on a 1D line: A(0), B(2), and C(6).
Initial Distances:
- Dist(A, B) = |2 - 0| = 2
- Dist(B, C) = |6 - 2| = 4
- Dist(A, C) = |6 - 0| = 6
Step 1: First Merge
A and B are closest (distance 2), so merge them into Cluster {A, B}.
Step 2: Recalculate Distance (Using Single Linkage)
Compute distance from new {A, B} to remaining C using Single Linkage (shortest distance from any point in {A, B} to C).
Dist({A, B}, C) = min(Dist(A, C), Dist(B, C)) = min(6, 4) = 4.
Step 3: Final Merge
Merge {A, B} and C together at distance 4 to form the final root cluster {A, B, C}.
Dendrogram — The Heart of Hierarchical Clustering
The most important visualization in Hierarchical Clustering is the Dendrogram. A dendrogram is a tree-like diagram showing Cluster merges, Similarity levels, and Hierarchical relationships.
Building and Reading a Dendrogram, Step-by-Step
Base Elements (Height = 0)
Before merging, every individual data point is placed along the structural baseline. The Y-axis of a dendrogram represents Distance (or Height). At distance 0, none of the points are grouped.
First Merge: Highly Similar
The algorithm discovers that A and B are very close. Their distance is computed as 2.0. An upside-down "U" shape links A and B, peaking exactly at 2.0 on the Y-axis. The lower the connection, the more similar the items.
Second Merge: Another Local Group
Next, the algorithm processes points C and D. They are slightly further apart from each other than A and B were, with a distance of 2.5. A green link bridges C and D at 2.5.
Final Merge: Uniting Clusters
Lastly, interpreting the distance between cluster AB and cluster CD, the algorithm finds they are quite dissimilar. They finally merge at a height of 4.0, enclosing all points into a single root.
Choosing Number of Clusters Using Dendrogram
We can build a hierarchy first and choose a horizontal cut later. In the teaching dendrogram above, a cut at height 3.0 gives 2 clusters: (A,B) and (C,D).
But: the cut height is a model-selection choice, not an automatically correct answer. Domain knowledge, validation measures such as silhouette score, and stability checks can help.
Scalability: standard hierarchical clustering can become expensive as the number of samples grows because the hierarchy is built from many pairwise relationships. Memory and runtime are often roughly quadratic-scale concerns, although exact cost depends on the linkage and implementation. For very large datasets, K-Means, MiniBatchKMeans, sampling, or structured connectivity constraints may be more practical.
Implementing Hierarchical Clustering in Python
Dendrogram and Scikit-Learn
# Step 1 — Import Libraries
import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage
from sklearn.datasets import make_blobs
from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics import silhouette_score
# Step 2 — Create a reproducible teaching dataset
X, _ = make_blobs(
n_samples=120,
centers=3,
cluster_std=0.70,
random_state=42
)
# ==========================================
# APPROACH 1: Build and plot the hierarchy
# ==========================================
linked = linkage(X, method='ward')
plt.figure(figsize=(10, 6))
dendrogram(linked)
plt.title("Dendrogram using Ward Linkage")
plt.ylabel("Linkage distance")
plt.show()
# ==========================================
# APPROACH 2: Cut the hierarchy into 3 groups
# ==========================================
model = AgglomerativeClustering(
n_clusters=3,
linkage='ward'
)
labels = model.fit_predict(X)
print("Cluster sizes:", np.bincount(labels))
print("Silhouette score:", round(silhouette_score(X, labels), 3))
plt.scatter(X[:, 0], X[:, 1], c=labels, cmap='viridis')
plt.title("Agglomerative Clustering Output")
plt.show()Understanding the Code: SciPy's linkage builds the hierarchy used by dendrogram. Scikit-learn's AgglomerativeClustering then returns a flat set of cluster labels for the selected number of groups.
Cluster sizes: [40 40 40]
Silhouette score: 0.892
Important: cluster labels such as 0, 1, and 2 are arbitrary identifiers. The silhouette score is useful for comparison, not proof that 3 clusters are the one true grouping.
Expected Output Visualizations
- Lower branches: Highly similar points (e.g., green/purple/orange merges)
- Higher branches: Less similar clusters (e.g., top blue merges)
Real-Life Scenario — Gene Analysis
Suppose scientists analyze gene-expression measurements across samples. Genes with similar expression patterns may be grouped together for further investigation of possible shared biological behavior.
Hierarchical clustering can reveal nested similarity patterns in such measurements. The dendrogram is an exploratory clustering result; biological or evolutionary conclusions require separate domain evidence and analysis.
Advantages
- A full hierarchy can be inspected before choosing a final cut.
- Produces a dendrogram that exposes nested merge structure.
- Supports multiple linkage rules and, depending on linkage, different distance metrics.
- Can be useful when nested grouping structure itself is scientifically or operationally interesting.
Disadvantages
- Can require substantial memory and runtime as sample count grows.
- Standard agglomerative merging is greedy: an earlier merge is not later undone.
- Results can change substantially with outliers, feature scaling, metric, and linkage choice.
- A dendrogram does not automatically reveal one objectively correct cut height.
Hierarchical Clustering vs K-Means
| Feature | Hierarchical | K-Means |
|---|---|---|
| Need K Initially | Not to build a full dendrogram; a final cut still needs a choice | Yes |
| Visualization | Dendrogram | None inherent |
| Speed / Scalability | Slower / Lower | Faster / Higher |
| Geometry | Depends strongly on linkage and metric | Favors compact centroid-based groups |
Applications of Hierarchical Clustering
- APPLICATIONS
- │
- ├── Bioinformatics
- ├── DNA Analysis
- ├── Gene Expression
- ├── Document Clustering
- ├── Customer Segmentation
- ├── Medical Research
- ├── Social Network Analysis
- ├── Image Segmentation
- └── Recommendation Systems
Common Mistakes
Treating the dendrogram as the truth
It visualizes the hierarchy produced by your metric and linkage choices.
Ignoring feature scales
Large numerical units can dominate distance calculations.
Calling one cut “the optimal K” automatically
Cut height should be justified with data, domain knowledge, and validation.
Using Ward with an incompatible metric
Ward linkage in Scikit-learn requires Euclidean distance.
Quick FAQs
Do I have to choose K before hierarchical clustering?
Not if you first build a full hierarchy/dendrogram. To obtain a final flat clustering, however, you still need a rule such as a chosen cluster count or distance threshold.
Does hierarchical clustering need feature scaling?
Often yes when numerical features have very different units and the selected distance metric is scale-sensitive.
What should I learn next?
Compare the method with K-Means, then study DBSCAN. If distance scales are unclear, review Feature Scaling.
Final Summary
Hierarchical Clustering is an interpretable clustering algorithm in Machine Learning. It works by Measuring similarities, Merging or splitting clusters, Building hierarchical structures, and Visualizing relationships using dendrograms.
A full hierarchy can be built without choosing the final number of clusters first, but obtaining a flat clustering still requires a cut rule such as a cluster count or distance threshold. The method is especially useful when the nested grouping structure itself is worth inspecting.
Most Important Insight to Remember:
"Hierarchical clustering does more than return cluster labels: it records a sequence of merges or splits. The dendrogram is valuable because it lets us inspect that structure at multiple resolutions—but its meaning always depends on the data, distance metric, linkage rule, and chosen cut."