Simple Algorithm
Machine Learning · Convergence · 26 min

Hierarchical & Density-Based Clustering

Dendrograms, linkage, DBSCAN and an impossibility theorem.

A dendrogram answers every "how many clusters?" question at once, and density-based methods let the data decide how many clusters there are and which points are noise. This lesson derives the classic linkages, proves that single linkage is a minimum spanning tree in disguise, makes DBSCAN, OPTICS and HDBSCAN precise, and proves Kleinberg's theorem that no clustering function can satisfy three natural axioms at once.

What you’ll learn

  • Run agglomerative clustering with single, complete, average and Ward linkage, derive Ward's merge cost, and write all four as Lance–Williams updates.
  • Prove that single-linkage clusters are the components of a minimum spanning tree with its heaviest edges removed, and explain chaining and the consistency of single linkage for density clusters.
  • Define DBSCAN's core, border and noise points exactly, and explain how OPTICS and HDBSCAN replace the fixed radius with a hierarchy.
  • State and prove Kleinberg's impossibility theorem, and describe the ways around it.

Agglomerative clustering and its linkages

Agglomerative hierarchical clustering starts with nn singleton clusters and repeatedly merges the two clusters A,BA,B with the smallest linkage distance D(A,B)D(A,B), recording the height at which each merge happens. After n−1n-1 merges everything is one cluster, and the record of merges is a dendrogram. Cutting it at any height gives a flat clustering, so one run serves every kk. The linkage decides what "closest clusters" means.

LinkageD(A,B)D(A,B)Typical behavior
singlemin⁡a∈A, b∈Bd(a,b)\min_{a\in A,\,b\in B}d(a,b)long, chained clusters; follows nonconvex shapes; a thin bridge of noise can merge two clusters
completemax⁡a∈A, b∈Bd(a,b)\max_{a\in A,\,b\in B}d(a,b)compact clusters of similar diameter; sensitive to outliers
average1∣A∣∣B∣∑a∈A∑b∈Bd(a,b)\frac1{\abs A\abs B}\sum_{a\in A}\sum_{b\in B}d(a,b)a compromise between the two
WardW(A∪B)−W(A)−W(B)W(A\cup B)-W(A)-W(B), the rise in within-cluster sum of squarescompact, k-means-like clusters, for Euclidean data
dd is any dissimilarity for the first three; Ward's method needs Euclidean geometry, because it is defined through centroids.
DerivationWard's merge cost
  1. W(A∪B)=W(A)+∣A∣ ∥μA−μ∥2+W(B)+∣B∣ ∥μB−μ∥2W(A\cup B)=W(A)+\abs A\,\norm{\boldsymbol\mu_A-\boldsymbol\mu}^2+W(B)+\abs B\,\norm{\boldsymbol\mu_B-\boldsymbol\mu}^2

    Let μ=∣A∣μA+∣B∣μB∣A∣+∣B∣\boldsymbol\mu=\frac{\abs A\boldsymbol\mu_A+\abs B\boldsymbol\mu_B}{\abs A+\abs B} be the centroid of A∪BA\cup B. The centroid identity, ∑x∈C∥x−c∥2=W(C)+∣C∣∥μC−c∥2\sum_{\mathbf x\in C}\norm{\mathbf x-\mathbf c}^2=W(C)+\abs C\norm{\boldsymbol\mu_C-\mathbf c}^2, applied to AA and to BB around μ\boldsymbol\mu:

  2. Δ(A,B)=W(A∪B)−W(A)−W(B)=∣A∣∣B∣2+∣B∣∣A∣2(∣A∣+∣B∣)2∥μA−μB∥2=∣A∣ ∣B∣∣A∣+∣B∣ ∥μA−μB∥2\Delta(A,B)=W(A\cup B)-W(A)-W(B)=\frac{\abs A\abs B^2+\abs B\abs A^2}{(\abs A+\abs B)^2}\norm{\boldsymbol\mu_A-\boldsymbol\mu_B}^2=\frac{\abs A\,\abs B}{\abs A+\abs B}\,\norm{\boldsymbol\mu_A-\boldsymbol\mu_B}^2

    Since μA−μ=∣B∣∣A∣+∣B∣(μA−μB)\boldsymbol\mu_A-\boldsymbol\mu=\frac{\abs B}{\abs A+\abs B}(\boldsymbol\mu_A-\boldsymbol\mu_B) and μB−μ=−∣A∣∣A∣+∣B∣(μA−μB)\boldsymbol\mu_B-\boldsymbol\mu=-\frac{\abs A}{\abs A+\abs B}(\boldsymbol\mu_A-\boldsymbol\mu_B):

  3. W(after the merge)=W(before)+min⁡A≠BΔ(A,B)W(\text{after the merge})=W(\text{before})+\min_{A\ne B}\Delta(A,B)

    Ward's method merges the pair with the smallest Δ\Delta, so each merge raises the total within-cluster sum of squares as little as possible. It is a greedy heuristic for the k-means objective, not an exact solver: an early merge can never be undone.

