Skip to main content
LearnMLAcademy
Intermediate10 min read

Hierarchical Clustering

Build agglomerative hierarchical tree dendrograms and compute linkages, with Python code, architecture diagrams, worked examples, and interview quiz.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

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.

1

Start Alone

A B C D

2

Merge Closest

(A B) C D

3

Merge Again

(A B) (C D)

4

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.

t=0

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.

ABCD
t=1

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.

ABCD
t=2

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.

ABCD
t=3

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.

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.

t=0

Step 1: Initialization

The process starts top-down. All data points are initially assumed to belong to one giant, single cluster ABCD.

ABCD
t=1

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.

ABCD
t=2

Step 3: Second Split

Cluster ABC is further divided. Point C is isolated, leaving points A and B together in cluster AB.

ABCD
t=3

Step 4: Final Split

Cluster AB splits into A and B. The algorithm terminates because every point is now in its own separate cluster.

ABCD

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.

Problem: May create chain-like clusters, called the "Chaining Effect". Even distant groups may merge through chains.

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

FeatureDifference
Age5 years
Salary20,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

Step 1

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.

Height (Distance)0.0ABCD
Step 2

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.

Height (Distance)2.00.0ABCD
Step 3

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.

Height (Distance)2.52.00.0ABCD
Step 4

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.

Height (Distance)4.02.52.00.0ABCD

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

Figure 1: Dendrogram using Ward Linkage
30150Data Points Index
Output Interpretation:
  • Lower branches: Highly similar points (e.g., green/purple/orange merges)
  • Higher branches: Less similar clusters (e.g., top blue merges)
Figure 2: Hierarchical Clustering Output

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

FeatureHierarchicalK-Means
Need K InitiallyNot to build a full dendrogram; a final cut still needs a choiceYes
VisualizationDendrogramNone inherent
Speed / ScalabilitySlower / LowerFaster / Higher
GeometryDepends strongly on linkage and metricFavors 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."

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Hierarchical Clustering"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Summary / Key Takeaways

  • Hierarchical clustering builds nested groups shown by a dendrogram.
  • Agglomerative methods repeatedly merge the closest clusters.
  • Linkage rules produce different cluster shapes.
  • A dendrogram cut determines the final cluster count.
  • Scaling and distance choices change the merge sequence.
  • Large datasets and outliers can make results costly or unstable.

Knowledge Check

Progress: 0/4

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 4
What is the key advantage of hierarchical clustering over K-Means?
Question 2 of 4
What does Ward linkage minimise when merging clusters?
Question 3 of 4
Hierarchical clustering has O(N^2) space and O(N^3) time. What does this mean practically?
Question 4 of 4
What does a tall merging step in a dendrogram indicate?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What is the key advantage of hierarchical clustering over K-Means?▼

Correct Answer: You do not need to specify k in advance — the dendrogram shows the full hierarchy and you choose the cut level after seeing the structure

The dendrogram reveals hierarchical structure. You might find k=3 and k=7 both make sense depending on the business question. Cutting at different heights gives different cluster counts from a single run.

2What does Ward linkage minimise when merging clusters?▼

Correct Answer: Increase in total within-cluster variance from the merge — Ward tends to create compact, similarly-sized clusters

Ward linkage is analogous to K-Means' objective — minimise within-cluster sum of squares. It tends to produce compact, interpretable clusters.

3Hierarchical clustering has O(N^2) space and O(N^3) time. What does this mean practically?▼

Correct Answer: For N=100,000 examples, the distance matrix requires billions of entries — hierarchical clustering is impractical for large datasets without approximations

In practice, hierarchical clustering works well for N < ~10,000. For larger datasets, use K-Means with multiple restarts, DBSCAN, or approximate hierarchical methods.

4What does a tall merging step in a dendrogram indicate?▼

Correct Answer: A large jump in distance between merged clusters — indicates a natural cluster boundary. Cut just before these tall steps to find the natural number of clusters

Height in a dendrogram represents dissimilarity at merge. A large jump means you are merging very different clusters. Cutting just below this jump gives the most natural partition.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next