Skip to main content

lib_jsl_machine_learning/unsupervised/clustering/
hdbscan.rs

1//! HDBSCAN hierarchical density-based clustering.
2//!
3//! See the book entry [Density-based clustering: DBSCAN and HDBSCAN](https://jwkunz.github.io/lib_jsl/book/unsupervised/density.html#hdbscan-every-density-at-once).
4
5use crate::common::{Clusterer, check_features, pairwise_distances};
6use lib_jsl_core::{ErrorsJSL, VR2D};
7
8/// Hierarchical DBSCAN (Campello, Moulavi and Sander). Instead of one density threshold `eps` it
9/// considers *all* of them at once:
10///
11/// 1. the *mutual reachability* distance `max(core(a), core(b), d(a, b))` (with `core` the
12///    distance to the `min_samples`-th nearest neighbour) spreads sparse points apart;
13/// 2. a minimum spanning tree of that metric gives the single-linkage hierarchy;
14/// 3. the hierarchy is condensed: a split only counts if both parts have at least
15///    `min_cluster_size` points, smaller pieces are just points falling out of their cluster;
16/// 4. each condensed cluster's *stability* `Σ (λ_leave - λ_birth)` (with `λ = 1/distance`) measures
17///    how long and how densely it persists, and the set of non-overlapping clusters with the
18///    greatest total stability is chosen ("excess of mass").
19///
20/// The result finds clusters of different densities without choosing `eps`, and labels the rest as
21/// noise (`None`). The implementation uses the dense `O(n²)` distance matrix.
22#[derive(Debug, Clone)]
23pub struct Hdbscan {
24    min_cluster_size: usize,
25    min_samples: usize,
26    stabilities: Vec<f64>,
27}
28
29#[derive(Debug, Clone)]
30struct CondensedCluster {
31    parent: Option<usize>,
32    birth_lambda: f64,
33    children: Vec<usize>,
34    stability: f64,
35    /// Points that fell out of this cluster, with the λ at which they did.
36    fallen: Vec<usize>,
37}
38
39const LAMBDA_CAP: f64 = 1e12;
40
41fn lambda_of(distance: f64) -> f64 {
42    if distance > 0.0 { (1.0 / distance).min(LAMBDA_CAP) } else { LAMBDA_CAP }
43}
44
45impl Hdbscan {
46    pub fn new(min_cluster_size: usize) -> Self {
47        Hdbscan { min_cluster_size, min_samples: min_cluster_size, stabilities: Vec::new() }
48    }
49
50    /// Sets `min_samples`, the neighbour count defining local density (default: `min_cluster_size`);
51    /// larger values make the result more conservative about calling points part of clusters.
52    pub fn with_min_samples(mut self, min_samples: usize) -> Self {
53        self.min_samples = min_samples;
54        self
55    }
56
57    /// The stability of each selected cluster, in label order.
58    pub fn cluster_stabilities(&self) -> &[f64] {
59        &self.stabilities
60    }
61}
62
63impl Clusterer for Hdbscan {
64    fn fit_predict(&mut self, x: VR2D) -> Result<Vec<Option<usize>>, ErrorsJSL> {
65        check_features(x)?;
66        let n = x.nrows();
67        if self.min_cluster_size < 2 || self.min_samples == 0 {
68            return Err(ErrorsJSL::InvalidInputRange("Need min_cluster_size >= 2 and min_samples >= 1."));
69        }
70        if n < self.min_cluster_size {
71            self.stabilities.clear();
72            return Ok(vec![None; n]);
73        }
74        let d = pairwise_distances(x);
75        // ANCHOR: mutual_reachability
76        // 1. Core distances and mutual reachability.
77        let core: Vec<f64> = (0..n)
78            .map(|i| {
79                let mut row = d.row(i).to_vec();
80                row.sort_by(f64::total_cmp);
81                row[(self.min_samples - 1).min(n - 1)]
82            })
83            .collect();
84        let mr = |i: usize, j: usize| d[[i, j]].max(core[i]).max(core[j]);
85        // 2. Minimum spanning tree (Prim, O(n²)).
86        let mut in_tree = vec![false; n];
87        let mut best = vec![(f64::INFINITY, 0usize); n];
88        in_tree[0] = true;
89        for (j, slot) in best.iter_mut().enumerate().skip(1) {
90            *slot = (mr(0, j), 0);
91        }
92        let mut edges: Vec<(f64, usize, usize)> = Vec::with_capacity(n - 1);
93        for _ in 1..n {
94            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");
95            edges.push((best[v].0, best[v].1, v));
96            in_tree[v] = true;
97            for j in (0..n).filter(|&j| !in_tree[j]) {
98                let w = mr(v, j);
99                if w < best[j].0 {
100                    best[j] = (w, v);
101                }
102            }
103        }
104        edges.sort_by(|a, b| a.0.total_cmp(&b.0));
105        // ANCHOR_END: mutual_reachability
106        // 3. Single-linkage tree: node ids 0..n are points, n.. are merges.
107        let mut uf: Vec<usize> = (0..2 * n).collect();
108        fn find(uf: &mut [usize], mut x: usize) -> usize {
109            while uf[x] != x {
110                uf[x] = uf[uf[x]];
111                x = uf[x];
112            }
113            x
114        }
115        let mut size = vec![1usize; 2 * n];
116        let mut children = vec![(0usize, 0usize); 2 * n];
117        let mut height = vec![0.0; 2 * n];
118        for (step, &(w, a, b)) in edges.iter().enumerate() {
119            let (ra, rb) = (find(&mut uf, a), find(&mut uf, b));
120            let id = n + step;
121            children[id] = (ra, rb);
122            height[id] = w;
123            size[id] = size[ra] + size[rb];
124            uf[ra] = id;
125            uf[rb] = id;
126        }
127        let root = 2 * n - 2;
128        // 4. Condense the tree.
129        let mcs = self.min_cluster_size;
130        let mut clusters = vec![CondensedCluster { parent: None, birth_lambda: 0.0, children: Vec::new(), stability: 0.0, fallen: Vec::new() }];
131        let mut point_cluster = vec![0usize; n];
132        let mut stack = vec![(root, 0usize)];
133        let leaves_of = |node: usize, children: &[(usize, usize)]| {
134            let mut out = Vec::new();
135            let mut s = vec![node];
136            while let Some(u) = s.pop() {
137                if u < n {
138                    out.push(u);
139                } else {
140                    s.push(children[u].0);
141                    s.push(children[u].1);
142                }
143            }
144            out
145        };
146        while let Some((node, cid)) = stack.pop() {
147            if node < n {
148                // A lone point reached the bottom of the condensed cluster.
149                point_cluster[node] = cid;
150                clusters[cid].fallen.push(node);
151                continue;
152            }
153            let lambda = lambda_of(height[node]);
154            let (l, r) = children[node];
155            let birth = clusters[cid].birth_lambda;
156            match (size[l] >= mcs, size[r] >= mcs) {
157                (true, true) => {
158                    clusters[cid].stability += (lambda - birth) * size[node] as f64;
159                    let mut kids = Vec::new();
160                    for side in [l, r] {
161                        let id = clusters.len();
162                        clusters.push(CondensedCluster { parent: Some(cid), birth_lambda: lambda, children: Vec::new(), stability: 0.0, fallen: Vec::new() });
163                        kids.push(id);
164                        stack.push((side, id));
165                    }
166                    clusters[cid].children = kids;
167                }
168                (false, false) => {
169                    clusters[cid].stability += (lambda - birth) * size[node] as f64;
170                    for p in leaves_of(node, &children) {
171                        point_cluster[p] = cid;
172                        clusters[cid].fallen.push(p);
173                    }
174                }
175                (big_left, _) => {
176                    let (big, small) = if big_left { (l, r) } else { (r, l) };
177                    clusters[cid].stability += (lambda - birth) * size[small] as f64;
178                    for p in leaves_of(small, &children) {
179                        point_cluster[p] = cid;
180                        clusters[cid].fallen.push(p);
181                    }
182                    stack.push((big, cid));
183                }
184            }
185        }
186        // ANCHOR: excess_of_mass
187        // 5. Excess-of-mass selection, bottom-up (children have larger ids than their parents).
188        let m = clusters.len();
189        let mut selected = vec![false; m];
190        let mut best_total = vec![0.0; m];
191        for c in (0..m).rev() {
192            if clusters[c].children.is_empty() {
193                selected[c] = true;
194                best_total[c] = clusters[c].stability;
195            } else {
196                let child_sum: f64 = clusters[c].children.iter().map(|&k| best_total[k]).sum();
197                if c != 0 && clusters[c].stability >= child_sum {
198                    selected[c] = true;
199                    best_total[c] = clusters[c].stability;
200                    let mut s = clusters[c].children.clone();
201                    while let Some(k) = s.pop() {
202                        selected[k] = false;
203                        s.extend(clusters[k].children.iter().copied());
204                    }
205                } else {
206                    best_total[c] = child_sum;
207                }
208            }
209        }
210        selected[0] = false; // the root is the whole data set, never a cluster by itself
211        // ANCHOR_END: excess_of_mass
212        // 6. Label the points by the selected cluster above (or at) where they fell out.
213        let mut label_of = vec![None; m];
214        self.stabilities.clear();
215        for (next, c) in (0..m).filter(|&c| selected[c]).enumerate() {
216            label_of[c] = Some(next);
217            self.stabilities.push(clusters[c].stability);
218        }
219        Ok((0..n)
220            .map(|p| {
221                let mut c = Some(point_cluster[p]);
222                while let Some(id) = c {
223                    if selected[id] {
224                        return label_of[id];
225                    }
226                    c = clusters[id].parent;
227                }
228                None
229            })
230            .collect())
231    }
232}
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237    use crate::datasets::{make_blobs, make_moons};
238    use crate::metrics::adjusted_rand_index;
239    use ndarray::{Axis, arr2, concatenate};
240
241    #[test]
242    fn finds_clusters_of_very_different_density_that_dbscan_cannot() {
243        // A tight blob and a diffuse blob: no single eps suits both.
244        let (dense, _) = make_blobs(60, &[vec![0.0, 0.0]], 0.2, 1);
245        let (sparse, _) = make_blobs(60, &[vec![10.0, 10.0]], 2.0, 2);
246        let x = concatenate(Axis(0), &[dense.view(), sparse.view()]).unwrap();
247        let truth: Vec<Option<usize>> = (0..120).map(|i| Some(usize::from(i >= 60))).collect();
248        let got = Hdbscan::new(10).fit_predict(x.view()).unwrap();
249        let clusters: std::collections::HashSet<_> = got.iter().flatten().collect();
250        assert_eq!(clusters.len(), 2);
251        // Most points land in the right cluster (some sparse-tail points may be noise).
252        let right = (0..120).filter(|&i| got[i].is_some()).count();
253        assert!(right > 100, "{right}");
254        let (kept, kept_truth): (Vec<_>, Vec<_>) = (0..120).filter(|&i| got[i].is_some()).map(|i| (got[i], truth[i])).unzip();
255        assert!(adjusted_rand_index(&kept, &kept_truth).unwrap() > 0.95);
256    }
257
258    #[test]
259    fn recovers_moons_and_flags_outliers_as_noise() {
260        let (m, l) = make_moons(120, 0.06, 5);
261        let got = Hdbscan::new(15).fit_predict(m.view()).unwrap();
262        let (kept, truth): (Vec<_>, Vec<_>) = (0..240).filter(|&i| got[i].is_some()).map(|i| (got[i], Some(l[i]))).unzip();
263        assert!(kept.len() > 200 && adjusted_rand_index(&kept, &truth).unwrap() > 0.9);
264        let with_noise = concatenate(Axis(0), &[m.view(), arr2(&[[8.0, 8.0], [-7.0, 9.0], [9.0, -6.0]]).view()]).unwrap();
265        let g = Hdbscan::new(15).fit_predict(with_noise.view()).unwrap();
266        assert!(g[240..].iter().all(Option::is_none));
267    }
268
269    #[test]
270    fn three_blobs_stabilities_and_degenerate_inputs() {
271        let (x, l) = make_blobs(40, &[vec![0.0, 0.0], vec![8.0, 0.0], vec![4.0, 7.0]], 0.6, 7);
272        let mut h = Hdbscan::new(8);
273        let got = h.fit_predict(x.view()).unwrap();
274        let truth: Vec<Option<usize>> = l.iter().map(|&c| Some(c)).collect();
275        assert!((adjusted_rand_index(&got, &truth).unwrap() - 1.0).abs() < 1e-9, "{got:?}");
276        assert_eq!(h.cluster_stabilities().len(), 3);
277        assert!(h.cluster_stabilities().iter().all(|&s| s > 0.0));
278        // Fewer points than the minimum cluster size: all noise, no panic.
279        assert_eq!(Hdbscan::new(10).fit_predict(arr2(&[[0.0], [1.0]]).view()).unwrap(), vec![None, None]);
280        // Identical points do not break the λ computation.
281        let same = lib_jsl_core::R2D::ones((30, 2));
282        assert_eq!(Hdbscan::new(5).fit_predict(same.view()).unwrap().len(), 30);
283        assert!(Hdbscan::new(1).fit_predict(x.view()).is_err());
284        assert!(Hdbscan::new(5).with_min_samples(0).fit_predict(x.view()).is_err());
285        // Larger min_samples is more conservative: no more clustered points than before.
286        let loose = Hdbscan::new(8).fit_predict(x.view()).unwrap().iter().flatten().count();
287        let strict = Hdbscan::new(8).with_min_samples(25).fit_predict(x.view()).unwrap().iter().flatten().count();
288        assert!(strict <= loose);
289    }
290}