Module contents
Lesson 5 of 24Core 95 min

Density-based clustering: DBSCAN, OPTICS and HDBSCAN

Density level-set clusters, DBSCAN, OPTICS and HDBSCAN, including variable-density hierarchies and stability.

After this lesson you can

  • Define core, boundary and noise points and density reachability in DBSCAN.
  • Relate DBSCAN to density level sets and single linkage.
  • Choose eps and minPts using k-distance plots and recognize when no eps works.
  • Construct the HDBSCAN hierarchy and select clusters by excess of mass.
  • Implement DBSCAN and validate against scikit-learn.

Before you start

Motivation: arbitrary shapes, explicit noise and no kk

You have the positions of thousands of satellite-detected fires and want to locate hotspots. Or a LiDAR point cloud from a driving scene and want to separate cars, pedestrians and streetlights. Or a store’s customers described by a few variables. All three share the same issue: you do not know how many groups exist, groups are not balls (a road is a line, a facade a plane), and some points belong to no group and should simply be left out.

k-means fails at all three. It requires choosing kk, divides space into Voronoi cells, and assigns every point a cluster, including noise that also pulls centroids. Hierarchical clustering does not require kk and single linkage follows elongated shapes, but a handful of intermediate points chains them (you saw eight points suffice to merge two clouds), and it cannot say “this is noise” either.

This lesson takes another approach. A cluster is a connected region where points are dense, separated from other regions by sparse zones. This definition gives arbitrary shapes for free (a connected region can be a moon), defines noise (what lies in no dense region), and removes kk as a parameter (the number of regions is a result). The price is that density must be measured, and measuring it well with few points is the problem of density estimation and kk-neighbor estimation from the previous lesson.

The lesson proceeds as follows. First Hartigan’s ideal definition with known density: clusters are connected components of level sets and form a tree. Then DBSCAN, that definition at a single level with density estimated by counting neighbors in a ball. Next, how to choose its two parameters and why sometimes none is good. Then OPTICS, ordering points to summarize all levels together, and HDBSCAN, building the full tree and selecting clusters by stability. It ends with costs, spatial indices and high dimension, where all this breaks down.

Clusters as connected components of {f≥λ}\{f \ge \lambda\}

Suppose for a moment you know the density ff generating the data. A group should be a region where ff is high. But how high? Hartigan (1975) answered without choosing: all levels at once.

That it is a tree rather than an arbitrary graph is proved in two lines.

Proof

Since λ′≥λ\lambda' \ge \lambda, L(λ′)⊆L(λ)L(\lambda') \subseteq L(\lambda). Set C′C' is connected and contained in L(λ)L(\lambda), so lies in a single connected component of L(λ)L(\lambda). If that component is CC, then C′⊆CC' \subseteq C; if another, C′C' is disjoint from CC because components are disjoint.

∎

Picture it: raise λ\lambda from zero and inspect what remains above the level. At first everything is connected. As it rises, a low-density valley between two modes is crossed and the component splits in two. As the level keeps rising both shrink to their mode peaks and disappear. Tree leaves are modes, and each internal node is a place where two groups separate.

InteractiveRaising the water level
Density ff and colored set {f≥λ}\{f \ge \lambda\}
−6−4−20246λ = 0.060
Cluster tree: height = level λ\lambda
ramas ordenadas por la posición de su moda
  • component of {f≥λ}\{f \ge \lambda\} (color = tree branch)
  • below the level (not in any cluster)
  • level λ\lambda
Density
0.060
Components of {f≥λ}\{f \ge \lambda\} (clusters)3
Mass inside {f≥λ}\{f \ge \lambda\}88.2 %
Tree leaves (modes)4
Maximum components at one level3
Equivalent radius ε\varepsilon (n=1000n = 1000, k=10k = 10)0.084
At this level there are 3 components. Each is a cluster; points below the level belong to none. No single level shows all 4 modes at once: the maximum is 3.
A known density (a mixture of four Gaussians, in one dimension and in the plane) and a level λ\lambda you control. What remains above the level is colored by component; on the right, the cluster tree with the same palette. Raise λ\lambda from the start: two nearby modes separate at a high level and a wide low mode separates sooner, much lower. Note the red readout: no single level gives more than 3 components, although the tree has 4 leaves (in one dimension and in the plane). To see every mode as a separate cluster each must be viewed at its own level, which DBSCAN cannot do and HDBSCAN can.

That red readout organizes the rest of the lesson. A flat clustering, a partition recovering all four modes, must use different levels on different branches: inspect the narrow high mode at a high level and the wide low mode at a low one. One density threshold is insufficient.

From known density to a sample

With data you have only points. The previous lesson’s kk-neighbor estimator gives a density at each point: the smallest ball centered at xx containing kk points (counting xx itself if it is in the sample) has radius rk(x)r_k(x), and since it encloses mass k/nk/n in volume Vd rk(x)dV_d\,r_k(x)^d, with VdV_d the unit-ball volume in Rd\R^d,

f^k(x)=kn Vd rk(x)d.\hat f_k(x) = \frac{k}{n\,V_d\,r_k(x)^d}.

Other normalizations (for example k−1k - 1 in the numerator) change one constant and nothing that follows. Throughout the lesson rkr_k is called core distance ck(x)c_k(x), counting the point itself as first neighbor, so c1(x)=0c_1(x) = 0. This is scikit-learn’s convention.

A sample clustering at level λ\lambda would then keep points with f^k≥λ\hat f_k \ge \lambda and join those that are “connected.” We still need to define connectivity with only isolated points. The simplest answer is to connect those within radius ε\varepsilon and take connected components of the resulting graph. That is almost word for word DBSCAN.

A historical note with consequences. Hartigan (1981) proved single linkage is consistent in one dimension for recovering these clusters, but ceases to be in dimension d≥2d \ge 2 (via reduction to continuum percolation). Chaudhuri and Dasgupta (2010, “Rates of convergence for the cluster tree”) propose robust single linkage: for each radius rr, the graph whose vertices are points with rk(xi)≤rr_k(x_i) \le r and whose edges join pairs with ∥xi−xj∥≤αr\norm{x_i - x_j} \le \alpha r. Single linkage is the case α=1\alpha = 1, k=2k = 2, and Wishart (1969) had proposed α=1\alpha = 1 with larger kk. For 2≤α≤2\sqrt 2 \le \alpha \le 2 and kk of order dlog⁡nd \log n they prove the estimated tree converges to Hartigan’s with explicit rates. Remember α=1\alpha = 1: for each rr that graph is exactly what HDBSCAN constructs with mutual reachability distance, as shown below.

DBSCAN: definitions and algorithm

Ester, Kriegel, Sander and Xu (1996) formulated the idea with two parameters, radius ε\varepsilon and integer minPts\text{minPts}. Let P={x1,…,xn}P = \{x_1, \dots, x_n\} be the dataset with distance dd and let Nε(p)={q∈P:d(p,q)≤ε}N_\varepsilon(p) = \{q \in P : d(p, q) \le \varepsilon\} be pp‘s neighborhood, including pp.

(A core point is required because otherwise every isolated point would be a singleton cluster.) The definition is deliberately asymmetric. Reachability originates only at core points: a boundary point is reachable but cannot serve as a bridge, so a thin chain of points does not join two dense regions, the desired improvement over single linkage.

The algorithm is the breadth-first traversal suggested by the definition. Scan points; if one is unassigned and core, start a new cluster with it and enqueue its neighbors; pop from the queue, assign unassigned neighbors to the cluster, and only core points expand again. When the queue empties the cluster is complete. Each point is visited once and makes one neighborhood query, so cost is nn range queries plus linear work; query cost is the last section’s subject. Try it before reading on.

