Hierarchical Clustering
A collection can have small groups inside larger groups. Joining the closest groups one step at a time lets us inspect that hierarchy without choosing one group count at the outset.
13 sections · 4 questions · 2 coding challenges
The arrow keys move between sections too.
Keeping the Smaller Groups Inside the Larger Ones
BOTIE
Once groups contain several sensors, there is more than one way to decide which groups are closest. Ward's criterion chooses the merge with the smallest increase in within-group squared variation. We will begin with single linkage instead: find the nearest pair with one sensor in each group. That lets us point to the distance responsible for each merge. These criteria can produce different hierarchies.
Do We Need One Answer to How Many Groups There Are?
Botie compares sensors by their response time. Two nearly identical sensors seem to belong together, and another nearby pair seems to form a second group. At a broader scale, all four might belong to one family. A single list of group labels hides that relationship.
Let's begin with every sensor in its own group. We will join the nearest groups, keep a record of each join, and see how that record lets us choose a useful level of detail later.
The response-time groups are illustrative measurements.
Step 1 of 3
Start with separate sensors
The numbers are invented response times in a shared unit. Every observation initially has its own group.
Groups
- Group 1{0}
- Group 2{1}
- Group 3{7}
- Group 4{9}
Step 2 of 3
Keep the close pairs
The nearest pair joins first, then the other nearby pair. We retain the earlier grouping decisions.
First join, distance 1
- Group 1{0, 1}
- Group 2{7}
- Group 3{9}
Second join, distance 2
- Group 1{0, 1}
- Group 2{7, 9}
Step 3 of 3
Choose a level of detail
Under single linkage, the nearest bridge between the two remaining groups spans from 1 to 7. Cutting the merge tree below that height leaves two groups.
| Cut | Groups left |
|---|---|
| Above 2, below 6 | {0, 1} and {7, 9} |
| At least 6 | {0, 1, 7, 9} |
Above 2, below 6
- Groups left
- {0, 1} and {7, 9}
At least 6
- Groups left
- {0, 1, 7, 9}
A linkage rule defines what distance between groups means
The smallest cross-group distance identifies the nearest bridge. Replacing the reducer with the maximum would ask a different question about the same two groups.
How close are the nearest members of these two groups?
Single linkage only needs one short connection between groups. Move a response time in either group and follow the smallest cross-group distance.
BOTIE
Single-linkage distance between the groups
3
Follow the operations
1. First group's response times
- 00
- 11
2. Second group's response times
- 04
- 16
3. Compare two sets of positions
4 6 3 5 4. Flatten a list
- 04
- 16
- 23
- 35
5. Smallest value
3
6. Result
3
This workshop calculates one linkage comparison in one dimension. A complete agglomerative algorithm repeatedly chooses and records merges.
1. A Group Needs a Distance Too
Distance between two observations is familiar. After the first join, we need a distance between groups containing several observations. The choice of that group distance is called linkage.
Agglomerative clustering starts with individual observations and repeatedly joins groups. It makes locally chosen merges; an early merge is not undone just because a later view would favour another partition.
A = [0, 1]
B = [4, 6]
Cross-group distances:
[4, 6]
[3, 5]Every entry compares one member of A with one member of B. This small table gives us several possible summaries.
2. Decide What Counts as Close
Single linkage uses the smallest cross-group distance. Complete linkage uses the largest. Average linkage averages all cross-group distances. Each answers a different question about what makes groups similar.
Single linkage can connect a long chain of neighbouring points. Complete linkage resists that chain because distant endpoints count against a merge. Neither choice discovers an objectively correct grouping without a useful notion of similarity.
For the distance table above:
single linkage = 3
complete linkage = 6
average linkage = (4 + 6 + 3 + 5) / 4 = 4.5Ward linkage is another criterion: the increase in within-group sum of squares. It is not simply one of these three summaries.
3. Record Each Merge
After selecting the closest pair of groups, combine their members and recalculate distances to the remaining groups. Record which groups joined and the distance or criterion value of the join.
A dendrogram draws that record as a tree. Leaves represent original observations; branch heights show when groups joined. The left-to-right order of leaves is not a measurement axis.
Response times: [0, 1, 7, 9]
Single-linkage merge heights: 1, 2, 6
Groups after the second merge: [0, 1] and [7, 9]A horizontal cut between the second and third merge heights retains two groups. A different cut gives a different level of detail.
4. Compare Groupings Without Reading Labels Into Them
A hierarchy records similarities under our chosen measurements, scaling, and linkage. It does not establish that the sensors have different physical causes or that each branch is a real category.
Inspect whether small data changes alter the joins. Revisit features and units. Ties need a consistent policy because several equally close merges may lead to different later structures.
The workshop isolates the group-distance step. Choosing a different reducer changes what it means for two groups to be close.
5. Know When the Tree Becomes Expensive
A complete distance table grows with the square of the number of observations. Large datasets may need different algorithms or constraints on possible neighbours.
A fitted hierarchy also does not automatically define a prediction rule for a new observation. Decide whether to rebuild, attach it by a documented rule, or use a model designed to assign future observations.
Keeping the full hierarchy is useful when the task has meaningful levels of grouping, rather than only one required partition.
Calculate three linkage choices
Broadcast each response time in A against each time in B. The rows and columns preserve which members were compared.
import numpy as np
a = np.array([0., 1.])
b = np.array([4., 6.])
d = np.abs(a[:, None] - b[None, :])
print(d.tolist())
print([float(d.min()), float(d.max()), float(d.mean())])[[4.0, 6.0], [3.0, 5.0]]
[3.0, 6.0, 4.5]The same observations can therefore produce different merge priorities under different linkage rules.
6. A Second Merge Must Compare Groups, Not Their Names
After joining the first pair, recompute linkage using the members of the new group. A group identifier is only a bookkeeping label. Its numerical value has no role in the distance calculation.
For single linkage, the nearest pair across two groups determines their separation. This lets nearby points extend a chain even when its endpoints are far apart. Complete linkage would ask about those endpoints and can produce a different hierarchy.
Follow a small single-linkage hierarchy
The two pairs occupy response times near zero and near five.
import numpy as np
x = np.array([0., 1., 5., 6.])
groups = [[i] for i in range(len(x))]
while len(groups) > 1:
candidates = []
for i in range(len(groups)):
for j in range(i+1, len(groups)):
distance = min(abs(x[a]-x[b]) for a in groups[i] for b in groups[j])
candidates.append((distance, i, j))
distance, i, j = min(candidates)
merged = groups[i] + groups[j]
print(sorted(merged), float(distance))
groups = [g for k,g in enumerate(groups) if k not in [i,j]] + [merged][0, 1] 1.0
[2, 3] 1.0
[0, 1, 2, 3] 4.0At a cut below four but above one, the two close pairs remain separate. The final merge height describes the nearest cross-pair distance, not the total width of the combined group.
7. A Cut Is a Decision About Useful Resolution
The hierarchy does not automatically tell us how many physical sensor types exist. A cut chooses the resolution at which we want to describe similarity. Compare that choice with the purpose of grouping: shared calibration, inspection scheduling or exploratory description may favour different resolutions.
Check whether small measurement changes move important merges. Stable groups can be useful, but stability alone does not establish a causal or biological category. Retain the distance definition and linkage with the result so another reader can reproduce the tree.
Check yourself
Questions on Parts 1 to 7
Question 1 of 4
What is the single-linkage distance?
Use the information below.
Group A: [0, 1]
Group B: [4, 6]
Cross-group distances: [[4, 6], [3, 5]]Try it with Botie
Build with Botie
Write and run Python