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
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 , divides space into Voronoi cells, and assigns every point a cluster, including noise that also pulls centroids. Hierarchical clustering does not require 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 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 -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
Suppose for a moment you know the density generating the data. A group should be a region where 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 , . Set is connected and contained in , so lies in a single connected component of . If that component is , then ; if another, is disjoint from because components are disjoint.
∎Picture it: raise 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.
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 -neighbor estimator gives a density at each point: the smallest ball centered at containing points (counting itself if it is in the sample) has radius , and since it encloses mass in volume , with the unit-ball volume in ,
Other normalizations (for example in the numerator) change one constant and nothing that follows. Throughout the lesson is called core distance , counting the point itself as first neighbor, so . This is scikit-learn’s convention.
A sample clustering at level would then keep points with 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 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 (via reduction to continuum percolation). Chaudhuri and Dasgupta (2010, “Rates of convergence for the cluster tree”) propose robust single linkage: for each radius , the graph whose vertices are points with and whose edges join pairs with . Single linkage is the case , , and Wishart (1969) had proposed with larger . For and of order they prove the estimated tree converges to Hartigan’s with explicit rates. Remember : for each 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 and integer . Let be the dataset with distance and let be ‘s neighborhood, including .
(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 range queries plus linear work; query cost is the last section’s subject. Try it before reading on.
Keep what the two figures show. With too small, almost everything is noise and clusters fragment. With 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: 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 to be dense; an adjacent dense group becomes connected at that .
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 be a core point and the set of density-reachable points from . A chain has all points except the last in , and each is within of . Thus form a path in , and is in ‘s component if core, or a non-core point within of otherwise. Conversely every such point is reachable by a chain. Hence , where consists of non-core points within of .
is a cluster: maximal because if and is reachable from , then is core (if ) and the chain from to concatenates with that from to ; and connected because all its points are reachable from .
Every cluster has this form. Take core . By maximality, . For , connectivity provides an from which and are reachable. If , is core and is core reachable from ; since the relation between cores is symmetric ( is symmetric and both are core), reaches , and by concatenation . Thus and . This proves (a); (b) follows from and the fact depends only on , itself determined only by data and .
∎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 are exactly sample points whose core distance satisfies , meaning , where
Indeed, means at least points (counting ) lie within , meaning the th neighbor is within . 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- graph on points in level set . One level, and one serving simultaneously as connection scale and density level: .
DBSCAN with is single linkage
The smallest parameter case matches what you already know.
Exercise 1 provides the proof step by step. The idea: with , a point is core if and only if it has another point within ; a non-core point has no neighbor and therefore cannot lie in a core point’s neighborhood, so there are no boundary points. Raise and pay with noise: points lacking sufficient density stop connecting, and sparse bridges break.
Choosing and
Ester and colleagues proposed a graphical heuristic in the original paper. Fix , calculate each point’s -distance (distance to the th neighbor, counted without the point itself in the paper; here we count it, so our of corresponds to there), sort and plot them. Reasoning: points with small -distance are in dense regions, those with large -distance are noise, and the sharp change, or elbow, separates them. The elbow value is the at which nearly all cluster points are core and nearly all noise is not. The paper uses for planar data.
Behind this is the previous section’s identity: a point’s -distance is the smallest 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.
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
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 . For , a common starting value is order with dimension, raised when noise is heavy or the sample large. Larger 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
If the problem is the value of , 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 from is at least , 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 at which they merge. Watch the traversal.
The figure’s green readout is a result, not a coincidence.
Proof
Sketch. Let be a core point for () just visited. All its unvisited neighbors in receive . While any unvisited point has , the next visited is one of them, because the smallest is selected. Traversal therefore leaves a cluster only when no unvisited point is density-reachable (at radius ) from visited points, meaning its connected core component plus boundaries is complete. The next point has and, if core, starts a new cluster: it is core of another component. A point with 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 . But the underlying problem remains. A horizontal cut is still one level. To extract clusters at different levels, the paper proposes the method, searching for sharp rises and falls (relative slope greater than ) to delimit valleys; scikit-learn uses it with cluster_method="xi", and its result depends strongly on 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 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.
With this distance the single-linkage hierarchy has an exact DBSCAN interpretation justifying the design.
Proof
If , every edge has , so is isolated. If , then is equivalent to . Thus the part of on points with (cores, by equivalence between being core and having in the previous section) is graph of the structure theorem. The final claim is the single-linkage theorem applied to : cuts of the single-linkage hierarchy are connected components of threshold graphs.
∎Graph is also Chaudhuri and Dasgupta’s robust-single-linkage graph with and radius : vertices with and edges with . HDBSCAN is that case.
In terms of the first figure’s tree, this is the gain. For fixed , dendrogram height for corresponds to level of the level set. HDBSCAN uses not but , 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 axis, and a nonlinear rescaling stretches some branches more than others, so the selection criterion can change its answer: is Campello and colleagues’ convention, not the only possible one. The construction is already familiar: the minimum spanning tree of distance (Prim, on the dense matrix without needing to store it) and a union-find hierarchy, the dendrogram.
The condensed tree
The single-linkage dendrogram has 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 .
Think of a cluster branch as a ribbon whose width is the number of points remaining in it. As 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 , naturally measure how long it lives: how many points and for what interval.
Stability is an area. Let be the number of points still in at level , the branch width. Each point contributes , so , the branch area drawn with width proportional to (the layer-cake integral trick with counting measure). In the continuous case with density and region , it is Müller and Sawitzki’s excess of mass, . This names the criterion. The correspondence is exact when the vertical axis is density level; with , 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 , worth . At an internal node, an admissible subtree set is either 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, by induction; the first is worth . Take the maximum, computed by the traversal.
∎The root is excluded for a specific reason: it is born with 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.
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 into branches of 34 and 31 points at both min_cluster_size values. With , those branches live until and , their stabilities sum to and beat the parent’s . With , the 31-point branch dies at , 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 , its sister’s to , their sum () no longer reaches and the parent wins. A cluster near 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 in core distance : it smooths density estimation and decides which points are noise (a point with large lies at low scale and falls out early). min_cluster_size is 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.
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 from a core in each of two groups.
# 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 time and memory; a spatial index such as the KD-tree grows much more slowly in low dimension.
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 by 4 multiplies time by 4 or less (at fixed call cost still matters). With the matrix, the factor is clearly above 4 and approaches quadratic 16 as grows, because at these sizes the row loop, linear, still matters. Memory is unambiguous: the matrix occupies bytes, 122 MB at , and at would be bytes, about 75 GB. Now the underlying problem’s data: two nearby dense groups and a diffuse one, with noise. Sweep the grid and count pairs recovering all three groups.
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 table tells the lesson’s story. At there are three clusters, but 90% of the diffuse group is noise. At there are still three clusters and 64% of the diffuse group remains noise. At 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 and of 2 or 3, nearly single linkage. HDBSCAN needs no and recovers them with two very different min_cluster_size values.
Now OPTICS, also from scratch and on the same data.
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.
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 ), 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).
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 this is single linkage: clouds join at , one seventh of actual separation . With they join at and with at . Mutual reachability does not eliminate chaining; it makes it more expensive. Inside clouds core distance also rises (the third column goes from to ), so look at the ratio: with the join is times the height at which a cloud completes, and with it is , a clear dendrogram gap. It does not rise monotonically. With it falls to : each bridge point still has its two chain neighbors within , so its stays at most and the join does not move, while the cloud completes higher. With it is : with 18 points per cloud, forces each cloud point to cover more than half the cloud and full-cloud height grows nearly as much as bridge height. Thus 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.
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 and HDBSCAN perform similarly (ARI and ). On different-density data, DBSCAN with produces six clusters and ARI , HDBSCAN three and . 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 range queries. With a spatial index (KD-tree or ball tree, from the nearest-neighbor lesson), each query costs order plus result size in low dimension, and total in practice. But the original paper claimed generally, and Gan and Tao (SIGMOD 2015) showed that claim was wrong: the algorithm is in the worst case, and in dimension solving DBSCAN exactly requires unless open computational-geometry problems are solved (Gunawan’s algorithm does achieve 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 plus neighborhoods.
HDBSCAN has two expensive steps: core distances (a -neighbor search per point, which is indexed) and the minimum spanning tree of . With a dense matrix, Prim takes 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 in any dimension. DBSCAN needs greater than the 5-distance of almost all points (so they are core) and less than the height at which the two groups merge.
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 the group merges at an more than twice what is needed for cores, and from the ratio is between and : the window does not exist or spans 2% of . The reason is visible in column three: relative dispersion of -distance falls from to , 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
Step 1 of 4. Which points are core with ?
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 etiquetasSummary
- High-density clusters (Hartigan) are connected components of ; they form a tree. No single level recovers every mode if heights differ.
- DBSCAN with : cores split into components of a radius- graph and boundaries hang from them. Cores and noise are deterministic; boundary assignment depends on order. With it is single linkage cut at .
- With , cores are points with , meaning .
- The -distance plot gives an with one density; with several it has a step for each and no 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 , MST, single linkage (containing all DBSCAN*), condensation with
min_cluster_size, stability (branch area) and bottom-up excess-of-mass selection. min_samplessmooths density and defines noise;min_cluster_sizedecides which splits are clusters. EOM is far more stable than leaves.- Cost: DBSCAN is range queries ( in practice in low dimension, worst case); HDBSCAN adds an MST. In high dimension distances concentrate and the window closes: reduce dimension first.