Machine Learning from Scratch – Day 14: Understanding Hierarchical Clustering
Understanding Hierarchical Clustering
Series: Machine Learning From Scratch (18 articles)
- …
- 14Machine Learning from Scratch – Day 14: Understanding Hierarchical Clustering This article
Machine Learning from Scratch – Day 14: Understanding Hierarchical Clustering
Introduction
In our previous article, we explored K-Means Clustering, an unsupervised learning algorithm that groups similar data points into clusters using centroids.
However, K-Means requires us to decide the number of clusters before training the model.
What if we don't know how many clusters exist in our dataset?
What if we want to understand how individual data points are related to one another and how smaller groups can combine into larger groups?
This is where Hierarchical Clustering becomes useful.
It builds a hierarchy of clusters and helps us visualize relationships between data points.
Let's understand how it works.
1. What is Hierarchical Clustering?
Hierarchical Clustering is an unsupervised machine learning algorithm that groups similar data points into a hierarchy of clusters.
Unlike K-Means, it does not require us to specify the final number of clusters before building the hierarchy.
Instead, it creates a tree-like structure that shows how data points or clusters are connected.
This structure is called a Dendrogram.
For example, imagine a company wants to group its customers based on purchasing behavior.
Hierarchical Clustering can identify:
- Customers with very similar purchasing habits.
- Groups of customers with related preferences.
- Larger customer segments formed by combining smaller groups.
We can then choose the number of clusters by cutting the dendrogram at an appropriate level.
2. Types of Hierarchical Clustering
There are two major approaches to Hierarchical Clustering.
1. Agglomerative Clustering (Bottom-Up)
Agglomerative Clustering starts with every data point as an individual cluster.
It then repeatedly combines the closest clusters.
The process continues until all points belong to one cluster or a stopping condition is reached.
Example:
Imagine we have five data points:
A, B, C, D, E
Initially:
{A}, {B}, {C}, {D}, {E}
Suppose A and B are closest. They are combined:
{A, B}, {C}, {D}, {E}
Next, another pair of nearby clusters is combined.
This continues until a hierarchy is formed.
2. Divisive Clustering (Top-Down)
Divisive Clustering follows the opposite approach.
It starts with all data points in one large cluster.
It repeatedly divides clusters into smaller groups.
For example:
{A, B, C, D, E}
It may first divide into:
{A, B, C} and {D, E}
Then divide those groups further until individual data points are separated or a stopping condition is reached.
Agglomerative clustering is more commonly used in practical implementations because divisive methods can be computationally expensive.
3. How Does Agglomerative Clustering Work?
Let's understand the process step by step.
Step 1: Start with individual clusters
Initially, each data point is treated as a separate cluster.
Step 2: Calculate distances
Calculate the distances between the clusters.
Step 3: Find the closest clusters
Identify the two clusters with the smallest distance according to the selected linkage method.
Step 4: Merge the clusters
Combine the closest clusters into one larger cluster.
Step 5: Repeat
Recalculate distances and continue merging clusters until the desired stopping condition is reached.
The process can be summarized as:
Initialize → Calculate Distances → Find Closest Clusters → Merge → Repeat
4. Understanding Linkage Methods
An important concept in Hierarchical Clustering is Linkage.
Linkage determines how the distance between two clusters is calculated.
Different linkage methods can produce different clustering results.
1. Single Linkage
The distance between two clusters is the minimum distance between any pair of points, one from each cluster.
In simple terms, it considers the closest pair of points.
It can identify elongated clusters but may suffer from a chaining effect, where clusters gradually connect through nearby points.
2. Complete Linkage
The distance between two clusters is the maximum distance between any pair of points across the two clusters.
It tends to produce compact clusters but can be sensitive to outliers.
3. Average Linkage
The distance between two clusters is the average of the pairwise distances between their points.
It provides a middle ground between single and complete linkage.
4. Ward's Linkage
Ward's method merges the clusters that result in the smallest increase in within-cluster variance, commonly measured using the sum of squared deviations from cluster means.
It often produces compact clusters.
Ward's method is generally used with Euclidean distance.
Linkage method | How distance is calculated |
|---|---|
Single | Minimum pairwise distance |
Complete | Maximum pairwise distance |
Average | Average pairwise distance |
Ward | Increase in within-cluster variance |
5. Understanding Dendrograms
A dendrogram is a tree-like diagram used to visualize the merging process in Hierarchical Clustering.
It shows:
- Individual data points.
- Which clusters are merged.
- The order in which clusters are combined.
- The distance at which merging occurs.
The vertical axis commonly represents the distance or linkage value at which clusters are merged.
How do we read a dendrogram?
Imagine a dendrogram containing several branches.
If two data points merge at a low height, they are relatively close according to the chosen distance and linkage method.
If two larger clusters merge at a high height, they are comparatively dissimilar.
We can draw a horizontal line across the dendrogram to determine the clusters.
The number of separate branches intersected by that line indicates the number of clusters.
This makes dendrograms useful for exploring the appropriate number of clusters.
However, the best cut is not always obvious and should also be evaluated using domain knowledge and clustering quality measures.
6. Distance Metrics in Hierarchical Clustering
Hierarchical Clustering uses distance metrics to measure similarity between data points.
Some commonly used metrics include:
1. Euclidean Distance
Measures straight-line distance between two points.
2. Manhattan Distance
Calculates distance by adding the absolute differences between coordinates.
3. Cosine Distance
Measures the difference in direction between two vectors and is useful in some high-dimensional applications, such as text analysis.
The choice of distance metric depends on the nature of the data and the clustering problem.
Feature scaling is also important when numerical features have different units or ranges.
7. Implementing Hierarchical Clustering Using Python
Now let's implement Agglomerative Clustering using Scikit-learn.
We will generate a sample dataset and divide it into three clusters.
Step 1: Import libraries
import matplotlib.pyplot as pltfrom sklearn.datasets import make_blobsfrom sklearn.cluster import AgglomerativeClusteringfrom sklearn.preprocessing import StandardScalerStep 2: Generate a dataset
X, _ = make_blobs( n_samples=300, centers=3, cluster_std=1.0, random_state=42)We generate 300 data points with three underlying groups.
We intentionally ignore the generated labels because we are performing unsupervised learning.
Step 3: Apply feature scaling
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)Scaling ensures that features with larger numerical ranges do not dominate the distance calculations.
Step 4: Create and train the model
model = AgglomerativeClustering( n_clusters=3, linkage="ward")
labels = model.fit_predict(X_scaled)Here:
-
n_clusters=3specifies the number of final clusters.
-
linkage="ward"selects Ward's linkage method.
-
fit_predict()performs clustering and returns the cluster assignments.
Step 5: Visualize the clusters
plt.scatter( X_scaled[:, 0], X_scaled[:, 1], c=labels, cmap="viridis")
plt.xlabel("Feature 1")plt.ylabel("Feature 2")plt.title("Hierarchical Clustering")plt.show()The scatter plot displays the three clusters identified by the algorithm.
Step 6: Generate a Dendrogram
Scikit-learn's AgglomerativeClustering does not directly provide a dendrogram plot.
We can use SciPy to visualize the hierarchical merging process.
from scipy.cluster.hierarchy import linkage, dendrogram
Z = linkage(X_scaled, method="ward")
plt.figure(figsize=(12, 6))
dendrogram(Z)
plt.title("Hierarchical Clustering Dendrogram")plt.xlabel("Data Points")plt.ylabel("Distance")
plt.show()The dendrogram helps us examine how clusters are progressively merged.
For large datasets, displaying every data point can make the dendrogram difficult to read. Sampling or truncating the dendrogram can improve visualization.
8. K-Means vs Hierarchical Clustering
Both algorithms are used for unsupervised clustering, but they work differently.
Feature | K-Means | Hierarchical Clustering |
|---|---|---|
Approach | Centroid-based | Hierarchy-based |
Number of clusters | Specified before fitting | Can be explored using a dendrogram |
Main process | Assign and update centroids | Repeatedly merge or divide clusters |
Output | Cluster assignments and centroids | Hierarchical cluster structure |
Scalability | Generally efficient for large datasets | Often more expensive for large datasets |
Visualization | Scatter plots | Dendrograms |
Neither algorithm is universally better. The choice depends on dataset size, cluster structure, computational resources, and the goal of the analysis.
9. Advantages and Disadvantages of Hierarchical Clustering
Advantages | Disadvantages |
|---|---|
Does not require selecting the final cluster count before building the hierarchy | Can be computationally expensive |
Dendrograms provide an interpretable hierarchy | Sensitive to distance and linkage choices |
Can reveal relationships between groups | Early merging decisions are generally not reversible |
Supports different distance metrics and linkage methods | Can be sensitive to outliers |
Useful for exploratory data analysis | Dendrograms become difficult to interpret for large datasets |
10. Real-World Applications of Hierarchical Clustering
Hierarchical Clustering is used in several fields.
1. Customer Segmentation
Groups customers based on purchasing behavior, preferences, and spending patterns.
2. Biology and Genetics
Helps identify groups of genes or biological samples with similar characteristics.
3. Document Clustering
Groups similar documents, articles, and research papers.
4. Image Segmentation
Can group similar pixels or image features into regions.
5. Social Network Analysis
Helps explore groups of users or communities based on similarity and relationships.
11. Key Takeaways
Let's summarize what we learned today:
- Hierarchical Clustering is an unsupervised learning algorithm.
- It creates a hierarchy of clusters.
- Agglomerative Clustering follows a bottom-up approach.
- Divisive Clustering follows a top-down approach.
- Linkage determines how distances between clusters are calculated.
- A dendrogram visualizes the merging process.
- We can select a cluster count by cutting the dendrogram.
- K-Means and Hierarchical Clustering solve clustering problems using different approaches.
Hierarchical Clustering helps us understand not just which data points belong together, but also how different groups are related to one another.
Coming Next – Day 15: Understanding Principal Component Analysis (PCA)
In our next article, we will explore Principal Component Analysis (PCA), a dimensionality reduction technique.
We will understand how PCA reduces the number of features while retaining as much important information as possible, why dimensionality reduction matters, and how to implement PCA using Python.
Series: Machine Learning From Scratch (18 articles)
- …
- 14Machine Learning from Scratch – Day 14: Understanding Hierarchical Clustering This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article