Skip to content
AI360XpertBeta

Hierarchical Clustering

Start with every point alone, then merge the two closest groups over and over and record each merge height. Cutting the resulting tree at one height gives you any number of clusters from a single run.

Four points at 0, 1, 5 and 6 merge at heights 1.0, 1.0 and 4.0, and a cut through the empty band between 1.0 and 4.0 leaves two clusters
Four points at 0, 1, 5 and 6 merge at heights 1.0, 1.0 and 4.0, and a cut through the empty band between 1.0 and 4.0 leaves two clusters

Why Does This Exist?

A seed bank holds 48 wheat varieties measured on grain length, protein, and disease scores. The curator does not want six groups. The question is which varieties are close relatives, which stand alone, and where two families stop being one family.

That is structure at every scale. K-means hands you one flat partition at the kk you picked before looking. Hierarchical clustering hands you every kk from 48 down to 1 in one tree, so you choose the count after seeing the gaps.

Two ideas make the rest click. A distance is one number saying how unlike two varieties are. A dendrogram is the recorded history: varieties along the bottom, one horizontal bar wherever two groups joined, and the bar height recording how far apart they were. This page covers the merging fix. How to score the result once you cut lives in clustering evaluation. The density alternative that labels stragglers as noise lives in DBSCAN.

Think of It Like This

Merging villages by nearest roads

Forty-eight villages each start alone. Every year the two nearest villages build a shared hall and become one parish, then the two nearest parishes merge, until one parish holds every village. The scribe records the road distance at each merger: early ones are neighbours a mile apart, late ones are counties joining.

Once a parish holds six villages, how far is it from another parish. Measure from the nearest pair of houses, the farthest pair, or the average across all pairs. Identical map, genuinely different histories, and no measurement that is simply correct.

Measure from the nearest houses and a parish creeps along a valley one village at a time until one parish stretches miles without a single long jump. Measure from the farthest and parishes stay compact and round, splitting a long valley in half.

Where it stops: villages choose to merge and parishes vote. Points never choose. You pick the rule, called linkage, and the rule decides the shapes you are allowed to find.

How It Actually Works

Agglomerative clustering is the version people run. Start with nn clusters of one point each. Find the two closest clusters, merge them, and write down the distance hh they merged at. Repeat until one cluster is left. That gives n−1n - 1 merges and n−1n - 1 heights, and those heights are the whole output.

Because every step was kept, you choose kk afterwards. Draw a horizontal line across the tree at height hh. The vertical lines it crosses count your clusters, and the groups below them are your answer. Lower for more, higher for fewer, from one fitted model.

Worked example: four points on a line

Put four points at 00, 11, 55, and 66. Call them AA, BB, CC, DD. Pairwise gaps are AB=1.0AB = 1.0, CD=1.0CD = 1.0, BC=4.0BC = 4.0, AC=5.0AC = 5.0, BD=5.0BD = 5.0, and AD=6.0AD = 6.0.

First merge: the closest pair is 1.01.0. Both ABAB and CDCD sit at 1.01.0, so AA joins BB at height 1.01.0 and CC joins DD at height 1.01.0. Two clusters remain: {A,B}\{A, B\} and {C,D}\{C, D\}.

Second merge under single linkage, which uses the closest cross-pair:

h=min⁡(5.0,6.0,4.0,5.0)=4.0h = \min(5.0, 6.0, 4.0, 5.0) = 4.0

The two pairs join at height 4.04.0. A cut at any height between 1.01.0 and 4.04.0 crosses exactly two vertical lines, so it returns two clusters: {A,B}\{A, B\} and {C,D}\{C, D\}. The empty band from 1.01.0 to 4.04.0 is 3.03.0 tall with no merges, and that emptiness is the evidence the cut is real.

Linkage decides what closest means for groups

Closest is unambiguous for two single points and ambiguous the moment a cluster holds more than one. The rule you pick is the linkage criterion.