Predict before you look

Two clusters of sizes 2 and 3 have centroids 4 apart. By how much does merging them raise the within-cluster sum of squares?

Show the answer

19.2

Δ=2⋅32+3⋅42=1.2⋅16=19.2\Delta=\frac{2\cdot3}{2+3}\cdot4^2=1.2\cdot16=19.2. The factor ∣A∣∣B∣∣A∣+∣B∣\frac{\abs A\abs B}{\abs A+\abs B}, half the harmonic mean of the sizes, makes Ward reluctant to merge two large clusters and willing to absorb small ones.

All four linkages can be updated from the old distances alone. After merging clusters ii and jj, the distance from any other cluster kk to the merged one is given by the Lance–Williams recurrence (Lance & Williams, 1967):

d(k,i∪j)=αi d(k,i)+αj d(k,j)+β d(i,j)+γ ∣d(k,i)−d(k,j)∣.d(k,i\cup j)=\alpha_i\,d(k,i)+\alpha_j\,d(k,j)+\beta\,d(i,j)+\gamma\,\abs{d(k,i)-d(k,j)}.
Linkageαi\alpha_iαj\alpha_jβ\betaγ\gamma
single12\tfrac1212\tfrac1200−12-\tfrac12
complete12\tfrac1212\tfrac1200+12+\tfrac12
averagenini+nj\frac{n_i}{n_i+n_j}njni+nj\frac{n_j}{n_i+n_j}0000
Ward (with d=Δd=\Delta)ni+nkni+nj+nk\frac{n_i+n_k}{n_i+n_j+n_k}nj+nkni+nj+nk\frac{n_j+n_k}{n_i+n_j+n_k}−nkni+nj+nk-\frac{n_k}{n_i+n_j+n_k}00
nin_i is the size of cluster ii. For single linkage, 12(a+b)−12∣a−b∣=min⁡(a,b)\tfrac12(a+b)-\tfrac12\abs{a-b}=\min(a,b); for complete linkage the sign of γ\gamma flips it to max⁡(a,b)\max(a,b).

Storing the distance matrix takes O(n2)\order{n^2} memory, and naive merging O(n3)\order{n^3} time. For linkages with a reducibility property, which these four have, the nearest-neighbor-chain algorithm needs only O(n2)\order{n^2} time, and single linkage runs in O(n2)\order{n^2} time with O(n)\order{n} memory (SLINK: Sibson, 1973). The same four produce monotone dendrograms, with merge heights that never decrease; centroid and median linkage can produce inversions, where a later merge sits lower than an earlier one.

Single linkage is a minimum spanning tree

