Hierarchical clustering is an unsupervised learning algorithm that constructs a tree-based hierarchy of clusters—visualized as a dendrogram—by iteratively merging or dividing data points based on a chosen linkage criterion and distance metric. Unlike partitional methods such as k-means, it does not require the user to pre-specify the number of clusters, making it valuable for exploratory analysis where the underlying group structure is unknown. The algorithm produces a complete nested sequence of partitions, from each point as its own cluster to a single all-encompassing cluster.
Glossary
Hierarchical Clustering

What is Hierarchical Clustering?
An unsupervised machine learning algorithm that builds a nested hierarchy of clusters by recursively merging or splitting data points based on their pairwise distances, without requiring a pre-specified number of groups.
The two primary strategies are agglomerative (bottom-up), where each observation starts as its own cluster and pairs are successively merged, and divisive (top-down), where all observations begin in one cluster that is recursively split. The choice of linkage method—such as Ward's method, complete linkage, or average linkage—critically determines cluster shape and compactness. In patient stratification, hierarchical clustering is applied to molecular or clinical feature matrices to reveal nested disease subtypes and identify clinically meaningful subgroups without imposing a rigid cluster count.
Key Features of Hierarchical Clustering
Hierarchical clustering builds a multi-level hierarchy of patient subgroups without requiring a pre-specified number of clusters. The output, visualized as a dendrogram, allows clinicians to explore data at varying granularities—from coarse disease categories to fine-grained molecular subtypes.
Agglomerative (Bottom-Up) Approach
The most common strategy in patient stratification. The algorithm initializes by treating every patient as an individual cluster. It then iteratively merges the two most similar clusters based on a chosen linkage criterion until a single root cluster remains. This process creates a nested hierarchy where early merges represent highly similar patients, and later merges capture broader disease categories. The sequence of merges is irreversible, meaning once patients are joined, they cannot be separated in subsequent steps.
Divisive (Top-Down) Approach
A less common but computationally intensive alternative. The algorithm starts with all patients in a single cluster and recursively splits them into smaller, more homogeneous groups. At each step, a flat clustering algorithm like k-means is applied to bisect the selected cluster. This method is particularly useful when the primary interest lies in identifying the dominant, high-level splits in a heterogeneous disease cohort, such as separating inflammatory from non-inflammatory subtypes before further refinement.
Linkage Criteria
The mathematical rule defining the distance between two clusters, critically influencing dendrogram topology:
- Single Linkage: Minimum distance between any two points in different clusters. Prone to chaining effects.
- Complete Linkage: Maximum distance. Tends to produce compact, equally sized clusters.
- Average Linkage: Mean distance between all pairs. A balanced compromise for most omics data.
- Ward's Method: Minimizes the increase in total within-cluster variance after merging. Often preferred for genomic data as it produces clusters of similar size and minimizes information loss.
Dendrogram Interpretation
A dendrogram is a tree diagram encoding the entire clustering history. The vertical axis represents the distance or dissimilarity at which merges occur. Clinicians can 'cut' the tree at a specific height to obtain a desired number of patient subgroups. Long, vertical branches indicate well-separated, stable clusters, while short branches suggest less distinct groupings. Cophenetic correlation coefficient quantifies how faithfully the dendrogram preserves the original pairwise distances, serving as a quality metric.
Distance Metrics for Patient Data
The choice of dissimilarity measure is fundamental to biological interpretation:
- Euclidean Distance: Standard for continuous clinical variables like lab values.
- Manhattan Distance: Robust to outliers, useful for high-dimensional omics data.
- Cosine Similarity: Focuses on the angular relationship between patient profiles, ignoring magnitude differences—ideal for RNA-seq count data where sequencing depth varies.
- Jaccard Distance: Used for binary presence/absence data, such as mutation profiles or symptom checklists.
Computational Complexity & Scalability
Standard agglomerative clustering has a time complexity of O(n³) and memory complexity of O(n²), where n is the number of patients. This makes it prohibitive for large biobank-scale cohorts without optimization. Strategies to scale include:
- Pre-clustering with k-means to reduce n before hierarchical analysis.
- Using approximate nearest neighbor graphs.
- Implementing the Lance-Williams algorithm for efficient linkage updates without recalculating the full distance matrix at each step.
Agglomerative vs. Divisive Hierarchical Clustering
Comparison of the two fundamental approaches to building a hierarchy of patient clusters in biomarker-driven stratification workflows.
| Feature | Agglomerative (Bottom-Up) | Divisive (Top-Down) |
|---|---|---|
Starting State | Each patient is its own singleton cluster | All patients belong to one universal cluster |
Core Mechanism | Iteratively merge the two most similar clusters | Iteratively split the most heterogeneous cluster |
Computational Complexity | O(n³) for naive; O(n² log n) for optimized linkage | O(2ⁿ) for exhaustive; O(kn²) for heuristic splitting |
Typical Use Case | Identifying fine-grained molecular subtypes | Partitioning broad disease categories into major branches |
Dendrogram Interpretation | Leaves are individual patients; root is final merge | Root is entire cohort; leaves are terminal splits |
Sensitivity to Noise | Moderate; early merges can propagate errors upward | High; early splits heavily influence downstream topology |
Scalability (n > 10,000) | Feasible with LANCE or pre-clustering heuristics | Prohibitively expensive; rarely applied to large cohorts |
Prevalence in Bioinformatics | Dominant; implemented in scipy.cluster.hierarchy | Rare; limited to specialized packages like DIANA |
Frequently Asked Questions
Clear, technically precise answers to common questions about using hierarchical clustering for identifying clinically meaningful patient subgroups.
Hierarchical clustering is an unsupervised machine learning algorithm that builds a nested hierarchy of patient groups by iteratively merging or dividing clusters based on their molecular or clinical similarity, without requiring a pre-specified number of subgroups. The algorithm operates through either an agglomerative (bottom-up) approach, where each patient starts as their own cluster and pairs are successively merged, or a divisive (top-down) approach, where all patients begin in one cluster that is recursively split. The merging or splitting decisions are governed by a linkage criterion—such as Ward's method, complete linkage, or average linkage—and a distance metric like Euclidean or correlation-based distance. The result is a dendrogram, a tree-like diagram that visualizes the entire clustering hierarchy, allowing clinical data scientists to cut the tree at different heights to explore patient subgroups at varying levels of granularity. This flexibility makes hierarchical clustering particularly valuable for discovering nested disease subtypes, such as identifying broad cancer categories that contain finer-grained molecular subtypes within them.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
Hierarchical clustering is one member of a broader family of unsupervised learning algorithms used to discover patient subgroups. These related terms cover alternative methodologies, validation techniques, and advanced extensions critical for robust biomarker-driven stratification.
Dendrogram Interpretation
The dendrogram is the primary visual output of hierarchical clustering, representing the nested grouping of patients and the order in which clusters are merged. The vertical axis represents the dissimilarity or distance at which merges occur. Key concepts include:
- Cutting the tree: A horizontal slice across the dendrogram defines the final cluster assignments. The height of the cut determines the number of clusters.
- Cophenetic correlation: A metric quantifying how faithfully the dendrogram preserves the original pairwise distances between patients.
- Branch lengths: In evolutionary biology, these represent genetic change; in patient stratification, they reflect the magnitude of molecular difference between subgroups.
Agglomerative vs. Divisive Clustering
Two opposing strategies exist for building the hierarchy:
- Agglomerative (bottom-up): The most common approach. Each patient starts as its own cluster, and pairs of clusters are iteratively merged based on a linkage criterion until a single root cluster remains.
- Divisive (top-down): A less common, computationally intensive approach. All patients start in one cluster, which is recursively split into smaller groups. DIANA (DIvisive ANAlysis) is a classic algorithm. Agglomerative methods are generally preferred for patient stratification due to their computational efficiency and the intuitive nature of the merging process.
Linkage Criteria Selection
The linkage criterion defines how the distance between two clusters of patients is calculated, dramatically impacting the final dendrogram shape:
- Single linkage: Distance between the two closest members of each cluster. Tends to produce long, chain-like clusters and is sensitive to noise.
- Complete linkage: Distance between the two farthest members. Tends to produce compact, equally sized clusters.
- Average linkage (UPGMA): The mean distance between all pairs of patients in the two clusters. A balanced compromise widely used in genomics.
- Ward's method: Minimizes the total within-cluster variance after merging. Tends to produce clusters of similar size and is the default in many bioinformatics packages.
Distance Metrics for Omics Data
The choice of distance metric is a critical hyperparameter that defines patient similarity. Common choices for molecular data include:
- Euclidean distance: The straight-line distance in feature space. Sensitive to scale; requires careful normalization of gene expression or protein abundance values.
- Manhattan distance: The sum of absolute differences. More robust to outliers in high-dimensional omics datasets.
- Cosine similarity: Measures the angle between patient vectors, ignoring magnitude. Ideal for comparing global gene expression patterns regardless of overall expression level.
- Spearman correlation distance: Based on the rank correlation, capturing non-linear monotonic relationships between patient profiles.
Consensus Hierarchical Clustering
A resampling-based methodology that addresses the instability of a single hierarchical clustering run. The process involves:
- Subsampling the original patient dataset or perturbing the feature space across many iterations.
- Running hierarchical clustering on each subsample.
- Building a consensus matrix where each entry records the proportion of runs in which two patients were assigned to the same cluster. This matrix is then clustered to identify robust, reproducible patient subgroups. This technique is a gold standard in cancer subtyping and is implemented in packages like ConsensusClusterPlus.
HDBSCAN: Hierarchical Density-Based Alternative
Hierarchical Density-Based Spatial Clustering of Applications with Noise (HDBSCAN) extends DBSCAN by constructing a hierarchy of clusters based on density estimates. Unlike traditional hierarchical clustering, HDBSCAN:
- Does not require specifying the number of clusters.
- Robustly identifies clusters of varying density, a common challenge in patient data where rare subtypes exist.
- Explicitly identifies noise points—patients who do not belong to any stable cluster.
- Extracts a flat clustering from the hierarchy based on cluster stability, making it highly practical for identifying both common and rare disease endotypes.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us