edSlash Labs  /  Machine Learning Lab  /  Unsupervised Learning  /  Hierarchical Clustering
Algorithm 02 · Unsupervised learning · Clustering

Hierarchical Clustering

Learn how a computer builds a family tree of groups. It starts with separate data points and joins the closest groups step by step, creating a tree-shaped diagram called a dendrogram.

Beginner friendly

The big idea

Build a tree of groups instead of choosing all groups at the start.

Hierarchical Clustering is an unsupervised learning method. It joins similar data points into larger and larger groups. The joining process creates levels, like branches in a family tree.

Small groups → Larger groupsKeep joining the closest groups until one big group remains

You can later choose where to cut the tree to decide how many clusters you want.

Quick facts

Hierarchical

Groups are arranged in levels, from small to large.

Dendrogram

A tree diagram that shows when groups join.

Linkage

A rule for measuring the distance between groups.

No labels needed

The algorithm finds groups without given answers.

Remember: Unlike K-Means, Hierarchical Clustering can show a whole set of possible groupings in one tree. You choose the final number of clusters by cutting the tree.

1. How does it work?

We will focus on the bottom-up method, also called agglomerative clustering.

From separate points to one family tree

Start with one cluster per point

If there are 6 data points, begin with 6 tiny clusters.

Find the closest two clusters

Use a distance rule to decide which groups are nearest.

Join those two clusters

They become one bigger cluster.

Repeat the search and join

Keep merging groups until all points are connected.

Cut the dendrogram

Choose a height to get the number of groups you want.

Two main directions

Agglomerative (bottom-up): starts with separate points and joins them into larger groups.

Divisive (top-down): starts with one large group and splits it into smaller groups.

This lesson and the playground use agglomerative clustering because it is the most common version taught first.

2. Live Hierarchical Clustering Playground

Step through the merges and watch the dendrogram grow. Change the linkage rule to see how the tree can change.

Interactive experiment

Cluster map and dendrogram

Coloured points show the current groups. The tree shows the merge history.

Group AGroup BGroup CGroup D

Dendrogram

1 group8 groups
Merges completed0Joining steps
Groups now8Current clusters
Next merge distance—Before next join
Chosen cut3Visible groups
Choose a linkage rule, then select “Next merge” to join the closest groups.
Tip: move the cut slider to explore different cluster counts. The cut does not change the merge history.

3. The mathematics behind Hierarchical Clustering

Distance tells the algorithm which groups should join.

Step 1: Distance between two points

d(A,B) = √((x₂−x₁)² + (y₂−y₁)²)Euclidean distance in two dimensions

This is the straight-line distance between two points.

Step 2: Distance between groups

Linkage = group distance ruleSingle, complete, or average

A group can contain many points, so we need a rule to compare two groups.

Single linkage

D(A,B) = minimum distance
between any point in A and B

Looks for the closest pair. It can create long, chain-shaped clusters.

Complete and average linkage

Complete = maximum pair distance

Average = mean of all pair distances

Complete favours tighter groups. Average uses all pair distances to balance the two.

Important: Linkage is the rule used to measure distance between clusters. Different rules can create different dendrograms from the same data.

4. Worked example: grouping eight learners

Imagine each learner is described by study hours and practice quizzes completed.

Learners with similar study habits may be grouped together. At the start, every learner is their own cluster. The algorithm repeatedly joins the closest groups.

LearnerStudy hoursPractice quizzesPossible interpretation
A1.02Low study, low practice
B1.53Low study, low practice
C2.02Low study, low practice
D5.05Middle range
E5.56Middle range
F8.08High study, high practice
G8.57High study, high practice
H9.09High study, high practice
What should we notice? A dendrogram does not tell us what a group means. We look at the original features and use our knowledge of the problem to describe each cluster.

5. How do we choose the number of clusters?

Read the dendrogram and look for large jumps in merge distance.

Cutting the dendrogram

Imagine drawing a horizontal line across the tree. Every branch the line crosses becomes a separate cluster. A higher cut usually gives fewer, larger clusters.

Look for large distance jumps

If two groups only join at a much larger distance than earlier merges, they may be quite different. A cut just below that jump can be useful.

There is no automatic perfect answer. Use the dendrogram, the purpose of the project, and whether the resulting groups make sense.

6. Python implementation

Scikit-learn can build hierarchical clusters with AgglomerativeClustering.

Example code

Group learners using study hours and practice quizzes.

import numpy as np
from sklearn.cluster import AgglomerativeClustering
from sklearn.preprocessing import StandardScaler
from scipy.cluster.hierarchy import dendrogram, linkage
import matplotlib.pyplot as plt

# Example data: [study hours, practice quizzes]
X = np.array([
    [1.0, 2], [1.5, 3], [2.0, 2],
    [5.0, 5], [5.5, 6],
    [8.0, 8], [8.5, 7], [9.0, 9]
])

# Scale features because distance is important
X_scaled = StandardScaler().fit_transform(X)

# Create three clusters
model = AgglomerativeClustering(
    n_clusters=3,
    linkage="average"
)
labels = model.fit_predict(X_scaled)
print("Cluster for each learner:", labels)

# Draw a dendrogram to inspect the merge structure
tree = linkage(X_scaled, method="average")
dendrogram(tree)
plt.xlabel("Learner")
plt.ylabel("Distance")
plt.title("Hierarchical Clustering Dendrogram")
plt.show()
Why scale the data? Distance-based methods can be dominated by a feature with much larger numbers. Scaling helps features contribute more fairly.

7. Real-life applications

Hierarchical Clustering is useful when we want to explore relationships between groups.

Biology and genetics

Group genes or samples that have similar patterns.

Customer research

Explore groups of customers with similar interests or shopping habits.

Document grouping

Organise articles or reports by similarity after converting text into numbers.

Social network analysis

Explore communities or people with similar connection patterns.

Strengths

  • Shows a hierarchy of groups.
  • You can inspect different cluster counts.
  • Does not need the number of clusters fixed before building the tree.

Limitations

  • Can be slow on very large datasets.
  • Results depend on the distance and linkage choices.
  • Early merges are usually not undone.
  • Scaling and outliers can affect distances.

8. Knowledge check

Answer all 10 questions, then submit to see your score and explanations.

0 of 10 answered

Mini challenge

In the playground, switch between single, complete, and average linkage. Keep the data the same. Do the merge steps change?

Can you explain why a different linkage rule can create a different tree?