Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Density-based clustering: DBSCAN and HDBSCAN

ProblemFind clusters as dense regions separated by sparse ones, of any shape, without fixing their number, and label isolated points as noise
Devised byMartin Ester, Hans-Peter Kriegel, Jörg Sander and Xiaowei Xu (1996), DBSCAN; Mihael Ankerst, Markus Breunig, Kriegel and Sander (1999), OPTICS; Ricardo Campello, Davoud Moulavi and Sander (2013), HDBSCAN
AccuracyDeterministic (DBSCAN up to the assignment of border points reachable from two clusters)
Cost time and memory with the dense distance matrix used here; with a spatial index in low dimensions
Read firstHierarchical clustering and phylogenetic trees
APIDbscan (new(eps, min_samples), core_points), Hdbscan (new(min_cluster_size), with_min_samples, cluster_stabilities)

Overview

Centroid methods such as k-means describe a cluster by a centre and assume it is round. Density-based methods instead define a cluster as a region where points are packed closely, separated from other clusters by regions of low density. Such clusters can have any shape, their number is found rather than given, and points in sparse regions are labelled noise (None) rather than forced into a cluster. DBSCAN uses one density threshold. HDBSCAN considers every threshold at once and keeps the clusters that persist longest, which handles clusters of different densities.

Where it is used

Density-based clustering finds groups of any shape without being told how many there are.

  • Geospatial analysis. Finding hotspots of crime, accidents or disease cases, and clustering GPS traces.
  • Anomaly detection. Points not in any cluster are noise, useful in fraud detection and sensor monitoring.
  • Astronomy and physics. Clusters of stars or particles of irregular shape.
  • Image analysis. Grouping points in a point cloud (for example from lidar) into objects.

History

Martin Ester, Hans-Peter Kriegel, Jörg Sander and Xiaowei Xu at the University of Munich published DBSCAN in 1996 for spatial databases; it received the KDD test-of-time award in 2014. Its weakness, a single global radius, led to OPTICS (Ankerst, Breunig, Kriegel and Sander, 1999), which orders points by reachability so that clusters at every radius can be read off. Ricardo Campello, Davoud Moulavi and Jörg Sander (2013) turned the idea into a complete algorithm, HDBSCAN, by condensing the density hierarchy and selecting clusters by stability. Leland McInnes and John Healy’s accelerated implementation (2017) made it a popular default.

The idea

DBSCAN: core, border and noise points

DBSCAN has two parameters, a radius and a count min_samples. The ε-neighbourhood of a point is the set of points within distance of it, the point itself included.

  • A core point has at least min_samples points in its ε-neighbourhood.
  • A border point is not core but lies in the ε-neighbourhood of a core point.
  • Every other point is noise.

Two core points within of each other belong to the same cluster, and so, transitively, does every chain of such points. A cluster is a connected set of core points together with their border points.

Figure 12.3. DBSCAN on moons with noise.

The two moons are found without being told there are two, and the 20 points scattered over the box are labelled noise. Border points (yellow) sit at the thin ends of the moons. A border point within reach of two clusters joins whichever reaches it first, the only order dependence in the method.

Choosing ε

A common heuristic sorts the distances from each point to its -th nearest neighbour, with = min_samples − 1, and looks for a knee: points in clusters have small -distances, and noise points large ones.

Figure 12.4. k-distance plot.

Here, without noise, there is no sharp knee. A value just above the bulk of the curve, such as the ε = 0.2 used above, works well.

One radius cannot fit all densities

Two tight clusters next to one diffuse one:

With a small ε the diffuse cluster dissolves into noise, apart from a fragment. With a large ε it is found, but the two tight clusters merge. No single value gets all three:

Table 12.9. DBSCAN and HDBSCAN on the same data.

methodclustersnoise pointsARI (noise as its own group)
DBSCAN, ε = 0.22970.793
DBSCAN, ε = 0.33790.921
DBSCAN, ε = 0.56440.829
DBSCAN, ε = 0.73270.883
DBSCAN, ε = 12170.485
DBSCAN, ε = 1.5230.551
HDBSCAN, min_cluster_size = 5330.982
HDBSCAN, min_cluster_size = 15390.949
HDBSCAN, min_cluster_size = 403220.886

HDBSCAN: every density at once

HDBSCAN replaces ε with a hierarchy over all values of it:

  1. Core distance. is the distance from to its min_samples-th nearest neighbour (counting itself). It is small in dense regions.
  2. Mutual reachability. The distance leaves dense regions unchanged and pushes sparse points away from everything.
  3. Single-linkage tree. A minimum spanning tree of , cut at every height, gives exactly the DBSCAN clusterings for every ε at once (with core points only). See hierarchical clustering for the link between single linkage and spanning trees.
  4. Condensing. Walk down the tree, measuring density by . When a cluster splits and both parts have at least min_cluster_size points, two new clusters are born. When a smaller piece breaks off, its points simply leave the parent cluster at that .
  5. Stability. A cluster born at whose points leave at has stability , large for clusters that are dense and long-lived.
  6. Excess of mass. Working up from the leaves, keep a cluster if its stability exceeds the total of the best selection among its descendants; otherwise keep the descendants.

