Hierarchical clustering: merge criteria, tree heights and cuts
层次聚类
Compare single, complete, average and Ward linkage with exact merge records, explicit ties and correctly scaled tree heights.
hierarchical-clusteringA tree of merges keeps several resolutions
Five toy timing offsets are 0, 1, 4, 5 and 9 minutes. At a fine resolution, 0 and 1 belong together, as do 4 and 5. The next decision is less obvious: should the two pairs join, or should 9 join the pair near 5? The answer depends on what “close groups” means.
Agglomerative hierarchical clustering starts with one cluster per observation and repeatedly merges a selected pair. Its output records every merge, not just one partition. A cut selects a resolution afterward. Divisive methods build a hierarchy by splitting instead; this chapter implements the agglomerative case. A dendrogram is a record of that algorithm’s decisions, not proof of a natural genealogy or a probability that two objects share a cause.
Unlike k-means, this construction needs neither initial centers nor a fixed final k during fitting. It still needs a dissimilarity, a linkage rule and a tie convention. Different choices can produce different hierarchies from identical observations.
Define distance between groups before merging them
For two disjoint nonempty clusters A and B, three common rules use the original pairwise distances d(x,y):
Single linkage only needs one short connection. Complete linkage looks at the most distant cross-pair. Average linkage gives every cross-pair equal weight; it is often called UPGMA. It is not the distance between the two centroids. Nor is it the WPGMA rule that gives the two previously merged clusters equal weight regardless of their sizes. SciPy 1.15.3 linkage definitions
This choice changes interpretation. At height h, single-linkage clusters are connected components of the graph joining observations at distance at most h. Following several short edges can connect endpoints much farther than h. Complete-linkage clusters formed by height h have diameter at most h. The average rule is a compromise in how it scores cross-pairs, not a guarantee of either of those particular properties.
Ward compares the increase in squared error
With Euclidean coordinates and each cluster’s arithmetic mean μ, define within-cluster SSE W. Expanding the squares around the merged mean gives
The expansion uses the fact that centered vectors sum to zero. The two mean-displacement terms reduce to the size-weighted squared difference above. Ward’s rule selects the pair with the smallest increase, so cluster sizes matter. It does not minimize the largest pairwise distance, and it does not guarantee the globally minimum SSE partition at every k. Ward’s original paper describes hierarchical merging as a compromise when independently optimal partitions at all resolutions are impractical. Ward, 1963, pages 236–238
One must specify the dendrogram’s height convention. We use the Euclidean linkage-height convention associated with the SciPy recurrence:
For two singleton observations, this height equals their ordinary Euclidean distance. The program stores its square exactly, labeled height-squared; it prints a symbolic square root. If coordinates are in minutes, height is in minutes, while the stored Ward level and SSE increment are in squared minutes. They differ by a factor of two. Comparing a stored Ward level directly with an ordinary-distance threshold would mix units.
Why the recorded heights do not go backward
Each merge removes two current clusters and inserts their union. For single, complete and average linkage, a new distance to a third cluster is respectively the minimum, maximum or size-weighted mean of the two previous distances. None can be smaller than the global minimum just selected. For Ward’s squared heights q, merging A and B gives
Both positive-term distances are at least the selected q_AB. Substituting that lower bound shows the new value is at least q_AB too. Thus these four methods have nondecreasing merge heights on the stated Euclidean input. Other linkage rules can have inversions; do not generalize the argument to every hierarchy. Versioned recurrence and Euclidean condition
Read an exact merge tree and cut it two ways
The complete Python program accepts a nonempty sequence of one-dimensional integer or Fraction coordinates. Ordinary distance is absolute difference. It recomputes each cluster-pair criterion directly from its members, while the tests use independent distance-update recurrences. This deliberately simple implementation has no distance-matrix input, missing values or approximate comparisons.
Original observations have IDs 0 through n−1. Merge t creates node n+t, and its record contains (left_id, right_id, level, member_count). Equal scores choose the lexicographically smallest sorted pair of current node IDs. This is reproducible for the same input order; it does not promise order-invariant partitions when ties exist. Repeated observations stay separate leaves and may merge at height zero.
cut_k performs the first n−k recorded merges. cut_height includes all merges with height at most its nonnegative threshold; for Ward it compares the stored level with the squared threshold. Cut results contain original row indices, not coordinate values. The model must be an unmodified result of fit. Invalid types, unsupported methods and out-of-range controls raise ValueError; one observation produces an empty merge sequence and a singleton cut.
from fractions import Fraction as F
from itertools import combinations
def number(value):
if type(value) not in (int, F):
raise ValueError('use integer or Fraction coordinates and heights')
return F(value)
def merge_level(x, a, b, method):
# a and b contain original row indices in disjoint active clusters.
if method == 'ward':
ma = sum((x[i] for i in a), F())/len(a)
mb = sum((x[i] for i in b), F())/len(b)
return F(2*len(a)*len(b), len(a)+len(b))*(ma-mb)**2
distances = (abs(x[i]-x[j]) for i in a for j in b)
if method == 'single':
return min(distances)
if method == 'complete':
return max(distances)
return sum(distances, F())/(len(a)*len(b))
def fit(values, method='average'):
if type(values) not in (list, tuple) or not values:
raise ValueError('provide a nonempty sequence of scalar coordinates')
x = tuple(number(v) for v in values)
if type(method) is not str or method not in ('single','complete','average','ward'):
raise ValueError('unsupported linkage')
n = len(x)
active, merges = {i:(i,) for i in range(n)}, []
while len(active) > 1:
best = None
for a, b in combinations(sorted(active), 2):
candidate = (merge_level(x, active[a], active[b], method), a, b)
if best is None or candidate < best:
best = candidate
level, a, b = best
members = active.pop(a)+active.pop(b)
node = n+len(merges)
active[node] = members
merges.append((a, b, level, len(members)))
return {'n':n, 'method':method,
'level_kind':'height-squared' if method=='ward' else 'height',
'merges':tuple(merges)}
def cut_k(model, k):
# model must be an unmodified result of fit.
n = model['n']
if type(k) is not int or not 1 <= k <= n:
raise ValueError('k must be an integer between one and n')
active = {i:(i,) for i in range(n)}
for t, (a, b, _, _) in enumerate(model['merges'][:n-k]):
active[n+t] = active.pop(a)+active.pop(b)
return tuple(sorted(tuple(sorted(group)) for group in active.values()))
def cut_height(model, height):
height = number(height)
if height < 0:
raise ValueError('height must be nonnegative')
limit = height*height if model['method']=='ward' else height
count = 0
for _, _, level, _ in model['merges']:
if level > limit:
break
count += 1
return cut_k(model, model['n']-count)
def tree_text(model):
# An exact nested tree; @sqrt(q) is symbolic, not rounded to a decimal.
nodes = {i:str(i) for i in range(model['n'])}
for t, (a, b, level, _) in enumerate(model['merges']):
height = f'sqrt({level})' if model['method']=='ward' else str(level)
nodes[model['n']+t] = f'({nodes.pop(a)},{nodes.pop(b)})@{height}'
return next(iter(nodes.values()))
if __name__ == '__main__':
x = [0, 1, 4, 5, 9]
for method in ('single','complete','average','ward'):
model = fit(x, method)
print(method, 'tree:', tree_text(model))
print('two groups:', cut_k(model, 2), 'height 4:', cut_height(model, 4))
tied = fit([0, 1, 2], 'single')
print('equal-height k=2 / h=1:', cut_k(tied, 2), cut_height(tied, 1))
The output is
single tree: (4,((0,1)@1,(2,3)@1)@3)@4
two groups: ((0, 1, 2, 3), (4,)) height 4: ((0, 1, 2, 3, 4),)
complete tree: ((0,1)@1,(4,(2,3)@1)@5)@9
two groups: ((0, 1), (2, 3, 4)) height 4: ((0, 1), (2, 3), (4,))
average tree: (4,((0,1)@1,(2,3)@1)@4)@13/2
two groups: ((0, 1, 2, 3), (4,)) height 4: ((0, 1, 2, 3), (4,))
ward tree: ((0,1)@sqrt(1),(4,(2,3)@sqrt(1))@sqrt(27))@sqrt(363/5)
two groups: ((0, 1), (2, 3, 4)) height 4: ((0, 1), (2, 3), (4,))
equal-height k=2 / h=1: ((0, 1), (2,)) ((0, 1, 2),)
In the printed tree, (a,b)@h joins its two subtrees at height h. Leaf labels are record indices: leaf 4 means the offset 9. Child order is a display convention and is not a time ordering of the original observations.
After the first two merges, the active groups are A=(0,1), B=(4,5) and C=(9), writing coordinate values here. Single linkage gives A–B distance 3 and B–C distance 4, so it joins A and B. Average linkage gives 4 versus 9/2 and makes the same choice. Complete linkage gives 5 for both pairs; the node-ID tie rule joins C with B. Ward has SSE increments 16 for A–B and 27/2 for B–C, so it also joins C with B, now for a strict quantitative reason.
The last line exposes a different ambiguity. On offsets 0,1,2, single linkage has two merges at height one. A two-group cut stops after one of them, but a height-one cut includes both. A horizontal height threshold cannot express every requested k when merge heights tie. Neither result is a failed cut.
At each stage, the total number of raw cross-pairs across active clusters is O(n²). There are n−1 stages, giving O(1+n³) arithmetic/comparison work for this implementation; recomputing Ward means satisfies the same bound. Active membership lists partition n indices, and merge records contain O(n) fields, so working plus returned storage is O(n) numeric/index slots. This trades memory for repeated computation and does not describe an optimized library implementation.
Cutting costs O(1+n²) operations in the worst case because tuple concatenation can repeatedly copy large groups; it uses O(n) slots. For text rendering, let L be the final character count: repeated nested-string construction takes at most O(1+nL) character work and O(1+L) character storage. Rational bit lengths and printed number lengths are extra costs beyond unit arithmetic.
A useful diagram still depends on modeling choices
Single linkage can connect a long chain through intermediate records. Complete linkage resists that particular effect, but an extreme observation can dominate its cross-pair maximum. Average linkage depends on the multiplicity of observations; silently removing duplicates changes its weighting. Ward favors small increases in within-cluster SSE, so changing coordinate scales changes what it considers compact.
The Ward derivation needs Euclidean geometry. Feeding an arbitrary similarity matrix, or squared distances where an API expects ordinary Euclidean distances, does not preserve its meaning. A software parameter called “Ward” is not enough to establish the objective and height convention. The fixed SciPy manual makes the Euclidean requirement and tie behavior explicit.
Once two observations have merged, this algorithm cannot separate them later. That restriction creates a hierarchy, but may prevent the best unconstrained partition for a later k. A large visual gap in merge heights can suggest a cut; it is not a significance test or proof of a correct number of groups. Stability under reasonable resampling, feature choices and scale changes answers a different question from simply drawing a tree.
There is also no universal prediction rule for a new observation. Assigning it to a nearest centroid, nearest member or minimum-linkage group are different extensions. Refitting the hierarchy can change old merges. Decide which behavior the application needs instead of treating the dendrogram as a trained classifier.
Name the quantity on the vertical axis
- Why does a single-linkage height-one cut of offsets 0,1,2 contain all three points although the endpoints are distance two apart?
Show answer
Answer: The edges 0–1 and 1–2 both qualify, so the graph is connected. Single linkage requires a chain of short connections, not a diameter bound. The two merges tie at height one, and the height cut includes both.
- For A=(4,5) and B=(9), calculate the Ward SSE increment, stored level and displayed height. Would height threshold 4 merge them?
Show answer
Answer: The means are 9/2 and 9; the increment is (2/3)(9/2)²=27/2. The stored level is 27 and the height is √27. Threshold 4 does not merge them, since 27 exceeds 4². Comparing 27 directly with 4 would use mismatched units even though it happens to reject this pair too.
- Suppose A=(0,2) and B=(10) have merged. What is their average-linkage distance to C=(20), and why is averaging the two previous cluster distances equally wrong?
Show answer
Answer: The three cross-distances are 20,18,10, averaging to 16. A–C distance was 19 and B–C was 10; the correct update is (2·19+1·10)/3=16, not (19+10)/2=29/2. Average linkage weights the prior groups by their observation counts.
- Do two libraries necessarily return identical partitions if they use the same linkage formula and encounter equal merge scores?
Show answer
Answer: No. Different tie policies can select different pairs. Even our reproducible node-ID policy can change a tied partition if input rows are reordered. Compare heights, memberships and the tie convention; rotated left/right drawing order alone does not change memberships.
Separate the criterion from the implementation
Ward’s 1963 paper frames merging through an objective loss and explicitly distinguishes a hierarchy from independently optimal groupings. The modern linkage interface places that criterion beside single, complete and average linkage, with precise matrix and height conventions. The same formula can be evaluated by recomputing members, updating a distance matrix or using a more specialized algorithm; those choices change cost without changing the intended criterion, provided ties are treated consistently.
Continue with clustering evaluation to assess a selected partition. DBSCAN instead builds groups from density and connectivity rules; that is a different definition of a cluster, not another name for cutting this merge tree.
Make a prediction, then check
A Ward merge stores level 27 under the program’s height-squared convention. Should a height threshold of 5 include it?
Learning objectives
- Compare four merge criteria and distinguish average cross-pair distance from centroid distance.
- Derive Ward’s SSE increment and track its relation to squared linkage height.
- Interpret merge records and explain why a fixed-k cut and a height cut can differ at ties.
Prerequisites & connections
Explore related knowledge →References
- Hierarchical Grouping to Optimize an Objective Function
Joe H. Ward, Jr. · 1963 - linkage — SciPy 1.15.3 Manual
The SciPy community
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- Eight tests pass. An independent Lance–Williams distance-cache implementation checks 24 complete fit reports, including all n−1 merge tuples, sizes and height-kind fields; disjoint-set replay checks all 88 fixed-k cuts. Twenty-four single-linkage height cuts independently equal the connected components of the original distance-threshold graph. The reference never rescans original cluster members to compute the merge criterion.
- Pairwise variance independently verifies that Ward’s cumulative stored levels divided by two equal within-partition SSE. Checked unequal-size average weights, exact Ward threshold units, equal-height partial cuts, duplicates and singletons, translation/negative uniform scaling, input/model preservation, invalid controls and 70-digit rational scales. Full stdout contains nine lines with symbolic square-root dendrograms.
- Complete original bilingual text, identical code, four matching displayed formulas, six ordered anchors and four answered exercises pass strict MDX/KaTeX/React HTML, MathML and emphasis checks. Only article_text controls test paths. Humanizer reread. Status written is AI author checking, not human review; no SciPy execution, large-data benchmark, whole-site build or browser acceptance.
- Ran all eight author tests. Independent criteria use adjacent opposite-group positions for single linkage, union diameter for the current greedy complete-linkage clusters, integrated empirical-CDF cross counts for average linkage, and indicator-subspace projection-matrix differences for Ward. These avoid both the direct author member-pair/mean formulas and the author test’s Lance–Williams recurrence. Sixteen models, 160 candidate scores and 40 complete merge records match exactly.
- Reverse tree splitting from the root independently checks 56 fixed-k cuts and 80 height cuts, instead of replaying forward merges or union-find edges. Checked scalar singleton, duplicates, tied merges, Ward squared-height thresholds and all four linkage choices. On coordinates (0,2,3,5), a projection-based audit finds Ward’s two-cluster SSE is 14/3 while partition ((0,1),(2,3)) has SSE 4, independently substantiating the stated lack of global partition optimality.
- Reviewed complete bilingual prose and mathematical assumptions: cross-pair averaging versus centroid/WPGMA, Ward size factor and Euclidean geometry, height-squared units, monotone-height proof, node-ID tie policy, irreversible hierarchy, height cuts unable to express every k at ties, and lack of a universal new-point assignment rule. Direct recomputation, cut concatenation and nested-text complexity bounds include stored membership and output, with rational bit costs qualified.
- Strict MDX/KaTeX and actual React HTML pass with four displays, six anchors and four answers per language; all four math annotations match. Final executable fence equals example.py, author tests verify bilingual code and all nine stdout lines, and five hashes/source IDs/URLs match the frozen manifest and metadata. No changes requested.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Hierarchical Grouping to Optimize an Objective Function · The university PDF opened through web but produced no extracted text. Web screenshots did not expose visible image content to this agent, so no reading is attributed to those calls. Downloaded the same official university-hosted PDF into this temporary directory using approved network access, rendered physical pages 2–4 with pdftoppm and actually viewed the images. Read printed pages 236–238: title/author, irreversible pair-merging compromise, objective-function section with ESS around the mean, sum of group errors, and explicit statement that a hierarchy need not optimize the objective for a specified number of groups. Printed page 238 identifies March 1963. Publisher DOI record https://doi.org/10.1080/01621459.1963.10500845 independently distinguishes the 1963 issue from April 10, 2012 online publication. Remaining original pages were not reviewed. Stored PDF is a reference artifact only, not website content.
- linkage — SciPy 1.15.3 Manual · Actually opened the official 1.15.3 linkage manual. Read lines 31–40 (hierarchy and n+i merge fields), 43–65 (single, complete, UPGMA versus WPGMA), 75–80 (Ward recurrence and tie warning), 115–118 (optimized implementation costs and Euclidean requirement). The initially attempted 1.16.2 URL returned an internal tool error; the article binds only the successful 1.15.3 page. Derived the exact height-squared=2*SSE-increase convention from singleton distances and the recurrence. No claim that the teaching program has SciPy’s optimized complexity or library tie behavior.
- Hierarchical Grouping to Optimize an Objective Function · Actually opened the listed university-hosted PDF through web; it has ten pages but no extracted text. Independently viewed the author-retained renders ward-page-02.png, ward-page-03.png and ward-page-04.png in the draft directory. These show printed pages 236–238: title and Joe H. Ward Jr., the irreversible-merging compromise, ESS around the group mean and sum of group errors, and the explicit statement that a hierarchy need not optimize the criterion at a specified group count. Printed page 238 carries March 1963. No remaining-page or publisher-online-date audit claimed.
- linkage — SciPy 1.15.3 Manual · Actually opened the exact SciPy 1.15.3 manual. Read lines 31–40 for agglomeration and four merge-matrix fields, 43–65 for single/complete/UPGMA versus WPGMA, 75–80 for Ward recurrence and differing tie policies, and 115–118 for optimized library complexity and Euclidean restrictions. The chapter correctly derives height-squared=2*delta-SSE from the recurrence and singleton convention, and distinguishes its recomputing implementation costs from the library. No SciPy execution.
Related topics