DerivationProof, through Kruskal's algorithm
  1. d(i,j)=min⁡a∈A, b∈Bd(a,b)=Dsingle(A,B)d(i,j)=\min_{a\in A,\ b\in B}d(a,b)=D_{\mathrm{single}}(A,B)

    Kruskal's algorithm scans pairs in increasing order of dd and accepts a pair when it joins two different components. Suppose it accepts (i,j)(i,j), joining components A∋iA\ni i and B∋jB\ni j. Any closer pair (a,b)(a,b) with a∈Aa\in A, b∈Bb\in B was scanned earlier, when aa and bb were already in different components (components only grow, and A≠BA\ne B now), so it would have been accepted and merged them. Hence:

  2. Dsingle(A,B)=min⁡A′≠B′Dsingle(A′,B′)D_{\mathrm{single}}(A,B)=\min_{A'\ne B'}D_{\mathrm{single}}(A',B')

    The same argument shows that no other pair of current components is closer in single linkage: its closest pair would have been scanned, and accepted, earlier. So each accepted edge performs exactly the merge that single linkage performs next, at the same height:

  3. {single-linkage clusters for k}=components of T∖{its k−1 heaviest edges}\{\text{single-linkage clusters for }k\}=\text{components of }T\setminus\{\text{its }k-1\text{ heaviest edges}\}

    Kruskal's accepted edges form a minimum spanning tree. Stopping after n−kn-k of them leaves kk components; the k−1k-1 edges not yet accepted are the heaviest edges of TT.

Three consequences. Single linkage costs no more than a minimum spanning tree: O(n2)\order{n^2} with Prim's algorithm on the complete graph, and less for low-dimensional Euclidean points, whose spanning tree can be found without examining every pair. The height at which ii and jj merge is the largest edge on the tree path between them, the minimax path distance, which is an ultrametric. And single linkage chains: only the closest pair counts, so a trail of points spaced more tightly than the gap between two clusters merges them, while one isolated point splits off before any real structure does.

Check your understanding

Two dense blobs 10 units apart are joined by a thin chain of points spaced 0.3 apart. Inside the blobs, nearest neighbors are 0.2 to 0.3 apart, and one stray point has its nearest neighbor 1.5 away. What does single linkage return with k=2k=2?

  1. The two blobs, each with half of the chain
  2. The chain as one cluster and both blobs as the other
  3. The stray point on its own, and everything else together
  4. It depends on the order in which the points are listed
Show the answer

C. The stray point on its own, and everything else together

With k=2k=2, single linkage deletes the heaviest edge of the minimum spanning tree. Every edge along the chain and inside the blobs is at most 0.3, while the stray point's edge is 1.5. So the stray point is split off, and the two blobs stay chained together. This is why single linkage is usually run with noise handling, as in the density-based methods below.

Is single linkage statistically sound? Hartigan proposed a target for hierarchical clustering: for a density ff, the clusters at level λ\lambda are the connected components of {x:f(x)≥λ}\{\mathbf x:f(\mathbf x)\ge\lambda\}, and all levels together form the cluster tree. An estimated hierarchy is consistent if, for any two disjoint such components AA and A′A', the smallest estimated clusters containing the sample points of AA and of A′A' are disjoint with probability tending to 1. Hartigan (1981) proved that single linkage is consistent in one dimension but not in two or more, where sample points form chains across low-density gaps (a continuum-percolation effect); it is only fractionally consistent. A robust variant that connects points only where the kk-nearest-neighbor radius is small, that is in high-density regions, is consistent, with finite-sample rates and lower bounds on the sample size that any method needs (Chaudhuri, Dasgupta, Kpotufe & von Luxburg, 2014).

Carlsson & Mémoli (2010) found a complementary characterization. Treat a hierarchical method as a map from finite metric spaces to dendrograms, viewed as ultrametrics; under three natural conditions, one of which is in the spirit of Kleinberg's consistency axiom below, single linkage is the unique such method, and it is stable under small perturbations of the input. Complete and average linkage are not stable in their sense, and their dendrograms can depend on how ties are broken.

Density-based clustering: DBSCAN, OPTICS and HDBSCAN

The core points of each DBSCAN cluster form a connected component of the graph that joins core points at distance at most ε\varepsilon; each cluster adds the border points within ε\varepsilon of its cores. That part is unique. A border point within ε\varepsilon of core points from two clusters can join either, so its label can depend on the order in which points are processed; the variant DBSCAN* treats border points as noise and removes the ambiguity. For choosing ε\varepsilon, the original paper sorts every point's distance to its 4th nearest neighbor, sets ε\varepsilon at the first "valley" of that curve, and fixes minPts=4\mathit{minPts}=4 for two-dimensional data.