A point takes the label of the selected cluster it fell out of, or of that cluster’s nearest selected ancestor. Points that fell out higher in the tree than every selected cluster are noise. HDBSCAN finds the three clusters, with a few noise points in the diffuse cluster’s tail. Its one main parameter, min_cluster_size, is a size rather than a distance, and the results change slowly with it.

Algorithm

DBSCAN. Input: the points, the radius and min_samples.

  1. Neighbourhoods. For every point, list the points within distance of it (itself included). A point whose list has at least min_samples entries is a core point.
  2. Grow clusters. Take each core point that has no label yet, in order. Give it a new cluster label and put it in a queue. While the queue is not empty: remove a point; give the cluster’s label to each of its neighbours that has none; and add those of them that are core points to the queue. Border points receive a label but are not expanded.
  3. Noise. Points still without a label are noise.

With neighbourhoods found by comparing all pairs, the cost is .

HDBSCAN. Input: the points, min_samples and min_cluster_size.

  1. Core distances. For each point, the distance to its min_samples-th nearest neighbour.
  2. Spanning tree. Build a minimum spanning tree of the complete graph whose edge weights are the mutual reachability distances, by Prim’s algorithm on the dense matrix, .
  3. Single-linkage tree. Sort the tree’s edges by weight and merge their endpoints in that order, recording the hierarchy of merges.
  4. Condense. Walk the hierarchy from the root down. At each split, compare the sizes of the two parts with min_cluster_size: two large parts are two new clusters; a small part is a set of points falling out of the cluster that continues.
  5. Stability. For each cluster of the condensed tree, sum over its points.
  6. Select. Working from the leaves upwards, keep a cluster if its stability exceeds the combined stability of the clusters selected among its descendants; otherwise keep those.
  7. Label each point by the selected cluster it belongs to, or as noise.

Implementation

        let neighbours: Vec<Vec<usize>> = (0..n).map(|i| (0..n).filter(|&j| d[[i, j]] <= self.eps).collect()).collect();
        let is_core: Vec<bool> = neighbours.iter().map(|nb| nb.len() >= self.min_samples).collect();
        let mut labels: Vec<Option<usize>> = vec![None; n];
        let mut next = 0;
        for start in (0..n).filter(|&i| is_core[i]) {
            if labels[start].is_some() {
                continue;
            }
            labels[start] = Some(next);
            let mut queue = vec![start];
            while let Some(p) = queue.pop() {
                for &q in &neighbours[p] {
                    if labels[q].is_none() {
                        labels[q] = Some(next);
                        if is_core[q] {
                            queue.push(q); // only core points propagate the cluster
                        }
                    }
                }
            }
            next += 1;
        }
        // 1. Core distances and mutual reachability.
        let core: Vec<f64> = (0..n)
            .map(|i| {
                let mut row = d.row(i).to_vec();
                row.sort_by(f64::total_cmp);
                row[(self.min_samples - 1).min(n - 1)]
            })
            .collect();
        let mr = |i: usize, j: usize| d[[i, j]].max(core[i]).max(core[j]);
        // 2. Minimum spanning tree (Prim, O(n²)).
        let mut in_tree = vec![false; n];
        let mut best = vec![(f64::INFINITY, 0usize); n];
        in_tree[0] = true;
        for (j, slot) in best.iter_mut().enumerate().skip(1) {
            *slot = (mr(0, j), 0);
        }
        let mut edges: Vec<(f64, usize, usize)> = Vec::with_capacity(n - 1);
        for _ in 1..n {
            let v = (0..n).filter(|&j| !in_tree[j]).min_by(|&a, &b| best[a].0.total_cmp(&best[b].0)).expect("a vertex remains");
            edges.push((best[v].0, best[v].1, v));
            in_tree[v] = true;
            for j in (0..n).filter(|&j| !in_tree[j]) {
                let w = mr(v, j);
                if w < best[j].0 {
                    best[j] = (w, v);
                }
            }
        }
        edges.sort_by(|a, b| a.0.total_cmp(&b.0));
        // 5. Excess-of-mass selection, bottom-up (children have larger ids than their parents).
        let m = clusters.len();
        let mut selected = vec![false; m];
        let mut best_total = vec![0.0; m];
        for c in (0..m).rev() {
            if clusters[c].children.is_empty() {
                selected[c] = true;
                best_total[c] = clusters[c].stability;
            } else {
                let child_sum: f64 = clusters[c].children.iter().map(|&k| best_total[k]).sum();
                if c != 0 && clusters[c].stability >= child_sum {
                    selected[c] = true;
                    best_total[c] = clusters[c].stability;
                    let mut s = clusters[c].children.clone();
                    while let Some(k) = s.pop() {
                        selected[k] = false;
                        s.extend(clusters[k].children.iter().copied());
                    }
                } else {
                    best_total[c] = child_sum;
                }
            }
        }
        selected[0] = false; // the root is the whole data set, never a cluster by itself
  • Both build the dense distance matrix, which limits them to roughly points.
  • HDBSCAN never returns the whole data set as one cluster (the root is excluded), matching the reference implementation’s default.
  • min_samples defaults to min_cluster_size. Raising it makes more points noise.
  • Identical points give zero distances; is capped at to keep the stabilities finite.