InteractiveCore, boundary and noise
Core (disk), border (ring), and noise (cross)
Sweep of ε\varepsilon with minPts=5\text{minPts} = 5: is there a window?
ε = 0.25
  • group points that are noise
  • mixing: second group within first group’s cluster
  • ε that separates both groups well
  • ball of radius ε
Data
0.25
5
Clusters2
Core / border / noise142 / 5 / 7
Group points labeled as noise0.0 %
Lower moon within the upper moon cluster0.0 %
With minPts=5\text{minPts} = 5 there is a window of ε\varepsilon that separates both groups well: from 0.21 to 0.35.
Two moons with uniform noise and a dataset with two groups of very different densities (one dense next to the edge of a diffuse one). Move ε\varepsilon and minPts\text{minPts}: disks are core points, rings boundary and crosses noise. Hover over a point to see its ball. Right: an ε\varepsilon sweep with current minPts\text{minPts}: red, fraction of true-group points declared noise; blue, fraction of the second group placed in the first group's cluster; aquamarine, ε\varepsilon values giving at most 15% noise, at most 5% mixing and two large clusters. Moons have a window for every minPts\text{minPts} from 2 to 15. Different densities have none for any minPts\text{minPts} from 2 to 15: ε\varepsilon values that stop declaring the diffuse group noise have already merged it with the dense one.

Keep what the two figures show. With ε\varepsilon too small, almost everything is noise and clusters fragment. With ε\varepsilon too large, everything is one cluster. For moons there is a middle interval producing what you expect. With different densities there is not. The cause is not the algorithm: ε\varepsilon performs two jobs, defining “dense” (how many neighbors in that ball) and “connected” (how far apart two points can join). A diffuse group needs large ε\varepsilon to be dense; an adjacent dense group becomes connected at that ε\varepsilon.

What exactly is a DBSCAN cluster?

One result captures why the definition is well formed: core points split into graph-connected components and boundary points hang from them.

Proof

Let pp be a core point and R(p)R(p) the set of density-reachable points from pp. A chain p=p1,…,pm=qp = p_1, \dots, p_m = q has all points except the last in KK, and each pi+1p_{i+1} is within ≤ε\le \varepsilon of pip_i. Thus p1,…,pm−1p_1, \dots, p_{m-1} form a path in GKG_K, and qq is in pp‘s component KpK_p if core, or a non-core point within ≤ε\le \varepsilon of KpK_p otherwise. Conversely every such point is reachable by a chain. Hence R(p)=Kp∪B(p)R(p) = K_p \cup B(p), where B(p)B(p) consists of non-core points within ≤ε\le \varepsilon of KpK_p.

R(p)R(p) is a cluster: maximal because if q∈R(p)q \in R(p) and rr is reachable from qq, then qq is core (if r≠qr \ne q) and the chain from qq to rr concatenates with that from pp to qq; and connected because all its points are reachable from pp.

Every cluster CC has this form. Take core p∈Cp \in C. By maximality, R(p)⊆CR(p) \subseteq C. For q∈Cq \in C, connectivity provides an oo from which pp and qq are reachable. If o≠po \ne p, oo is core and pp is core reachable from oo; since the relation between cores is symmetric (dd is symmetric and both are core), pp reaches oo, and by concatenation qq. Thus q∈R(p)q \in R(p) and C=R(p)C = R(p). This proves (a); (b) follows from R(p)=Kp∪B(p)R(p) = K_p \cup B(p) and the fact KpK_p depends only on GKG_K, itself determined only by data and (ε,minPts)(\varepsilon, \text{minPts}).

∎

Two consequences. First, practically, DBSCAN is deterministic except for boundary points, assigned to the first cluster reaching them in traversal order (exercise 3). Second, conceptually, and most important from here: DBSCAN cores with minPts=k\text{minPts} = k are exactly sample points whose core distance satisfies ck≤εc_k \le \varepsilon, meaning f^k≥λε\hat f_k \ge \lambda_\varepsilon, where

λε=kn Vd εd.\lambda_\varepsilon = \frac{k}{n\,V_d\,\varepsilon^d}.

Indeed, ∣Nε(p)∣≥k\abs{N_\varepsilon(p)} \ge k means at least kk points (counting pp) lie within ≤ε\le \varepsilon, meaning the kkth neighbor is within ≤ε\le \varepsilon. Together with the theorem this gives the desired interpretation: DBSCAN clusters without boundary points (the variant DBSCAN*, from Campello and colleagues) are connected components of the radius-ε\varepsilon graph on points in level set {f^k≥λε}\{\hat f_k \ge \lambda_\varepsilon\}. One level, and one ε\varepsilon serving simultaneously as connection scale and density level: λε∝ε−d\lambda_\varepsilon \propto \varepsilon^{-d}.

DBSCAN with minPts=2\text{minPts} = 2 is single linkage

The smallest parameter case matches what you already know.

Exercise 1 provides the proof step by step. The idea: with minPts=2\text{minPts} = 2, a point is core if and only if it has another point within ≤ε\le \varepsilon; a non-core point has no neighbor and therefore cannot lie in a core point’s neighborhood, so there are no boundary points. Raise minPts\text{minPts} and pay with noise: points lacking sufficient density stop connecting, and sparse bridges break.

Choosing ε\varepsilon and minPts\text{minPts}

Ester and colleagues proposed a graphical heuristic in the original paper. Fix minPts\text{minPts}, calculate each point’s kk-distance (distance to the kkth neighbor, counted without the point itself in the paper; here we count it, so our minPts\text{minPts} of kk corresponds to k−1k - 1 there), sort and plot them. Reasoning: points with small kk-distance are in dense regions, those with large kk-distance are noise, and the sharp change, or elbow, separates them. The elbow value is the ε\varepsilon at which nearly all cluster points are core and nearly all noise is not. The paper uses minPts=4\text{minPts} = 4 for planar data.

Behind this is the previous section’s identity: a point’s kk-distance is the smallest ε\varepsilon at which it is core. The sorted curve is therefore the distribution of points by the density level at which they enter the level set. When all clusters have the same density, group points have similar values and the elbow is clear. Otherwise, the curve has a step for each density.

InteractiveThe elbow of the k-distance plot
DBSCAN with ε=0.54\varepsilon = 0.54 and minPts=5\text{minPts} = 5
Plot of 55-distances, sorted ascending
ε = 0.54knee
  • 5-distance of each point
  • ε (drag)
  • knee (maximum distance from chord)
Data
5
0.54
Plot knee (suggested ε)0.54
Clusters / noise3 / 10 points
cloud 1: median 5-dist. · noise0.19 · 0 %
cloud 2: median 5-dist. · noise0.20 · 0 %
cloud 3: median 5-dist. · noise0.22 · 2 %
Uniform noise: median 5-dist.0.97
A point’s kk-distance is the smallest ε\varepsilon at which it would be core. A point with kk-distance above the line is noise or border.
The sorted kk-distance plot linked to DBSCAN output. Drag the horizontal line (or use the slider) and inspect clustering. With three equal clouds there is a clear elbow and the expected result. Switch to different densities and enable 'color by group': dense-group points form the low segment, diffuse points the middle and uniform noise the high segment. The curve then has different segments by group and no ε\varepsilon leaves both groups as clusters.

The plot does not solve the underlying problem, and knowing why matters. The elbow isolates noise from the rest, but clustering is asked something else: how many density levels exist. The plot shows the steps; DBSCAN can stand on only one.

Scale, metric and minPts\text{minPts}

ε\varepsilon has units. If one variable is in meters and another in millimeters, the ball is a sphere in a space that is not yours. Standardize (or choose an already meaningful metric, such as Gower’s from lesson 1 for mixed data) before seeking ε\varepsilon. For minPts\text{minPts}, a common starting value is order 2d2d with dd dimension, raised when noise is heavy or the sample large. Larger minPts\text{minPts} smooths density estimation (each point estimates it with more neighbors) and requires thicker clusters; a small value such as 2 turns DBSCAN back into single linkage.

