Agglomerative clustering: how the hierarchy forms
Agglomerative clustering is a bottom-up method for arranging observations into nested groups. Every customer, article, sensor reading or image begins as a separate cluster. The algorithm repeatedly joins the two most similar clusters and records each decision, producing a hierarchy rather than one fixed partition. This form of hierarchical clustering is useful when the number of groups is uncertain and when several levels of structure deserve inspection.
The result is a dendrogram, a tree whose leaves are observations and whose internal nodes are clusters. A cut through the tree can create a chosen number of groups, while the path from a leaf to the root shows the other clusters it joined along the way. Agglomerative methods do not need a centroid, so they can cluster shapes that centre-based methods struggle to represent.
The bottom-up idea
Each merge follows a precise cycle. The algorithm begins with (n) singleton clusters, calculates how similar every pair is, chooses the closest pair, and replaces them with a larger cluster. It then recalculates relevant similarities before making another merge. This continues until every observation belongs to one cluster. The merge history forms a cluster tree and preserves information that a flat grouping would discard.
Linkage defines how the distance between two existing clusters is calculated. With single linkage, only the smallest cross-cluster distance matters; complete linkage uses the largest. Average linkage combines all cross-cluster distances, while Ward linkage chooses merges that add least to the total within-cluster sum of squares. The same observations can therefore produce different trees under different linkage rules.
Preparing observations for comparison
Before clustering begins, each observation needs a feature vector. A customer might be represented by order frequency, average basket value and preferred time of day; a text document by word counts or embeddings. The columns must share a meaningful scale. Standardisation prevents a variable measured in hundreds of dollars from dominating one measured in tens, while normalisation can make direction more important than magnitude.
Missing values, outliers and irrelevant columns can distort the pairwise distances. Impute or remove incomplete cases with care, inspect extreme observations, and retain features that have a defensible relationship to the intended grouping. One-hot encoding may fit categorical variables, but sparse high-dimensional data needs distance metrics such as cosine similarity rather than an unsuitable Euclidean measure.
Australian geography adds another design choice. Sydney and Perth are separated by thousands of kilometres, while Melbourne and Adelaide have a much shorter intercity corridor. Geographic coordinates may therefore justify a haversine distance or a separately scaled feature. Combining longitude and latitude as ordinary columns can misplace points because a degree of longitude changes value with latitude.
Distance metrics and linkage choices
Distance metrics define what “similar” means. Euclidean distance follows a straight line and suits continuous, standardised measurements. Manhattan distance sums absolute coordinate changes and can be less sensitive to large coordinate differences. Cosine similarity compares vector direction and is common for text or product vectors. The choice should match the data rather than follow habit, because every later merge depends on it.
The main linkage strategies trade chaining, compactness and computational cost differently:
| Linkage | Distance between clusters | Typical effect | Main caution |
|---|---|---|---|
| Single | Minimum cross-cluster distance | Preserves fine structure and can reveal chains | One bridge can link unrelated observations |
| Complete | Maximum cross-cluster distance | Produces compact groups with similar diameters | Outliers can delay useful merges |
| Average | Mean of all cross-cluster distances | Balances compactness and connectivity | Still averages distances across every pair |
| Ward | Increase in within-cluster sum of squares | Favours compact, roughly spherical groups | Requires Euclidean geometry and careful scaling |
Ward linkage has specific assumptions: it uses Euclidean distances and tends to favour compact, roughly spherical clusters. Single linkage can reveal chains of nearby points but may connect outliers into one long group. Complete linkage resists chaining, while average linkage is often a practical compromise. The merge tree should not be confused with a storage tree; the guide to implementing a B-tree covers a different balancing problem.
A worked grocery example
Australia’s supermarket market is strongly shaped by Woolworths and Coles, alongside Aldi and independent stores. Imagine a small, synthetic set of weekly grocery baskets from Melbourne and Sydney. Each basket has three standardised features: packaged groceries, fresh produce and household bulk items. The data is synthetic, but the workflow reflects routine supermarket shopping patterns without exposing a real customer’s history.
Let A be [5, 0, 0], B [5.2, 0.2, 0.1], C [1, 5, 4], D [1.2, 4.8, 4.1] and E [10, 0, 0]. Under Euclidean distance with average linkage, A and B merge first, and C and D merge next. E then joins the A–B cluster because it is closer to those baskets than the C–D group is. The final merge combines the two remaining clusters at a larger height.
A cut at the height where E joins A–B gives three groups: {A, B}, {C, D} and {E}. A cut above the final merge gives two, while a cut below the earlier basket merges leaves more granular groups. Heights are meaningful under the selected metric and linkage, but their numbers do not transfer automatically between methods.
Choosing and validating the cut
Choosing where to cut the dendrogram is partly technical and partly contextual. Silhouette scores can compare candidate partitions, and resampling can test whether groups persist, but neither replaces domain judgement. If the goal is to distinguish household basket types, a cut that separates meaningful shopping patterns is more defensible than the numerically highest score. Report the linkage, metric, preprocessing and cut together so the result can be reproduced.
In an Australian transport dataset, clustering might instead group Sydney train commuters and Melbourne tram users by travel time, frequency and peak-hour behaviour. Those patterns reflect everyday public-transport use, yet they should not be interpreted as personal characteristics without adequate evidence. Cluster labels describe similarity in the selected features; they do not automatically reveal cause, need or identity.
Customer-level clustering can involve personal information. Under the federal Privacy Act 1988 and the Australian Privacy Principles, organisations must consider how collected data is used, kept and disclosed, subject to the Act’s scope and relevant state or territory rules. De-identified examples are safer for teaching, but apparent removal of names does not guarantee privacy. The site’s problem-solving guidance can help turn each modelling assumption into a small, testable case.
Implementing the hierarchy in Python
Python’s scientific ecosystem supports both labels and the full merge tree. SciPy’s hierarchy routines retain child nodes and merge heights, while scikit-learn provides a convenient flat-label interface. For a numeric matrix X, standardise the data first, choose a linkage that suits the metric, and keep the fitted scaler so new observations receive the same treatment.
from scipy.cluster.hierarchy import linkage, fcluster
from sklearn.preprocessing import StandardScaler
X_scaled = StandardScaler().fit_transform(X)
Z = linkage(X_scaled, method="average", metric="euclidean")
labels = fcluster(Z, t=3, criterion="maxclust")
Here, Z is the linkage matrix: each row records two child clusters and the distance at which they joined. fcluster then requests a three-group cut from the tree. The count is only a convenience; inspect Z or draw a dendrogram to understand which observations changed together. For Ward clustering, pass method="ward" and use Euclidean distance, because Ward’s objective depends on squared Euclidean geometry.
For (n) observations, a full distance matrix requires (O(n^2)) memory. A straightforward implementation that repeatedly scans cluster pairs can take (O(n^3)) time, although optimised nearest-neighbour methods reduce the practical cost. Large datasets may need sampling, dimensionality reduction or a different algorithm with a fixed cluster count. Broader explanations of trees, sorting and algorithm analysis are available in the hello ML library. A reproducible hierarchy depends on explicit preprocessing, a deliberate linkage rule and a validated cut.