In practice

//! Density-based clustering: DBSCAN with a fixed radius against HDBSCAN on clusters of different density.

use lib_jsl_machine_learning::common::Clusterer;
use lib_jsl_machine_learning::datasets::make_blobs;
use ndarray::{Axis, concatenate};
use lib_jsl_machine_learning::unsupervised::clustering::{Dbscan, Hdbscan};

fn summary(labels: &[Option<usize>]) -> String {
    let k = labels.iter().flatten().max().map_or(0, |m| m + 1);
    let sizes: Vec<usize> = (0..k).map(|c| labels.iter().filter(|l| **l == Some(c)).count()).collect();
    format!("{k} clusters of sizes {sizes:?}, {} noise points", labels.iter().filter(|l| l.is_none()).count())
}

fn main() {
    // Two tight blobs and one diffuse blob.
    let (dense, _) = make_blobs(80, &[vec![0.0, 0.0], vec![2.0, 0.0]], 0.25, 1);
    let (sparse, _) = make_blobs(80, &[vec![7.0, 4.0]], 1.6, 2);
    let x = concatenate(Axis(0), &[dense.view(), sparse.view()]).unwrap();
    for eps in [0.3, 1.0] {
        let mut db = Dbscan::new(eps, 5);
        let labels = db.fit_predict(x.view()).unwrap();
        println!("DBSCAN eps = {eps}: {} ({} core points)", summary(&labels), db.core_points().len());
    }
    let mut h = Hdbscan::new(15);
    let labels = h.fit_predict(x.view()).unwrap();
    println!("HDBSCAN:          {}", summary(&labels));
    println!("cluster stabilities: {:?}", h.cluster_stabilities().iter().map(|s| format!("{s:.0}")).collect::<Vec<_>>());
}
DBSCAN eps = 0.3: 3 clusters of sizes [78, 78, 5], 79 noise points (151 core points)
DBSCAN eps = 1: 2 clusters of sizes [160, 63], 17 noise points (217 core points)
HDBSCAN:          3 clusters of sizes [71, 80, 80], 9 noise points
cluster stabilities: ["27", "270", "225"]

The diffuse cluster has the smallest stability: it is found, but it is the least clear-cut of the three.

Strengths

  • Arbitrary cluster shapes, no cluster count, and explicit noise.
  • HDBSCAN handles varying densities with a single, intuitive parameter.

Weaknesses

  • Distances lose contrast in high dimensions, and density becomes hard to estimate.
  • DBSCAN’s ε is hard to choose; neither method gives a model for assigning new points.
  • The dense implementation needs memory.

Exercises

  1. Show that the DBSCAN clusters of core points are the connected components of the graph joining core points within ε.
  2. Show that is a metric when is.
  3. Explain why cutting the single-linkage tree of at height ε gives DBSCAN’s clustering of the core points with radius ε.
  4. Use a k-d tree to find ε-neighbourhoods and measure the speed-up over the dense distance matrix for points in the plane.
  5. Compute the stabilities by hand for six points on a line at 0, 0.1, 0.2, 5, 5.1, 5.2 with min_cluster_size = 3.
Hints and answers
  1. Core points within of each other are density-connected; DBSCAN’s cluster of a core point is everything reachable from it through chains of such core points, which is the connected component of the core-point graph.
  2. with the core distance: symmetry is clear, and the triangle inequality follows from and being monotone in each argument.
  3. Cutting the single-linkage tree at height joins exactly the pairs with , i.e. core points within of each other.
  4. A k-d tree answers radius queries in about time for results, so the neighbourhood computation falls from to nearly .
  5. The mutual-reachability graph joins the points within each triple at distances of about to and the two triples by one edge of length about . Compute each triple’s stability as the sum of with ; expect the two triples to be selected because their combined stability exceeds that of the merged cluster.

Further reading

  • M. Ester, H.-P. Kriegel, J. Sander and X. Xu, “A density-based algorithm for discovering clusters in large spatial databases with noise”, Proceedings of the 2nd International Conference on Knowledge Discovery and Data Mining (1996) 226–231.
  • R. J. G. B. Campello, D. Moulavi and J. Sander, “Density-based clustering based on hierarchical density estimates”, Advances in Knowledge Discovery and Data Mining, Lecture Notes in Computer Science 7819 (2013) 160–172.
  • L. McInnes, J. Healy and S. Astels, “hdbscan: hierarchical density based clustering”, Journal of Open Source Software 2 (2017) 205.
  • E. Schubert, J. Sander, M. Ester, H.-P. Kriegel and X. Xu, “DBSCAN revisited, revisited”, ACM Transactions on Database Systems 42 (2017) 19.