A Natural Hierarchy
You are a materials engineer cataloguing the concrete mixes used across a mega-project: airport runways, bridge decks, high-rise columns, and precast tunnel segments. Each mix has a unique recipe — cement content, water-to-cement ratio, aggregate gradation, admixture dosage, 28-day compressive strength. You want to organise these mixes into a tree-like classification: individual mixes group into families, families into categories, and categories into broad classes.
K-Means could give you a flat partitioning, but it would hide the multi-level relationships. Hierarchical clustering builds precisely that tree — a dendrogram — revealing which mixes are closest cousins, which families merge next, and at what dissimilarity level every grouping forms.
Hierarchical clustering is a family of algorithms that produce a nested sequence of partitions rather than a single flat assignment. Instead of committing to a fixed number of clusters upfront, it constructs a full hierarchy from individual observations all the way up to one all-encompassing cluster (or vice versa). This hierarchy is encoded in a tree diagram called a dendrogram, which an engineer can "cut" at any height to obtain the desired number of groups.
In this sub-chapter, we will explore two flavours of hierarchical clustering — agglomerative (bottom-up) and divisive (top-down) — study the critical role of linkage methods in shaping the resulting clusters, learn how to read and cut dendrograms, and ground every concept in civil engineering practice. Two interactive demos let you build dendrograms and compare linkage methods in real time.
This sub-chapter assumes you have completed Sub-chapter 3.1 (unsupervised learning fundamentals) and Sub-chapter 3.2 (K-Means). You should understand what clustering is, how Euclidean distance works, and what within-cluster sum of squares measures. Familiarity with K-Means will help you appreciate why hierarchical clustering addresses some of its limitations.
Two Directions: Bottom-Up and Top-Down
Hierarchical clustering can proceed in two opposite directions. Both produce the same kind of output — a nested tree of clusters — but they build it very differently.
Agglomerative Clustering (Bottom-Up)
Start with every data point as its own individual cluster (N clusters for N points). At each step, find the two closest clusters and merge them into one. Repeat until all points belong to a single cluster. This produces N−1 merges, each recorded as a node in the dendrogram.
Agglomerative clustering is by far the more common approach. It is conceptually simple, computationally tractable (though still O(N²) in memory and O(N³) in time for a naive implementation), and supported by all major ML libraries.
Divisive Clustering (Top-Down)
Start with all data points in one giant cluster. At each step, select a cluster and split it into two (usually by running a flat clustering algorithm like K-Means with K=2 on that cluster). Repeat until every point is its own cluster.
Divisive clustering is less common in practice because the splitting decision at each level is more computationally expensive and the results depend heavily on the splitting criterion. However, it can be useful when you care most about the top-level structure — for example, first splitting bridge inspection data into "pass" vs "requires action" before further subdividing.
Agglomerative = building a classification from specimens up. Imagine you have 200 concrete core samples from different structures. You start by treating each core as its own category. Then you merge the two most similar cores (perhaps both are C30 mixes from adjacent bridge piers). You keep merging similar groups: C30 bridge mixes join other bridge mixes, bridge mixes join infrastructure mixes, until everything is in one "all concrete" category.
Divisive = classifying from broad categories down. Instead, you start with "all 200 cores are concrete." First split: structural vs non-structural. Next split: high-strength vs normal- strength within structural. Keep splitting until each core stands alone.
Both approaches produce the same family tree, just built in opposite order. In practice, the bottom-up approach (agglomerative) is almost always preferred because it avoids the difficult question of how to optimally split a large cluster.
For the remainder of this sub-chapter, we focus on agglomerative hierarchical clustering (AHC) because it is the dominant method in both research and engineering practice. Everything you learn about dendrograms, linkage methods, and cluster evaluation applies equally to divisive approaches.
The Agglomerative Algorithm Step by Step
The agglomerative algorithm is elegant in its simplicity. Here is the complete procedure:
Initialise: Each Point is a Cluster
Begin with N singleton clusters, one per data point. Compute the distance matrix: an N×N symmetric matrix where entry (i, j) records the distance between points i and j. For numerical features, Euclidean distance is the most common choice.
In a civil engineering context, each row might represent a soil sample described by moisture content, liquid limit, and plasticity index. The distance matrix captures how different every pair of samples is.
Find the Closest Pair of Clusters
Scan the distance matrix (or a condensed version of it) to find the two clusters with the smallest inter-cluster distance. How "inter-cluster distance" is defined depends on the linkage method — the subject of our next section.
Merge the Closest Pair
Combine the two closest clusters into a single new cluster. Record this merge event: the two clusters that merged and the distance at which they merged. This information becomes a node in the dendrogram.
Update the Distance Matrix
Recompute distances between the newly formed cluster and all remaining clusters. The specific formula depends on the linkage method. Remove the rows and columns of the two merged clusters and add one row/column for the new cluster.
Repeat Until One Cluster Remains
Go back to Step 2 and repeat. After N−1 iterations, all points have been merged into a single cluster. The complete sequence of merges defines the dendrogram.
The naive agglomerative algorithm runs in O(N³) time and O(N²) space because it must scan the full distance matrix at each of N−1 iterations. Optimised implementations using priority queues bring this down to O(N² log N) for single and complete linkage. For datasets with more than about 10,000 points, consider using approximate methods or switching to algorithms like BIRCH or mini-batch approaches.
Linkage Methods: How to Measure Cluster Distance
The linkage method is the most critical decision in hierarchical clustering. It defines how we measure the distance between two clusters that each contain multiple points. Different linkage methods produce dramatically different dendrograms and cluster shapes from the same data.
Single Linkage (Nearest Neighbour)
The distance between two clusters is the minimum distance between any point in one cluster and any point in the other.
d(A, B) = min { d(a, b) : a ∈ A, b ∈ B }
Pros: Can detect elongated, chain-like clusters. Computationally efficient.
Cons: Prone to the chaining effect — a single noisy point between two natural clusters can cause them to merge prematurely. Tends to produce unbalanced, straggly dendrograms.
CE example: Useful when crack patterns on a concrete surface form elongated chains rather than compact blobs.
Complete Linkage (Farthest Neighbour)
The distance between two clusters is the maximum distance between any point in one cluster and any point in the other.
d(A, B) = max { d(a, b) : a ∈ A, b ∈ B }
Pros: Produces compact, tightly bound clusters of roughly equal diameter. Avoids the chaining problem.
Cons: Sensitive to outliers (a single far-flung point can inflate the inter-cluster distance). Tends to break large clusters apart.
CE example: Good for grouping structural elements (beams, columns) where you want every member of a group to be within a guaranteed maximum dissimilarity.
Average Linkage (UPGMA)
The distance between two clusters is the average of all pairwise distances between points in the two clusters.
d(A, B) = (1 / |A||B|) Σa ∈ A Σb ∈ B d(a, b)
Pros: A balanced compromise between single and complete linkage. Less sensitive to outliers than complete linkage and less prone to chaining than single linkage.
Cons: Can still be influenced by cluster size imbalance. Slightly more expensive to compute.
CE example: A solid default choice for grouping soil samples or traffic patterns where you want a middle ground.
Ward's Linkage (Minimum Variance)
Instead of a simple distance, Ward's method merges the pair of clusters that causes the smallest increase in total within-cluster variance (sum of squares). It is the hierarchical analogue of K-Means' inertia objective.
Δ(A, B) = (|A| · |B|) / (|A| + |B|) · || μA − μB ||²
Pros: Produces compact, spherical clusters similar to K-Means. Often yields the most "natural-looking" dendrograms. Best for well-separated, globular clusters.
Cons: Assumes clusters are spherical and similar in size (same assumption as K-Means). Requires Euclidean distance.
CE example: Ideal for classifying concrete mixes by strength class, where groups tend to be compact and well-separated.
Linkage is like deciding when two construction crews should share a field office. Under single linkage, two crews merge if their nearest workers are close — even if the crews are spread across the site (chaining risk). Under complete linkage, they merge only if their most distant workers are close — a strict criterion. Average linkage considers the typical commute across both crews. Ward's method asks: "Will merging these two crews increase the average commute the least?" — optimising for overall efficiency.
For most civil engineering datasets (material properties, sensor readings, inspection scores), start with Ward's linkage. It produces intuitive, compact clusters and is the default in many libraries. Switch to average linkage if you suspect unequal cluster sizes, and consider single linkage only if you expect elongated, chain-like patterns (rare in CE data).
Understanding Dendrograms
The dendrogram is the signature output of hierarchical clustering. It is a tree diagram that encodes the complete merge history. Reading it correctly is essential for extracting meaningful clusters.
Anatomy of a Dendrogram
A dendrogram has leaves at the bottom (or left), one per data point. Each horizontal line connecting two branches represents a merge event. The height of that connecting line indicates the distance (or dissimilarity) at which the two clusters were merged. The higher the merge, the more dissimilar the clusters were.
- Short vertical lines near the bottom: very similar points merged early.
- Tall vertical lines near the top: very different groups merged late, suggesting distinct clusters below.
- Large jumps in merge height: indicate natural cluster boundaries — the optimal place to "cut."
The key insight is that you do not need to choose the number of clusters before running the algorithm. The dendrogram contains all possible partitions from N clusters (every point alone) to 1 cluster (everything together). You simply draw a horizontal line at the desired height, and every branch that line crosses defines one cluster.
Cutting the Dendrogram
To extract K clusters from a dendrogram, draw a horizontal line that crosses exactly K vertical branches. Equivalently, choose a distance threshold t: every merge below t is kept (those points stay in the same cluster), and every merge above t is ignored (those branches become separate clusters).
The best cut height is typically where you see the largest gap between consecutive merge distances — a jump that says "the clusters below here are natural, but the next merge would combine genuinely different groups."
In civil engineering, this is like deciding at what level of material dissimilarity you want to draw the line between "same class" and "different class." A low cut gives many fine-grained classes; a high cut gives few broad categories.
A dendrogram is like a classification tree for construction materials. At the lowest level, you have individual concrete mixes (C25/30 with fly ash, C30/37 with silica fume, etc.). Moving up, these merge into strength classes (C25, C30, C35). Higher still, strength classes merge into categories (normal-strength, high- strength). At the very top, everything is simply "concrete."
Where you "cut" depends on the engineering question. For a structural design check, you might cut at the strength-class level. For a procurement decision, the broad category level suffices. The dendrogram lets you answer all these questions from a single analysis.
CE Application: Material Classification Hierarchy
One of the most natural applications of hierarchical clustering in civil engineering is building a material classification hierarchy from measured properties. Unlike K-Means, which gives a flat grouping, hierarchical clustering reveals the nested relationships between materials.
Scenario: Soil Classification from Lab Data
A geotechnical investigation for a highway project produces 150 soil samples with measured liquid limit, plastic limit, grain size distribution, moisture content, and specific gravity. Rather than manually applying the Unified Soil Classification System (USCS) to each sample, you run agglomerative clustering with Ward's linkage on the standardised feature matrix.
The resulting dendrogram reveals three main branches at the top level: coarse-grained soils (gravels and sands), fine-grained soils with low plasticity (silts), and fine-grained soils with high plasticity (clays). Within the clay branch, sub-groups naturally separate into lean clays (CL) and fat clays (CH). This hierarchical view mirrors the USCS structure and helps the engineer verify that the lab data is consistent with standard classification.
Scenario: Bridge Condition Grouping
A transport authority maintains 500 bridges, each assessed on deck condition, superstructure rating, substructure rating, load capacity, age, and average daily traffic. Hierarchical clustering groups these bridges into a tree of condition states.
At the coarsest level (K=2), the dendrogram splits bridges into "good condition" and "needs attention." At K=4, it further separates "needs attention" into "minor maintenance," "major rehabilitation," and "replacement candidates." The engineer can choose the granularity that matches their budget planning cycle. This multi-resolution view is impossible with flat clustering alone.
These examples illustrate a key advantage: hierarchical clustering naturally handles multi-scale decision-making. A project director needs broad categories; a field engineer needs fine-grained groups. The same dendrogram serves both.
Hierarchical Clustering vs K-Means
Having studied both K-Means (Sub-chapter 3.2) and hierarchical clustering, let us compare them directly. Understanding when to choose one over the other is a practical skill every data-literate civil engineer should have.
Comparison at a Glance
| Criterion | K-Means | Hierarchical (AHC) |
|---|---|---|
| Must choose K upfront? | Yes | No (cut dendrogram later) |
| Output | Flat partition | Nested hierarchy (dendrogram) |
| Cluster shape assumption | Spherical | Depends on linkage |
| Time complexity | O(NKI) — fast | O(N² log N) to O(N³) |
| Scalability | Handles large N well | Impractical for N > ~10k |
| Deterministic? | No (random init) | Yes (given same linkage) |
| Multi-resolution? | No | Yes (cut at any height) |
Use K-Means when you have a large dataset and a reasonable idea of K. Use hierarchical clustering when your dataset is moderate-sized (up to a few thousand points), you want to explore different numbers of clusters without re-running the algorithm, or you need the interpretive power of a dendrogram for stakeholder communication.
Demo 1: Interactive Dendrogram Builder
Click on the canvas below to place data points, then watch agglomerative clustering build a dendrogram step by step. You can control the animation speed, step through merges one at a time, or let it run automatically. The left panel shows the 2D scatter of points with merge connections; the right panel shows the dendrogram growing upward.
Click to add points
Dendrogram
Place points by clicking the left canvas, or click "Random 15" to generate sample data. Then step through the merging process.
Demo 2: Linkage Method Comparison
This demo runs all four linkage methods on the same dataset simultaneously and shows the resulting dendrograms side by side. Generate a dataset, choose the desired number of clusters (cut height), and observe how single, complete, average, and Ward's linkage produce different groupings from identical data.
Single Linkage
Complete Linkage
Average Linkage
Ward's Linkage
Click "Generate Data" to create clustered points, then "Cluster" to see all four linkage methods side by side.
Practical Considerations
Before applying hierarchical clustering to a real engineering dataset, keep the following practical points in mind.
Feature Scaling
Just like K-Means, hierarchical clustering with Euclidean distance is sensitive to feature scales. If compressive strength ranges from 20 to 80 MPa while water-to-cement ratio ranges from 0.3 to 0.6, the strength feature will dominate distance calculations. Always standardise (zero mean, unit variance) or normalise (min-max to [0, 1]) your features before clustering.
Handling Outliers
Outliers can distort the dendrogram significantly. A single anomalous measurement (e.g., a lab error producing an impossibly high UCS value) may form its own long branch, compressing the rest of the tree. Inspect your data for outliers before clustering. Consider removing or capping extreme values, or use robust distance metrics like Manhattan distance.
Memory and Scalability
The full distance matrix requires O(N²) memory. For N=10,000, this is about 800 MB of floating-point storage. For large datasets, consider: (1) sub-sampling the data, (2) using BIRCH or mini-batch hierarchical methods, or (3) running K-Means first to produce a manageable number of cluster centres and then applying hierarchical clustering to those centres.
Choosing the Number of Clusters
While the dendrogram provides visual guidance, formal methods include:
- Inconsistency coefficient: measures the relative increase in merge distance at each node.
- Gap statistic: compares within-cluster dispersion to a reference null distribution.
- Silhouette analysis: same metric used for K-Means, applicable to any clustering result.
- Domain knowledge: often the most reliable guide. If you know there are 4 soil types on site, cut at K=4.
Advanced Topics
Beyond the basics, several extensions and refinements make hierarchical clustering more powerful in engineering applications.
Non-Euclidean Distance Metrics
Hierarchical clustering works with any distance metric, not just Euclidean. For categorical features (soil type codes, structural element types), use Hamming distance or Gower's distance. For time series data (sensor readings), consider Dynamic Time Warping (DTW). This flexibility is an advantage over K-Means, which is fundamentally tied to Euclidean distance.
Cophenetic Correlation
The cophenetic correlation coefficient measures how faithfully the dendrogram preserves the original pairwise distances. It is the Pearson correlation between the original distance matrix and the cophenetic distance matrix (where the cophenetic distance between two points is the height at which they first merge in the dendrogram). Values close to 1.0 indicate excellent preservation. This metric can help you choose between linkage methods: the one with the highest cophenetic correlation best represents the true data structure.
Hybrid Approaches
A common practical strategy is to combine hierarchical clustering with K-Means: run K-Means to reduce N data points to, say, 50 representative centroids. Then apply hierarchical clustering to the 50 centroids for interpretable dendrogram analysis. This two-stage approach scales to very large datasets while retaining the visual and interpretive benefits of dendrograms.
CE Application: Hierarchical Clustering for Materials
Dendrograms reveal natural groupings in materials and strata — no need to specify k upfront.
Concrete Mix Families
Cluster historical mix designs by w/c ratio, aggregate type, and 28-day strength. The dendrogram shows which mixes are "closest cousins" — useful for mix optimization.
Soil Strata Relationships
Cluster borehole layers by grain-size distribution and Atterberg limits. Cut the dendrogram at different heights to see coarse vs. fine soil groupings emerge.
Knowledge Check
Test your understanding of hierarchical clustering with these four questions. Each reinforces a core concept from this sub-chapter.
Quick Check 1
What is the main advantage of hierarchical clustering over K-Means?
Quick Check 2
In single linkage, the distance between two clusters is defined as:
Quick Check 3
What does the height of a merge in a dendrogram represent?
Quick Check 4
Ward's linkage merges the pair of clusters that:
Key Takeaways
What You Should Remember
- Hierarchical clustering builds a nested tree (dendrogram) of clusters, allowing you to extract any number of groups without re-running the algorithm.
- Agglomerative (bottom-up) clustering starts with each point as its own cluster and merges the closest pair at each step. It is the most common variant.
- The linkage method determines how inter-cluster distance is measured: single (min), complete (max), average (mean pairwise), and Ward (minimum variance increase).
- Ward's linkage is the best default for most CE datasets because it produces compact, well-separated clusters similar to K-Means.
- The dendrogram height encodes merge dissimilarity. Cut where you see the largest gap to obtain natural clusters.
- Hierarchical clustering is deterministic (no random initialisation) but scales poorly beyond about 10,000 points.
- In civil engineering, hierarchical clustering excels at material classification, bridge condition grouping, and any task where multi-level categorisation is valuable.
In the next sub-chapter, we explore DBSCAN — a density-based clustering algorithm that can discover clusters of arbitrary shape and automatically identify outliers (noise points). Unlike both K-Means and hierarchical clustering, DBSCAN does not require you to specify the number of clusters at all.