Speed is subtler than first claimed. The original paper's O(nlog⁡n)\order{n\log n} was an average case resting on a spatial index; in the worst case the algorithm is quadratic. Gan & Tao (2015) proved that for d≥3d\ge3 exact DBSCAN needs about n4/3n^{4/3} time unless a geometric problem (unit-spherical emptiness checking) that is widely believed, like Hopcroft's problem, to need that much can be solved faster, and that a slightly relaxed, ρ\rho-approximate DBSCAN runs in expected O(n)\order{n} time in any fixed dimension; in two dimensions an exact O(nlog⁡n)\order{n\log n} algorithm exists. Schubert, Sander, Ester, Kriegel & Xu (2017) replied that with sensible parameters and indexes, DBSCAN remains practical.

Check your understanding

With minPts=4\mathit{minPts}=4 and radius ε\varepsilon, a point pp has two other points within distance ε\varepsilon, so ∣Nε(p)∣=3\abs{N_\varepsilon(p)}=3, and one of those two is a core point. What is pp?

  1. A core point, because it has neighbors
  2. A border point of the core point's cluster
  3. Noise, because it is not a core point
  4. The seed of a new cluster
Show the answer

B. A border point of the core point's cluster

pp fails the core condition (3<43<4, counting pp itself), but it lies within ε\varepsilon of a core point, so it is directly density-reachable from it and joins that cluster as a border point. Only points that are neither core nor within ε\varepsilon of any core point are noise.

One radius cannot fit clusters of different densities. OPTICS (Ankerst, Breunig, Kriegel & Sander, 1999) avoids choosing it. A point's core distance is the radius at which it would become a core point, and the reachability distance of pp from oo is max⁡{core-dist(o), d(o,p)}\max\{\text{core-dist}(o),\,d(o,p)\}. Visiting points in order of smallest reachability produces a plot in which clusters appear as valleys, for every ε\varepsilon up to a maximum at once.

HDBSCAN (Campello, Moulavi & Sander, 2013) turns this into a hierarchy and then selects from it. With corek(x)\mathrm{core}_k(\mathbf x) the distance from x\mathbf x to its kk-th nearest neighbor (counting x\mathbf x), define the mutual reachability distance

dmreach(a,b)=max⁡{corek(a), corek(b), d(a,b)}.d_{\mathrm{mreach}}(\mathbf a,\mathbf b)=\max\{\mathrm{core}_k(\mathbf a),\ \mathrm{core}_k(\mathbf b),\ d(\mathbf a,\mathbf b)\}.

Two points are joined at level ε\varepsilon exactly when both are core points at radius ε\varepsilon and lie within ε\varepsilon of each other, so single linkage on dmreachd_{\mathrm{mreach}}, computed through a minimum spanning tree, contains the DBSCAN* clustering for every ε\varepsilon at once. HDBSCAN condenses this tree by ignoring splits that shed fewer points than a minimum cluster size, then picks the flat clusters with the greatest stability, ∑p(λp−λbirth)\sum_{p}(\lambda_p-\lambda_{\mathrm{birth}}) with λ=1/ε\lambda=1/\varepsilon: clusters that persist over a long range of density levels win. Everything outside them is noise.

Kleinberg's impossibility theorem