OPTICS: one ordering summarizing every ε\varepsilon

If the problem is the value of ε\varepsilon, why not run DBSCAN with all values at once? Ankerst, Breunig, Kriegel and Sander (1999) achieved this with an ordering of points.

Since reachability of qq from pp is at least c(p)c(p), entering a dense region from outside costs high reachability (the jump) and, once inside, points are visited at low reachability, on the order of their core distance. A dense cluster is a valley; the denser, the deeper. Between valleys is a pass, whose height is the ε\varepsilon at which they merge. Watch the traversal.

InteractiveThe reachability plot
Points and the order OPTICS visits them
Reachability plot: one valley per cluster
ε′ = 0.30
  • cluster extracted at cut ε′ (color)
  • noise
  • cut ε′ (drag)
  • clipped bar: reachability above axis or infinite
5
0.30
144 of 144
Clusters at cut ε′\varepsilon'4
Noise31 points
Core points: same partition as DBSCAN(ε′\varepsilon', minPts)yes
Current point: reachability · core distance1.46 · 2.60
A deep narrow valley is a dense cluster; a wider higher one is diffuse. Each ε′ gives a different DBSCAN: at a low cut only the deepest valleys appear, then diffuse clusters emerge, and at a higher cut all merge.
Three clouds with very different densities (standard deviations 0.2, 0.5 and 0.3) and uniform noise. Slide 'visited points' to follow OPTICS order in the plane: an entire cloud is traversed before jumping to another, and each jump is a plot peak. Drag the ε′ line on the plot (or slider): bars below it form a cluster, and the green readout checks live that the cut agrees with DBSCAN run separately at that ε′ and the same minPts\text{minPts} on core points. A low cut reveals mostly the dense cloud; raising it reveals others; at a high cut everything merges.

The figure’s green readout is a result, not a coincidence.

Proof

Sketch. Let pp be a core point for ε′\varepsilon' (c(p)≤ε′c(p) \le \varepsilon') just visited. All its unvisited neighbors in Nε′(p)N_{\varepsilon'}(p) receive R≤max⁡{c(p),ε′}=ε′R \le \max\{c(p), \varepsilon'\} = \varepsilon'. While any unvisited point has R≤ε′R \le \varepsilon', the next visited is one of them, because the smallest RR is selected. Traversal therefore leaves a cluster only when no unvisited point is density-reachable (at radius ε′\varepsilon') from visited points, meaning its connected core component plus boundaries is complete. The next point has R>ε′R > \varepsilon' and, if core, starts a new cluster: it is core of another component. A point with R>ε′R > \varepsilon' that is not core cannot join anything already visited: noise in extraction (or a boundary of a cluster visited later, the only possible discrepancy).

∎

This provides what was requested: one computation, of the same cost order as DBSCAN (plus a priority queue), gives every DBSCAN with ε′≤εmax⁡\varepsilon' \le \varepsilon_{\max}. But the underlying problem remains. A horizontal cut is still one level. To extract clusters at different levels, the paper proposes the ξ\xi method, searching for sharp rises and falls (relative slope greater than ξ\xi) to delimit valleys; scikit-learn uses it with cluster_method="xi", and its result depends strongly on ξ\xi and min_cluster_size. OPTICS ordering is not a tree and has another detail: order depends on start and tie-breaking, and reachability is asymmetric (only the source point’s core distance counts). HDBSCAN reconstructs that information as a hierarchy with a symmetric distance and selects clusters by an explicit criterion.

HDBSCAN: the complete density hierarchy

HDBSCAN (Campello, Moulavi and Sander, 2013) does what the Hartigan section requested: build the sample’s cluster tree and select a flat clustering from it. It has four pieces: a new distance, its minimum spanning tree, the single-linkage hierarchy and a selection criterion.

Mutual reachability distance

This applies each point’s own scale: two sparse points, even if close in absolute value, remain at least as far apart as each needs to find kk neighbors. Two dense points retain their actual distance. This is the same single linkage from lesson 3, but a sparse-point bridge is no longer cheap. The figure shows the bridge example.

InteractiveMutual reachability slows chaining
Minimum spanning tree of mutual reachability (red: path between the clouds)
Merge heights versus kk
actual separation
  • joining the two clouds (via the bridge)
  • larger cloud becomes complete
  • minimum distance between clouds without bridge
  • bridge points
1
Height at which the two clouds join0.728
Height at which the larger cloud is complete0.566
Ratio (clouds join) / (cloud complete)1.29
Minimum distance between clouds, without bridge4.844
With k=1k = 1, c1=0c_1 = 0 and mutual reachability is ordinary distance: the eight-point bridge joins the clouds at a height far below their actual separation.
Two Gaussian clouds joined by eight points. With k=1k = 1 mutual reachability is ordinary distance and single linkage joins clouds far below their real separation (gray dashed line). Raise kk: circles of radius ckc_k grow more on the bridge (sparse magenta points) than within clouds, and the path joining clouds (red, on the minimum spanning tree) becomes more expensive. Right, merge height grows with kk, but so does the full cloud's height: their ratio matters.

With this distance the single-linkage hierarchy has an exact DBSCAN interpretation justifying the design.

Proof

If ck(a)>εc_k(a) > \varepsilon, every edge {a,b}\{a, b\} has dk(a,b)≥ck(a)>εd_k(a, b) \ge c_k(a) > \varepsilon, so aa is isolated. If ck(a),ck(b)≤εc_k(a), c_k(b) \le \varepsilon, then dk(a,b)≤εd_k(a, b) \le \varepsilon is equivalent to d(a,b)≤εd(a, b) \le \varepsilon. Thus the part of HεH_\varepsilon on points with ck≤εc_k \le \varepsilon (cores, by equivalence between being core and having ck≤εc_k \le \varepsilon in the previous section) is graph GKG_K of the structure theorem. The final claim is the single-linkage theorem applied to dkd_k: cuts of the single-linkage hierarchy are connected components of threshold graphs.

∎

Graph HεH_\varepsilon is also Chaudhuri and Dasgupta’s robust-single-linkage graph with α=1\alpha = 1 and radius r=εr = \varepsilon: vertices with ck≤εc_k \le \varepsilon and edges with d≤εd \le \varepsilon. HDBSCAN is that case.

In terms of the first figure’s tree, this is the gain. For fixed kk, dendrogram height ε\varepsilon for dkd_k corresponds to level λε∝ε−d\lambda_\varepsilon \propto \varepsilon^{-d} of the f^k\hat f_k level set. HDBSCAN uses not λε\lambda_\varepsilon but λ=1/ε\lambda = 1/\varepsilon, inverse height, which also increases with density. Since one is an increasing function of the other, the tree is the same: the same splits in the same order. But this choice is not innocuous. Stability in the next section is an area measured on the λ\lambda axis, and a nonlinear rescaling stretches some branches more than others, so the selection criterion can change its answer: 1/ε1/\varepsilon is Campello and colleagues’ convention, not the only possible one. The construction is already familiar: the minimum spanning tree of distance dkd_k (Prim, O(n2)\bigO(n^2) on the dense matrix without needing to store it) and a union-find hierarchy, the dendrogram.

The condensed tree

The single-linkage dendrogram has n−1n - 1 merges, almost all trivial: a lone point attaches to a cluster. HDBSCAN traverses it from root to leaves and keeps only significant splits, using parameter min_cluster_size =mc= m_c.

Think of a cluster branch as a ribbon whose width is the number of points remaining in it. As λ\lambda rises the ribbon narrows whenever a few points peel off for insufficient density, and ends when it splits into two wide ribbons or runs out of points. The figure at the section’s end draws this.

Stability and excess of mass

We still need to decide which condensed-tree clusters to retain. For each node CC, naturally measure how long it lives: how many points and for what λ\lambda interval.

Stability is an area. Let nC(λ)n_C(\lambda) be the number of points still in CC at level λ\lambda, the branch width. Each point contributes ∫λnacλpdλ=λp−λnac\int_{\lambda_{\text{nac}}}^{\lambda_p} d\lambda = \lambda_p - \lambda_{\text{nac}}, so S(C)=∫λnacλfinnC(λ) dλS(C) = \int_{\lambda_{\text{nac}}}^{\lambda_{\text{fin}}} n_C(\lambda)\,d\lambda, the branch area drawn with width proportional to nCn_C (the layer-cake integral trick with counting measure). In the continuous case with density ff and region CC, it is Müller and Sawitzki’s excess of mass, E(C)=∫C(f(x)−λnac(C)) dx=∫λnac∞vol(C∩{f≥λ}) dλE(C) = \int_C (f(x) - \lambda_{\text{nac}}(C))\,dx = \int_{\lambda_{\text{nac}}}^{\infty} \text{vol}\bigl(C \cap \{f \ge \lambda\}\bigr)\,d\lambda. This names the criterion. The correspondence is exact when the vertical axis is density level; with λ=1/ε\lambda = 1/\varepsilon, stability is the sample analogue on that scale, hence the previous paragraph’s warning.

Proof

Induct on subtree height. At a leaf, the only nonempty admissible set is {C}\{C\}, worth S(C)S(C). At an internal node, an admissible subtree set is either {C}\{C\} or a union of admissible sets from child subtrees, which do not interfere. The best value in the second case is the sum of the children’s best values, ∑B(C′)\sum B(C') by induction; the first is worth S(C)S(C). Take the maximum, computed by the traversal.

∎

The root is excluded for a specific reason: it is born with λnac=0\lambda_{\text{nac}} = 0 and contains all points, and if selectable, “everything is one cluster” would be admissible for every dataset. Scikit-learn excludes it by default and permits it with allow_single_cluster=True. The alternative cluster_selection_method="leaf" selects every condensed-tree leaf: the finest partition, highly sensitive to min_cluster_size.

InteractiveCondensed tree and stability
Selected clusters (color), noise (cross) and highlighted branch
Condensed tree: height λ=1/d\lambda = 1/d, width = points present
012345678
Stability S(C)S(C) of each node (filled bar) versus the sum of its best children (line)
Rama 0 · 185 ptsS = 149.1 · hijos 492.4 · la raíz no se eligeRama 1 · 132 ptsS = 55.6 · hijos 210.6 · ganan los hijosRama 2 · 72 ptsS = 90.5 · hijos 173.4 · ganan los hijosRama 3 · 34 ptsS = 70.1 · hojaRama 4 · 31 ptsS = 103.3 · hojaRama 5 · 51 ptsS = 37.2 · hijos 31.9 · gana el padreRama 6 · 28 ptsS = 31.2 · hojaRama 7 · 12 ptsS = 0.7 · hojaRama 8 · 48 ptsS = 281.8 · hoja
  • selected branch (color = cluster)
  • discarded branch
  • sum of best children
10
5
Selection
Selected clusters4
Noise21 points
Condensed tree nodes9
With leaves5 clusters
Stability S(C)S(C) is the branch area. A node remains with its parent only if its area exceeds that of its descendants combined.
HDBSCAN step by step on 185 points (a dense group, a group with two touching subgroups, a diffuse one and 20 noise points). Right: the condensed tree, height λ=1/d\lambda = 1/d and width proportional to points present, so each branch's area is its stability. Below, each node's stability versus the sum of its children's best. At initial values, excess of mass chooses four clusters and leaves five. Raise min_cluster_size to 30: EOM merges the two touching subgroups into one cluster, while leaves still give four. Lower to 5: both criteria gain a cluster, but leaves leave 54 points as noise and EOM 32. Return to min_cluster_size = 10 and move min_samples, smoothing density instead of fixing minimum size: at 1 a fifth cluster of 18 points appears, and at 15 the two subgroups merge again into one of 72 without changing minimum size.

What happens with min_cluster_size = 30 deserves explanation: the criterion does not stop seeing the two subgroups. With min_samples = 5, the two-subgroup group is branch 2 in the figure (72 points), splitting at λ=2.55\lambda = 2.55 into branches of 34 and 31 points at both min_cluster_size values. With mc=10m_c = 10, those branches live until λ=5.46\lambda = 5.46 and λ=7.59\lambda = 7.59, their stabilities sum to 70.1+103.3=173.470.1 + 103.3 = 173.4 and beat the parent’s 90.590.5. With mc=30m_c = 30, the 31-point branch dies at λ=2.64\lambda = 2.64, almost immediately: once it loses two points, every later split leaves two pieces below 30, and by the condensed-tree definition all its points leave at once. Its stability falls to 2.62.6, its sister’s to 33.833.8, their sum (36.436.4) no longer reaches 90.590.5 and the parent wins. A cluster near mcm_c in size has a short branch by construction, so min_cluster_size does more than decide which splits count: it also penalizes clusters barely above it.

min_samples and min_cluster_size are not the same

The original paper uses one parameter for two roles; implementations separate them, and confusing them is HDBSCAN’s most common mistake. min_samples is kk in core distance ckc_k: it smooths density estimation and decides which points are noise (a point with large ckc_k lies at low scale and falls out early). min_cluster_size is mcm_c in the condensed tree: it decides which splits count as clusters. In scikit-learn, min_samples defaults to min_cluster_size, which defaults to 5. Usually set min_cluster_size to the smallest cluster of interest and lower min_samples if there is too much noise.

Lab: from scratch and with libraries

Everything runs in the browser. First DBSCAN from scratch, with a KD-tree for neighborhoods and breadth-first expansion from the definition.

[ ]DBSCAN from scratch, validated against scikit-learnBrowser
import numpy as np
from collections import deque
from scipy.spatial import cKDTree
from sklearn.cluster import DBSCAN
from sklearn.datasets import make_moons
from sklearn.metrics import adjusted_rand_score

def dbscan(X, eps, min_samples):
    """DBSCAN por expansión. Devuelve etiquetas (-1 = ruido) y la máscara de puntos núcleo."""
    n = len(X)
    vecinos = cKDTree(X).query_ball_point(X, r=eps)     # N_eps(p) = {q : d(p, q) <= eps}, incluye a p
    es_nucleo = np.array([len(v) >= min_samples for v in vecinos])
    etiquetas = np.full(n, -1)
    c = 0
    for i in range(n):
        if etiquetas[i] != -1 or not es_nucleo[i]:
            continue                                     # ya asignado, o no puede iniciar un cluster
        etiquetas[i] = c
        cola = deque([i])
        while cola:
            p = cola.popleft()                           # p es núcleo: todos sus vecinos son alcanzables
            for q in vecinos[p]:
                if etiquetas[q] == -1:
                    etiquetas[q] = c
                    if es_nucleo[q]:
                        cola.append(q)                   # solo los núcleos siguen expandiendo
        c += 1
    return etiquetas, es_nucleo

rng = np.random.default_rng(0)
X, y_lunas = make_moons(n_samples=400, noise=0.06, random_state=0)
X = np.vstack([X, rng.uniform([-1.5, -1.0], [2.5, 1.5], size=(20, 2))])      # 20 puntos de ruido uniforme
verdad_lunas = np.concatenate([y_lunas, -np.ones(20, dtype=int)])
eps, m = 0.15, 5

etq, nucleo = dbscan(X, eps, m)
ref = DBSCAN(eps=eps, min_samples=m).fit(X)
print("n =", len(X), "| clusters:", etq.max() + 1, "| núcleo:", int(nucleo.sum()), "| frontera:", int(((etq >= 0) & ~nucleo).sum()), "| ruido:", int((etq == -1).sum()))
print("scikit-learn: clusters", ref.labels_.max() + 1, "| ruido", int((ref.labels_ == -1).sum()))
print("ARI en los puntos núcleo:", adjusted_rand_score(etq[nucleo], ref.labels_[nucleo]))
print("mismo conjunto de ruido:", np.array_equal(etq == -1, ref.labels_ == -1))
print("etiquetas idénticas también en la frontera:", np.array_equal(etq, ref.labels_))

It matches scikit-learn on cores and noise (the two things the structure theorem says are order-independent). Here it also agrees on boundaries because no boundary point touches two clusters. To see ambiguity we must construct it: a non-core point at distance 0.90.9 from a core in each of two groups.

[ ]A boundary point with two ownersBrowser
# El 1.8 está a 0.9 de un núcleo de cada grupo y no es núcleo (su vecindario tiene solo 3 puntos)
Xb = np.array([[0.0], [0.3], [0.6], [0.9], [1.8], [2.7], [3.0], [3.3], [3.6]])
for nombre, orden in [("orden original", np.arange(9)), ("orden inverso", np.arange(9)[::-1])]:
    e, nu = dbscan(Xb[orden], eps=1.0, min_samples=4)
    inv = np.argsort(orden)                                  # de vuelta al orden original
    print(f"{nombre:15s} etiquetas: {e[inv]}   núcleo: {nu[inv].astype(int)}")

Core points have the same labels in both traversals (up to cluster naming, determined by which is numbered first), and the middle point joins the group visited first. Now cost. Neighborhoods are expensive: a distance matrix costs O(n2)\bigO(n^2) time and memory; a spatial index such as the KD-tree grows much more slowly in low dimension.

[ ]Neighborhoods: KD-tree versus distance matrixBrowser
import time
from scipy.spatial.distance import cdist

def vecinos_arbol(P, eps):
    return cKDTree(P).query_ball_point(P, r=eps)

def vecinos_matriz(P, eps):
    D = cdist(P, P)
    return [np.flatnonzero(f <= eps) for f in D]

def mejor_tiempo(f, *args, rep=3):
    ts = []
    for _ in range(rep):
        t0 = time.perf_counter(); f(*args); ts.append(time.perf_counter() - t0)
    return min(ts)

res = {}
for n in (1000, 2000, 4000):
    P = np.random.default_rng(1).uniform(0, 1, size=(n, 2))
    eps = np.sqrt(10 / (np.pi * n))                          # unos 10 vecinos por bola en cualquier n
    res[n] = (mejor_tiempo(vecinos_arbol, P, eps), mejor_tiempo(vecinos_matriz, P, eps))
    print(f"n = {n:5d}   con KD-tree: {1e3 * res[n][0]:7.1f} ms   con matriz de distancias: {1e3 * res[n][1]:7.1f} ms   (la matriz ocupa {8 * n * n / 2**20:5.1f} MB)")
print(f"de n = 1000 a n = 4000 (x4): el tiempo se multiplica por {res[4000][0] / res[1000][0]:.1f} con KD-tree y por {res[4000][1] / res[1000][1]:.1f} con la matriz (lineal sería x4; cuadrático, x16)")

Exact times depend on machine and vary between runs; the trend persists. With KD-tree, multiplying nn by 4 multiplies time by 4 or less (at n=1000n = 1000 fixed call cost still matters). With the matrix, the factor is clearly above 4 and approaches quadratic 16 as nn grows, because at these sizes the row loop, linear, still matters. Memory is unambiguous: the matrix occupies 8n28n^2 bytes, 122 MB at n=4000n = 4000, and at n=105n = 10^5 would be 8⋅10108 \cdot 10^{10} bytes, about 75 GB. Now the underlying problem’s data: two nearby dense groups and a diffuse one, with noise. Sweep the (minPts,ε)(\text{minPts}, \varepsilon) grid and count pairs recovering all three groups.

[ ]Different densities: the DBSCAN window and HDBSCANBrowser
from sklearn.cluster import HDBSCAN

def densidades(seed):
    """Dos grupos densos (sigma 0.15) a 0.9 de distancia y uno difuso (sigma 0.8), más 20 puntos de ruido uniforme."""
    g = np.random.default_rng(seed)
    A1 = g.normal([-1.2, 0.0], 0.15, size=(50, 2))
    A2 = g.normal([-0.3, 0.0], 0.15, size=(50, 2))
    B = g.normal([2.8, 0.3], 0.8, size=(80, 2))
    R = g.uniform([-3.0, -2.5], [5.0, 2.5], size=(20, 2))
    return np.vstack([A1, A2, B, R]), np.repeat([0, 1, 2, -1], [50, 50, 80, 20])

def separa_los_tres(e, verdad):
    """¿Recupera los tres grupos? Cada uno tiene al menos el 80 % de sus puntos en un mismo cluster y los tres clusters son distintos."""
    dueños = []
    for g in (0, 1, 2):
        mis = e[verdad == g]
        if (mis >= 0).sum() == 0:
            return False
        c = np.bincount(mis[mis >= 0]).argmax()
        if (mis == c).mean() < 0.8:
            return False
        dueños.append(c)
    return len(set(dueños)) == 3

Y, verdad = densidades(7)
buenos = []
for m in (2, 3, 4, 5, 6, 8, 10, 12, 15):
    for eps in np.arange(0.05, 1.3, 0.02):
        if separa_los_tres(DBSCAN(eps=eps, min_samples=m).fit_predict(Y), verdad):
            buenos.append((m, round(float(eps), 2)))
print(f"pares (minPts, eps) de la rejilla (9 x 63 = 567) que recuperan los tres grupos con DBSCAN: {len(buenos)}")
for m in sorted({b[0] for b in buenos}):
    es = [b[1] for b in buenos if b[0] == m]
    print(f"   minPts = {m:2d}: eps de {min(es):.2f} a {max(es):.2f}")

print("minPts = 8: eps, clusters, ruido, fracción del grupo difuso que es ruido, ¿los dos densos separados?")
for eps in (0.2, 0.35, 0.5, 0.8):
    e = DBSCAN(eps=eps, min_samples=8).fit_predict(Y)
    sep = len(set(np.bincount(e[verdad == g][e[verdad == g] >= 0]).argmax() if (e[verdad == g] >= 0).any() else -9 for g in (0, 1))) == 2
    print(f"  {eps:.2f}   {e.max() + 1}   {int((e == -1).sum()):3d}   {(e[verdad == 2] == -1).mean():.2f}   {sep}")

for mcs in (10, 20):
    h = HDBSCAN(min_cluster_size=mcs, copy=True).fit(Y)
    print(f"HDBSCAN con min_cluster_size = {mcs}: recupera los tres grupos: {separa_los_tres(h.labels_, verdad)}, clusters = {h.labels_.max() + 1}, ruido = {(h.labels_ == -1).sum()}")

The minPts=8\text{minPts} = 8 table tells the lesson’s story. At ε=0.20\varepsilon = 0.20 there are three clusters, but 90% of the diffuse group is noise. At ε=0.35\varepsilon = 0.35 there are still three clusters and 64% of the diffuse group remains noise. At 0.500.50 the diffuse group exists (only 24% of its points are noise) but the two dense groups are one. Of 567 grid pairs only two recover all three groups, both with the same ε\varepsilon and minPts\text{minPts} of 2 or 3, nearly single linkage. HDBSCAN needs no ε\varepsilon and recovers them with two very different min_cluster_size values.

Now OPTICS, also from scratch and on the same data.

[ ]OPTICS from scratch and its equivalence to DBSCANBrowser
from scipy.spatial.distance import pdist, squareform
from scipy.sparse.csgraph import minimum_spanning_tree
from sklearn.cluster import OPTICS, cluster_optics_dbscan

def optics(X, min_samples):
    """OPTICS con eps_max = infinito: cada paso visita el punto no visitado de menor alcanzabilidad."""
    D = squareform(pdist(X))
    n = len(X)
    nucleo = np.sort(D, axis=1)[:, min_samples - 1]          # distancia al min_samples-ésimo vecino, contando el propio punto
    alcanz = np.full(n, np.inf)
    visitado = np.zeros(n, dtype=bool)
    orden, r_orden = [], []
    for _ in range(n):
        p = int(np.argmin(np.where(visitado, np.inf, alcanz)))
        visitado[p] = True
        orden.append(p)
        r_orden.append(alcanz[p])
        nueva = np.maximum(nucleo[p], D[p])                  # alcanzabilidad de cada punto desde p
        alcanz = np.where(visitado, alcanz, np.minimum(alcanz, nueva))
    return np.array(orden), np.array(r_orden), nucleo

k = 5
orden, r, nucleo = optics(Y, k)
ref = OPTICS(min_samples=k).fit(Y)
print("mismo orden que scikit-learn:", np.array_equal(orden, ref.ordering_))
print("misma alcanzabilidad (máx. diferencia):", np.max(np.abs(r[1:] - ref.reachability_[ref.ordering_][1:])))

# Cortar el gráfico con eps' reproduce DBSCAN(eps', k) en los puntos núcleo
for eps2 in (0.2, 0.39, 0.6):
    e_opt = cluster_optics_dbscan(reachability=ref.reachability_, core_distances=ref.core_distances_, ordering=ref.ordering_, eps=eps2)
    e_db, es_nucleo = dbscan(Y, eps2, k)
    print(f"eps' = {eps2}: ARI entre el corte y DBSCAN en los núcleos = {adjusted_rand_score(e_opt[es_nucleo], e_db[es_nucleo]):.3f}   (núcleos: {int(es_nucleo.sum())} de {len(Y)})")

The ordering and reachabilities match scikit-learn, and each cut matches DBSCAN on cores, as the proposition states. Now HDBSCAN step by step: the previous section’s six pieces, each in a few lines, and the result versus sklearn.cluster.HDBSCAN.

[ ]HDBSCAN step by stepBrowser
def hdbscan_desde_cero(X, min_samples=5, min_cluster_size=5, seleccion="eom"):
    n = len(X)
    D = squareform(pdist(X))
    # 1) distancia núcleo (el propio punto cuenta como el primer vecino) y alcanzabilidad mutua
    nucleo = np.sort(D, axis=1)[:, min_samples - 1]
    W = np.maximum(D, np.maximum(nucleo[:, None], nucleo[None, :]))
    np.fill_diagonal(W, 0)
    # 2) árbol de expansión mínimo (Prim, O(n^2)); a igual peso se conserva el orden de inserción
    en_arbol = np.zeros(n, dtype=bool); mejor = np.full(n, np.inf); origen = np.zeros(n, dtype=int)
    actual, aristas = 0, []
    en_arbol[0] = True
    for _ in range(n - 1):
        mejora = ~en_arbol & (W[actual] < mejor)
        mejor[mejora] = W[actual][mejora]; origen[mejora] = actual
        nuevo = int(np.argmin(np.where(en_arbol, np.inf, mejor)))
        aristas.append((mejor[nuevo], origen[nuevo], nuevo)); en_arbol[nuevo] = True; actual = nuevo
    aristas.sort(key=lambda e: e[0])
    # 3) jerarquía de enlace simple con union-find: la fusión s crea el nodo n + s
    padre = list(range(2 * n - 1)); tam = [1] * n + [0] * (n - 1)
    def raiz(x):
        while padre[x] != x:
            padre[x] = padre[padre[x]]; x = padre[x]
        return x
    hijos, altura = {}, {}
    for s, (w, u, v) in enumerate(aristas):
        a, b = raiz(u), raiz(v)
        padre[a] = padre[b] = n + s
        hijos[n + s], altura[n + s], tam[n + s] = (a, b), w, tam[a] + tam[b]
    def hojas(x):
        pila, out = [x], []
        while pila:
            y = pila.pop()
            if y < n: out.append(y)
            else: pila.extend(hijos[y])
        return out
    # 4) condensación: un nodo se divide solo si los dos trozos tienen al menos min_cluster_size puntos
    nodos = [dict(nace=0.0, cae=[], parte=0, fin=0.0, hijos=[])]
    def recorre(x, c):
        a, b = hijos[x]; lam = 1.0 / altura[x]
        if tam[a] >= min_cluster_size and tam[b] >= min_cluster_size:
            nodos[c]["fin"], nodos[c]["parte"] = lam, tam[x]
            for y in (a, b):
                nodos.append(dict(nace=lam, cae=[], parte=0, fin=lam, hijos=[]))
                nodos[c]["hijos"].append(len(nodos) - 1)
                recorre(y, len(nodos) - 1)
        elif tam[a] < min_cluster_size and tam[b] < min_cluster_size:
            nodos[c]["fin"] = lam; nodos[c]["cae"].append((lam, hojas(a) + hojas(b)))
        else:
            chico, grande = (a, b) if tam[a] < min_cluster_size else (b, a)
            nodos[c]["cae"].append((lam, hojas(chico))); recorre(grande, c)
    recorre(2 * n - 2, 0)
    # 5) estabilidad S(C) = suma sobre los puntos de C de (lambda de salida - lambda de nacimiento)
    for nd in nodos:
        nd["S"] = sum(len(p) * (lam - nd["nace"]) for lam, p in nd["cae"]) + nd["parte"] * (nd["fin"] - nd["nace"])
    # 6) selección de abajo arriba (un hijo siempre tiene índice mayor que su padre)
    m = len(nodos); mejor_sub = [0.0] * m; se_queda = [False] * m
    for i in range(m - 1, -1, -1):
        suma = sum(mejor_sub[k] for k in nodos[i]["hijos"])
        if seleccion == "hojas":
            se_queda[i] = not nodos[i]["hijos"] and i != 0
            mejor_sub[i] = nodos[i]["S"] if not nodos[i]["hijos"] else suma
        elif not nodos[i]["hijos"]:
            se_queda[i] = i != 0
            mejor_sub[i] = nodos[i]["S"] if se_queda[i] else 0.0
        elif i != 0 and nodos[i]["S"] >= suma:
            se_queda[i] = True; mejor_sub[i] = nodos[i]["S"]
        else:
            mejor_sub[i] = suma                       # la raíz no se elige nunca
    elegidos = []
    def baja(i, cubierto):
        if se_queda[i] and not cubierto:
            elegidos.append(i); cubierto = True
        for k in nodos[i]["hijos"]: baja(k, cubierto)
    baja(0, False)
    def puntos(i):
        out = [p for _, ps in nodos[i]["cae"] for p in ps]
        for k in nodos[i]["hijos"]: out += puntos(k)
        return out
    etiquetas = np.full(n, -1)
    for e, i in enumerate(elegidos):
        etiquetas[puntos(i)] = e
    return etiquetas, nodos, elegidos, np.array([a[0] for a in aristas])

etq_h, nodos, elegidos, pesos = hdbscan_desde_cero(Y, min_samples=5, min_cluster_size=20)
print("nodo  padre  puntos  lambda_nace -> lambda_fin     S(C)   elegido")
for i, nd in enumerate(nodos):
    padre_i = next((j for j, o in enumerate(nodos) if i in o["hijos"]), -1)
    tam_i = nd["parte"] + sum(len(p) for _, p in nd["cae"])
    print(f"{i:3d}  {padre_i:5d}  {tam_i:6d}  {nd['nace']:10.2f} -> {nd['fin']:6.2f}   {nd['S']:7.2f}   {'sí' if i in elegidos else ''}")

ref_h = HDBSCAN(min_cluster_size=20, min_samples=5, copy=True).fit(Y)
print("ARI frente a scikit-learn:", round(adjusted_rand_score(etq_h, ref_h.labels_), 4), "| clusters:", etq_h.max() + 1, "(propio),", ref_h.labels_.max() + 1, "(scikit-learn) | ruido:", int((etq_h == -1).sum()), "y", int((ref_h.labels_ == -1).sum()))
print("aristas del MST con peso repetido (empates):", len(pesos) - len(np.unique(pesos)), "de", len(pesos))

The table writes this dataset’s condensed tree as rows, just as the figure draws its own: the root splits into a diffuse node (4) and a node with both dense groups (1); that in turn splits into the two dense groups (2 and 3). Node 1’s stability (both dense groups together) is far below the sum of its children’s, so EOM separates them; the root does not compete. The last line explains why exact agreement with scikit-learn cannot generally be demanded: mutual reachability has ties by construction (all points joining a large-core-distance point at the same weight ckc_k), and tie-breaking order can change tree shape and which pieces reach min_cluster_size. Here agreement is complete.

Next examine mutual reachability’s effect on the bridge, using the same construction as the hierarchical clustering lesson (another sample, so values differ from the figure).

[ ]The bridge and mutual reachabilityBrowser
from scipy.cluster.hierarchy import linkage, cophenet
from scipy.spatial.distance import cdist, pdist, squareform

g = np.random.default_rng(0)
izq = g.normal([-3.3, 0.0], 0.42, size=(18, 2))
der = g.normal([3.3, 0.3], 0.42, size=(18, 2))
t = np.arange(8)
puente = np.column_stack([-2.3 + 0.657 * t + 0.05 * g.normal(size=8), 0.05 + 0.05 * t + 0.08 * g.normal(size=8)])
P = np.vstack([izq, der, puente])
D = squareform(pdist(P))
print("menor distancia entre las dos nubes, sin el puente:", round(float(cdist(izq, der).min()), 2))
print("   k   unión de las nubes   mayor nube completa   cociente")
for k in (1, 3, 5, 8, 10):
    nuc = np.sort(D, axis=1)[:, k - 1]
    W = np.maximum(D, np.maximum(nuc[:, None], nuc[None, :]))
    np.fill_diagonal(W, 0)
    C = squareform(cophenet(linkage(squareform(W, checks=False), "single")))
    union = C[:18, 18:36].min()                         # primera altura a la que algún punto de una nube se conecta con la otra
    completa = max(C[:18, :18].max(), C[18:36, 18:36].max())
    print(f"{k:4d}   {union:17.2f}   {completa:19.2f}   {union / completa:8.2f}")

With k=1k = 1 this is single linkage: clouds join at 0.780.78, one seventh of actual separation 5.515.51. With k=8k = 8 they join at 2.032.03 and with k=10k = 10 at 2.252.25. Mutual reachability does not eliminate chaining; it makes it more expensive. Inside clouds core distance also rises (the third column goes from 0.560.56 to 1.231.23), so look at the ratio: with k=1k = 1 the join is 1.391.39 times the height at which a cloud completes, and with k=8k = 8 it is 1.981.98, a clear dendrogram gap. It does not rise monotonically. With k=3k = 3 it falls to 1.251.25: each bridge point still has its two chain neighbors within 0.780.78, so its c3c_3 stays at most 0.780.78 and the join does not move, while the cloud completes higher. With k=10k = 10 it is 1.831.83: with 18 points per cloud, c10c_{10} forces each cloud point to cover more than half the cloud and full-cloud height grows nearly as much as bridge height. Thus kk is not raised without limit: it must be small relative to cluster sizes.

And comparison with the standard implementation, including the difference between the two selection criteria.

[ ]With libraries: DBSCAN, HDBSCAN and both selection criteriaBrowser
import warnings
warnings.filterwarnings("ignore")

def resumen(nombre, modelo, Z, verdad):
    e = modelo.fit_predict(Z)
    print(f"{nombre:42s} ARI = {adjusted_rand_score(verdad, e):.3f}   clusters = {e.max() + 1:2d}   ruido = {(e == -1).sum():3d}")
    return e

print("Dos lunas con ruido uniforme (420 puntos)")
resumen("DBSCAN(eps=0.15, min_samples=5)", DBSCAN(eps=0.15, min_samples=5), X, verdad_lunas)
resumen("HDBSCAN(min_cluster_size=15)", HDBSCAN(min_cluster_size=15, copy=True), X, verdad_lunas)
print("Dos densos cercanos y uno difuso (200 puntos)")
resumen("DBSCAN(eps=0.35, min_samples=5)", DBSCAN(eps=0.35, min_samples=5), Y, verdad)
resumen("HDBSCAN(min_cluster_size=15)", HDBSCAN(min_cluster_size=15, copy=True), Y, verdad)

print("Los dos criterios de selección de HDBSCAN sobre las lunas, al bajar min_cluster_size")
for mcs in (30, 10, 5):
    for sel in ("eom", "leaf"):
        e = HDBSCAN(min_cluster_size=mcs, cluster_selection_method=sel, copy=True).fit_predict(X)
        print(f"  min_cluster_size = {mcs:2d}  {sel:4s}  clusters = {e.max() + 1:2d}   ruido = {(e == -1).sum():3d}   ARI = {adjusted_rand_score(verdad_lunas, e):.3f}")

On moons, which have one density, DBSCAN with a good ε\varepsilon and HDBSCAN perform similarly (ARI 0.9700.970 and 0.9610.961). On different-density data, DBSCAN with ε=0.35\varepsilon = 0.35 produces six clusters and ARI 0.6780.678, HDBSCAN three and 0.8440.844. The lower part is the warning: with leaf, lowering min_cluster_size to 10 and 5 fragments moons into 11 and 29 pieces (with 213 and 154 noise points), whereas excess of mass keeps two. Leaves are sensitive to everything; EOM much less so.

Complexity, spatial indices and high dimension

DBSCAN costs nn range queries. With a spatial index (KD-tree or ball tree, from the nearest-neighbor lesson), each query costs order log⁡n\log n plus result size in low dimension, and O(nlog⁡n)\bigO(n \log n) total in practice. But the original paper claimed O(nlog⁡n)\bigO(n \log n) generally, and Gan and Tao (SIGMOD 2015) showed that claim was wrong: the algorithm is O(n2)\bigO(n^2) in the worst case, and in dimension d≥3d \ge 3 solving DBSCAN exactly requires Ω(n4/3)\Omega(n^{4/3}) unless open computational-geometry problems are solved (Gunawan’s algorithm does achieve O(nlog⁡n)\bigO(n \log n) in the plane). Schubert and colleagues (2017) respond that criticism should address assumptions about spatial-index performance (such as R-trees), not DBSCAN, and that with efficient indices and reasonable parameters original DBSCAN is competitive: in their experiments Gan and Tao’s approximate methods offer no practical advantage with well-chosen parameters. No matrix need be stored: memory is linear in nn plus neighborhoods.

HDBSCAN has two expensive steps: core distances (a kk-neighbor search per point, which is indexed) and the minimum spanning tree of dkd_k. With a dense matrix, Prim takes O(n2)\bigO(n^2) time; McInnes and Healy (2017) propose a dual-tree Borůvka algorithm accelerating it in low dimension. Condensation and selection are linear in node count.

High dimension

All this uses distances, and in high dimension distances concentrate (lesson 1). To see the effect on density clustering, consider two Gaussian clouds with the same identity covariance six standard deviations apart in increasing dimension. One threshold on the first coordinate separates them with Bayes error Φ(−3)≈0.13 %\Phi(-3) \approx 0.13\,\% in any dimension. DBSCAN needs ε\varepsilon greater than the 5-distance of almost all points (so they are core) and less than the height at which the two groups merge.

[ ]The eps window closes as dimension risesBrowser
import numpy as np
from scipy.cluster.hierarchy import linkage
from scipy.spatial.distance import pdist, squareform
from scipy.stats import norm

print("error de Bayes con las nubes a 6 desviaciones típicas:", round(float(norm.cdf(-3)), 5))
print("  d   c_5 mediana   c_5: desv./media   eps mínimo (95 % núcleos)   eps de unión de los grupos   cociente")
for d in (2, 10, 50, 200, 1000):
    g = np.random.default_rng(0)
    centro2 = np.zeros(d); centro2[0] = 6.0                  # dos nubes N(0, I) con los centros a 6 desviaciones típicas
    Z = np.vstack([g.normal(0, 1, size=(150, d)), g.normal(0, 1, size=(150, d)) + centro2])
    D = squareform(pdist(Z))
    c5 = np.sort(D, axis=1)[:, 4]                            # 5-distancia contando el propio punto
    eps_min = np.quantile(c5, 0.95)
    eps_union = linkage(squareform(D, checks=False), "single")[-1, 2]
    print(f"{d:4d}   {np.median(c5):10.2f}   {c5.std() / c5.mean():16.3f}   {eps_min:24.2f}   {eps_union:25.2f}   {eps_union / eps_min:8.2f}")

The ratio is relative window width: in d=2d = 2 the group merges at an ε\varepsilon more than twice what is needed for cores, and from d=10d = 10 the ratio is between 0.990.99 and 1.021.02: the window does not exist or spans 2% of ε\varepsilon. The reason is visible in column three: relative dispersion of kk-distance falls from 0.620.62 to 0.0110.011, all points become core at once, and distance to the other group cannot be distinguished from within-group distance. The data remain highly separable (for a linear classifier), but not by distances. In practice first reduce dimension (PCA, UMAP) and apply HDBSCAN to the embedding, knowing that the result consists of clusters in the embedding.

Common mistakes

Exercises

ProofDBSCAN with minPts = 2 is single linkage
Prove: With minPts=2\text{minPts} = 2, DBSCAN(ε,2)(\varepsilon, 2) clusters are connected components with at least two points of graph GεG_\varepsilon (edges dij≤εd_{ij} \le \varepsilon), singleton-component points are noise, and there are no boundary points. Therefore these are the clusters of the single-linkage hierarchy cut at height ε\varepsilon, excluding singletons.
0
Use this lesson's DBSCAN definition (with neighborhood Nε(p)N_\varepsilon(p) including pp) and the previous lesson's single-linkage theorem: single-linkage clusters immediately after the last merge at height ≤ε\le \varepsilon are connected components of GεG_\varepsilon.

Step 1 of 4. Which points are core with minPts=2\text{minPts} = 2?

NumericMutual reachability of two points
Two points aa and bb have core distances ck(a)=0.5c_k(a) = 0.5 and ck(b)=1.2c_k(b) = 1.2 and distance d(a,b)=0.8d(a, b) = 0.8. What is their mutual reachability distance dk(a,b)d_k(a, b)?
QuizWhy a boundary point can change clusters
In DBSCAN, why can a boundary point's assignment depend on point-processing order?
NumericStability of a condensed-tree node
A condensed-tree cluster is born at λ=2\lambda = 2 with 10 points. Three points leave at λ=4\lambda = 4 and two at λ=5\lambda = 5; the remaining five stay until the cluster splits into two large clusters at λ=8\lambda = 8. What is its stability S(C)S(C)?
NumericFrom eps to density level
You have n=1000n = 1000 points in the plane (d=2d = 2) and run DBSCAN with minPts=10\text{minPts} = 10 and ε=0.1\varepsilon = 0.1. With the kk-neighbor estimator f^k=k/(nVdrkd)\hat f_k = k/(n V_d r_k^d), what density level λε\lambda_\varepsilon corresponds to that radius? Give three decimal places.
CodeImplement DBSCAN
Implement dbscan(X, eps, min_samples), taking X (an array of shape (n, d)) and returning an integer label array of length n, with -1 for noise and 0, 1, ... for clusters. A point is core if its radius-eps neighborhood (with d <= eps, including the point itself) has at least min_samples points. Traverse points in order and expand each cluster breadth-first from cores. Tests compare with scikit-learn on core points and noise.
import numpy as np
from scipy.spatial import cKDTree

def dbscan(X, eps, min_samples):
  """Devuelve las etiquetas de DBSCAN (-1 = ruido)."""
  X = np.asarray(X, dtype=float)
  n = len(X)
  etiquetas = np.full(n, -1)
  # tu código: vecindarios con cKDTree, núcleos y expansión en anchura
  return etiquetas
Shift+Enter to run
QuizDBSCAN, HDBSCAN or Gaussian mixture
Which method best fits each scenario? (A) Order maps with very dense urban and much sparser rural regions, and a desire to separate nearby urban zones. (B) Two customer groups overlapping in their tails with elliptical shapes, where membership probabilities are wanted. (C) Sensor traces with a continuous band of points and pockets of isolated noise, at a single density.
NumericWhat excess of mass selects
In a condensed tree, node PP has S(P)=10S(P) = 10 and two children. Child AA is a leaf with S(A)=6S(A) = 6. Child BB has S(B)=3S(B) = 3 and splits into two leaves with stabilities 22 and 2.52.5. Under excess-of-mass selection (assuming PP is not the root), what is the sum of stabilities of selected clusters inside PP's subtree?
QuizWhat each HDBSCAN parameter changes
You obtain 40 small clusters and much noise with default HDBSCAN parameters on 50,000 points. You want fewer clusters of at least 200 points each. What do you change first?
QuizDBSCAN in 300 dimensions
You have 300-dimensional embeddings and the 5-distance plot is nearly horizontal: every point has 5-distance between 0.980.98 and 1.021.02 times the median. Trying several ε\varepsilon values yields one cluster or all noise. What is the best explanation and response?

Summary

Key idea
A cluster is a connected component of a density level set, and clusters at all levels form a tree. DBSCAN takes one level, with one ε\varepsilon serving as level and connection scale, so fails when groups have different densities. OPTICS summarizes every DBSCAN in one ordering; HDBSCAN reconstructs the tree with single linkage on mutual reachability and selects clusters by stability, each branch’s area.
  • High-density clusters (Hartigan) are connected components of {f≥λ}\{f \ge \lambda\}; they form a tree. No single level recovers every mode if heights differ.
  • DBSCAN with (ε,minPts)(\varepsilon, \text{minPts}): cores split into components of a radius-ε\varepsilon graph and boundaries hang from them. Cores and noise are deterministic; boundary assignment depends on order. With minPts=2\text{minPts} = 2 it is single linkage cut at ε\varepsilon.
  • With minPts=k\text{minPts} = k, cores are points with ck≤εc_k \le \varepsilon, meaning f^k≥λε=k/(nVdεd)\hat f_k \ge \lambda_\varepsilon = k/(n V_d \varepsilon^d).
  • The kk-distance plot gives an ε\varepsilon with one density; with several it has a step for each and no ε\varepsilon recovers them all.
  • OPTICS orders points by reachability; a valley is a cluster, and a horizontal cut is DBSCAN (identical on cores).
  • HDBSCAN: core distance, mutual reachability max⁡{ck(a),ck(b),d(a,b)}\max\{c_k(a), c_k(b), d(a, b)\}, MST, single linkage (containing all DBSCAN*), condensation with min_cluster_size, stability S(C)S(C) (branch area) and bottom-up excess-of-mass selection.
  • min_samples smooths density and defines noise; min_cluster_size decides which splits are clusters. EOM is far more stable than leaves.
  • Cost: DBSCAN is nn range queries (O(nlog⁡n)\bigO(n \log n) in practice in low dimension, O(n2)\bigO(n^2) worst case); HDBSCAN adds an MST. In high dimension distances concentrate and the ε\varepsilon window closes: reduce dimension first.