Single linkage uses the closest cross-pair and follows thin filaments. It chains distinct groups together through any bridge of intermediate points. Complete linkage uses the farthest cross-pair. On our four points that is max⁡(5.0,6.0,4.0,5.0)=6.0\max(5.0, 6.0, 4.0, 5.0) = 6.0, so the final merge sits at 6.06.0 instead of 4.04.0. It favours compact round clusters and splits a long real group in half. Average linkage uses the mean over all cross-pairs, here (5.0+6.0+4.0+5.0)/4=5.0(5.0 + 6.0 + 4.0 + 5.0) / 4 = 5.0, and sits between the two. Ward method uses no pair distance at all and merges whichever two clusters raise total within-cluster variance least, which makes it the closest relative of k-means on this page.

Reading the tree without fooling yourself

Merge height carries all the information. A long stretch of empty vertical space below a bar means those groups had nothing between them, so cut there. Horizontal position carries none. Every bar can flip left to right without changing a merge or a height, so two leaves drawn side by side may have joined only at the root.

The bill is quadratic. Every pair needs a distance, so nn rows need about n2/2n^2 / 2 values. Forty-eight varieties are nothing. A million rows do not fit.

Code

The point is the heights: same four points, three rules, three different final merges.

def gap(a: float, b: float) -> float:    return abs(a - b)
pts: dict[str, float] = {"A": 0.0, "B": 1.0, "C": 5.0, "D": 6.0}pairs: dict[str, float] = {    "AB": gap(pts["A"], pts["B"]),    "CD": gap(pts["C"], pts["D"]),    "BC": gap(pts["B"], pts["C"]),    "AC": gap(pts["A"], pts["C"]),    "BD": gap(pts["B"], pts["D"]),    "AD": gap(pts["A"], pts["D"]),}cross: list[float] = [pairs["AC"], pairs["AD"], pairs["BC"], pairs["BD"]]print(pairs["AB"], pairs["CD"])  # -> 1.0 1.0print(min(cross))  # -> 4.0print(sum(cross) / len(cross))  # -> 5.0print(max(cross))  # -> 6.0

The printout matches the hand computation: both tight pairs merge at 1.01.0, then single linkage joins the pairs at 4.04.0, average at 5.05.0, and complete at 6.06.0. Change CC from 5.05.0 to 2.52.5 and watch the gap between 1.01.0 and the final merge shrink from 3.03.0 to 1.51.5.

Watch Out For

Single linkage plus a bridge of points between groups

The result comes back as one cluster holding almost everything plus a few singletons. That shape is the signature of chaining: single linkage walked from one real group to the other across stragglers, each hop shorter than the merge that would have kept the groups apart.

Symptom: a long run of merges at similar small heights, one point at a time, with no jump anywhere in the height list. Fix: switch to average linkage or Ward method, or remove the bridge first. DBSCAN is built to label low-density bridge points as noise instead of assigning them.

Reading side-by-side leaves as similar

Two varieties sit next to each other at the bottom of the tree and get called close relatives. Follow both leaves upward and their branches join only near the root. They landed adjacent because the plot had to put the leaves in some order.

Symptom: a claim about two points justified by the picture alone. Fix: read the height where their branches actually meet, and take any similarity number for two specific varieties from the distance matrix, not off the drawing.

The Quick Version

  • Every point starts alone. Merge the two closest groups, record the height, and repeat until one group is left.
  • The output is a tree, not a partition. A horizontal cut at height hh chooses the cluster count after fitting.
  • Linkage decides the answer on our four points: single linkage finishes at 4.0, average at 5.0, and complete at 6.0.
  • Merge height carries all the information. A 3.0 tall empty band between 1.0 and 4.0 is the evidence for cutting there.
  • Leaf order carries none. Any bar can flip without changing the history.
  • The distance matrix grows with the square of the row count, so this stops being practical past tens of thousands of rows.