DerivationProof that the range is an antichain
  1. d′(i,j)≤a inside clusters of Γ,d′(i,j)≥b across them⟹f(d′)=Γd'(i,j)\le a\ \text{inside clusters of }\Gamma,\quad d'(i,j)\ge b\ \text{across them}\quad\Longrightarrow\quad f(d')=\Gamma

    Forcing pairs. Let ff be consistent and f(d)=Γf(d)=\Gamma. Choose a<ba<b with aa at most every within-cluster distance of dd and bb at least every between-cluster distance. Any d′d' whose within-cluster distances are at most aa and whose between-cluster distances are at least bb is a Γ\Gamma-transformation of dd, so consistency gives:

  2. d(i,j)≤ε inside Γ0,a2≤d(i,j)≤a1 inside Γ1 only,d(i,j)≥b1 across Γ1d(i,j)\le\varepsilon\ \text{inside }\Gamma_0,\qquad a_2\le d(i,j)\le a_1\ \text{inside }\Gamma_1\text{ only},\qquad d(i,j)\ge b_1\ \text{across }\Gamma_1

    Suppose Γ0≠Γ1\Gamma_0\ne\Gamma_1 are both in the range and Γ0\Gamma_0 refines Γ1\Gamma_1, with forcing pairs (a0,b0)(a_0,b_0) and (a1,b1)(a_1,b_1). Pick a2≤a1a_2\le a_1 and 0<ε<a0a2/b00<\varepsilon<a_0a_2/b_0, and build dd in three bands. Then dd is Γ1\Gamma_1-forced: inside Γ1\Gamma_1's clusters every distance is at most a1a_1 (as ε<a2\varepsilon<a_2), and across them at least b1b_1. So f(d)=Γ1f(d)=\Gamma_1:

  3. Γ0=f(αd)=f(d)=Γ1,a contradiction\Gamma_0=f(\alpha d)=f(d)=\Gamma_1,\quad\text{a contradiction}

    Now rescale by α=b0/a2\alpha=b_0/a_2. Inside Γ0\Gamma_0's clusters, αd≤εb0/a2<a0\alpha d\le\varepsilon b_0/a_2<a_0; across them, αd≥a2⋅b0/a2=b0\alpha d\ge a_2\cdot b_0/a_2=b_0 (pairs across Γ1\Gamma_1 are farther still, as b1>a1≥a2b_1>a_1\ge a_2). So αd\alpha d is Γ0\Gamma_0-forced, while scale-invariance demands f(αd)=f(d)f(\alpha d)=f(d):

  4. {{1},…,{n}} refines {S}⟹the range of a rich f is not an antichain\{\{1\},\dots,\{n\}\}\ \text{refines}\ \{S\}\quad\Longrightarrow\quad\text{the range of a rich }f\text{ is not an antichain}

    Richness would put every partition in the range, including the nn singletons and the single cluster SS. For n≥2n\ge2 the first is a proper refinement of the second, so the set of all partitions is not an antichain. That proves the theorem.

Single linkage, stopped by…Scale-invariantRichConsistent
kk clusters: stop when kk components remainyesnoyes
distance rr: add only edges of length at most rrnoyesyes
scale α\alpha: add only edges up to α\alpha times the largest distance (0<α<10<\alpha<1)yesyesno
Any two axioms can hold at once (Kleinberg, 2002, Theorem 2.2; the last row needs n≥3n\ge3). Every practical method gives one up: a fixed kk gives up richness, and a built-in length scale such as DBSCAN's ε\varepsilon gives up scale-invariance.
Think first DBSCAN with minPts=1\mathit{minPts}=1 and a fixed ε\varepsilon: which of Kleinberg's axioms does it satisfy?

With minPts=1\mathit{minPts}=1 every point is a core point (its neighborhood contains itself), so the clusters are the connected components of the graph joining points at distance at most ε\varepsilon. That is single linkage with the distance-ε\varepsilon stopping rule: rich and consistent, but not scale-invariant. Doubling every distance can break clusters apart, because ε\varepsilon is a length scale built into the method.

Kleinberg also showed that centroid-based clustering functions that choose kk of the input points as centers, including the kk-median function, violate consistency once nn is large compared with kk. Weakening the axioms helps only so much. With refinement-consistency (a Γ\Gamma-transformation may only refine the clustering) the impossibility survives, but barely: some scale-invariant, refinement-consistent functions produce every partition except the nn singletons. Changing the output helps more. Asking for a dendrogram instead of a partition turns non-existence into existence and uniqueness, the single-linkage theorem of Carlsson & Mémoli above.

Key takeaways

  • Agglomerative clustering merges the closest pair of clusters under a linkage (single, complete, average or Ward), and the merges form a dendrogram that serves every kk; all four follow the Lance–Williams recurrence, and Ward's merge cost is ∣A∣∣B∣∣A∣+∣B∣∥μA−μB∥2\frac{\abs A\abs B}{\abs A+\abs B}\norm{\boldsymbol\mu_A-\boldsymbol\mu_B}^2.
  • Single linkage is Kruskal's algorithm: its clusters for kk are the components of a minimum spanning tree minus its k−1k-1 heaviest edges. It chains through bridges of points, and it is consistent for Hartigan's cluster tree only in one dimension, while robust variants are consistent in general.
  • DBSCAN defines clusters as density-connected sets of core points with their border points, and labels the rest noise; OPTICS and HDBSCAN remove the single radius, and HDBSCAN selects the clusters that persist longest across density levels.
  • Kleinberg's theorem: no clustering function is scale-invariant, rich and consistent, because the first and third force the range to be an antichain. Each method gives up one axiom; with dendrograms as output, single linkage is the unique method satisfying an analogous set of axioms.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Ward's method considers merging a cluster of 2 points with a cluster of 3 points whose centroids are 2 apart. What is the merge cost Δ\Delta?

  1. 2.4
  2. 4.8
  3. 9.6
  4. 20
Show the answer

B. 4.8

Δ=∣A∣∣B∣∣A∣+∣B∣∥μA−μB∥2=65⋅4=4.8\Delta=\frac{\abs A\abs B}{\abs A+\abs B}\norm{\boldsymbol\mu_A-\boldsymbol\mu_B}^2=\frac{6}{5}\cdot4=4.8: the increase in the total within-cluster sum of squares caused by the merge.

Question 2

How do you obtain the single-linkage clustering into kk clusters from a minimum spanning tree of the points?

  1. Delete the k−1k-1 heaviest edges of the tree and take the connected components
  2. Delete the k−1k-1 lightest edges of the tree
  3. Keep only the kk heaviest edges
  4. Cut every edge longer than the median edge
Show the answer

A. Delete the k−1k-1 heaviest edges of the tree and take the connected components

Kruskal's algorithm performs single linkage's merges in order, so the last k−1k-1 edges it would add, the heaviest in the tree, are exactly the merges that have not yet happened when kk clusters remain.

Question 3

Single linkage with the distance-rr stopping rule (merge only along edges of length at most rr) satisfies which two of Kleinberg's axioms?

  1. Scale-invariance and richness
  2. Scale-invariance and consistency
  3. Richness and consistency
  4. All three, for a suitable rr
Show the answer

C. Richness and consistency

Any partition is reachable by making within-cluster distances below rr and the rest above it (richness). Shrinking within-cluster distances and stretching between-cluster ones keeps every within-cluster edge below rr and every between-cluster distance above it, so the output is unchanged (consistency). But rescaling all distances can push edges across rr, so it is not scale-invariant.

Question 4

Why can DBSCAN's output depend on the order in which points are processed?

  1. Core points are chosen at random
  2. The number of clusters is estimated from a random sample
  3. The radius ε\varepsilon is adjusted as clusters grow
  4. A border point within ε\varepsilon of core points from two clusters can be assigned to either
Show the answer

D. A border point within ε\varepsilon of core points from two clusters can be assigned to either

Core points and the cluster structure among them are determined by the data alone. A border point is not core, so it cannot connect clusters, but it may be reachable from both; it joins whichever cluster reaches it first. DBSCAN* labels such points noise, which makes the result order-independent.

Further reading

  • J. H. Ward Jr., "Hierarchical grouping to optimize an objective function," Journal of the American Statistical Association 58(301), 236–244 (1963).
  • J. C. Gower & G. J. S. Ross, "Minimum spanning trees and single linkage cluster analysis," Journal of the Royal Statistical Society C (Applied Statistics) 18(1), 54–64 (1969).
  • M. Ester, H.-P. Kriegel, J. Sander & X. Xu, "A density-based algorithm for discovering clusters in large spatial databases with noise," Proceedings of the 2nd International Conference on Knowledge Discovery and Data Mining (KDD-96), 226–231 (1996).
  • R. J. G. B. Campello, D. Moulavi & J. Sander, "Density-based clustering based on hierarchical density estimates," Advances in Knowledge Discovery and Data Mining (PAKDD 2013), Lecture Notes in Computer Science, 160–172 (2013).
  • J. Kleinberg, "An impossibility theorem for clustering," Advances in Neural Information Processing Systems 15 (NIPS 2002), 463–470 (MIT Press, 2003).