Skip to main content

lib_jsl_machine_learning/unsupervised/clustering/
dbscan.rs

1//! DBSCAN 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).
4
5use crate::common::{Clusterer, check_features, pairwise_distances};
6use lib_jsl_core::{ErrorsJSL, VR2D};
7
8/// Density-Based Spatial Clustering of Applications with Noise. A point is a *core* point if at
9/// least `min_samples` points (itself included) lie within `eps` of it; clusters are the
10/// connected regions of core points together with the *border* points within `eps` of a core
11/// point, and everything else is noise (`None`). Unlike k-means it needs no cluster count, finds
12/// arbitrarily shaped clusters and flags outliers, but a single `eps` cannot suit clusters of
13/// very different density (see HDBSCAN).
14#[derive(Debug, Clone)]
15pub struct Dbscan {
16    eps: f64,
17    min_samples: usize,
18    core_points: Vec<usize>,
19}
20
21impl Dbscan {
22    pub fn new(eps: f64, min_samples: usize) -> Self {
23        Dbscan { eps, min_samples, core_points: Vec::new() }
24    }
25
26    /// Indices of the core points found by the last fit.
27    pub fn core_points(&self) -> &[usize] {
28        &self.core_points
29    }
30}
31
32impl Clusterer for Dbscan {
33    fn fit_predict(&mut self, x: VR2D) -> Result<Vec<Option<usize>>, ErrorsJSL> {
34        check_features(x)?;
35        if self.eps.is_nan() || self.eps <= 0.0 || self.min_samples == 0 {
36            return Err(ErrorsJSL::InvalidInputRange("Need eps > 0 and min_samples >= 1."));
37        }
38        let n = x.nrows();
39        let d = pairwise_distances(x);
40        // ANCHOR: dbscan
41        let neighbours: Vec<Vec<usize>> = (0..n).map(|i| (0..n).filter(|&j| d[[i, j]] <= self.eps).collect()).collect();
42        let is_core: Vec<bool> = neighbours.iter().map(|nb| nb.len() >= self.min_samples).collect();
43        let mut labels: Vec<Option<usize>> = vec![None; n];
44        let mut next = 0;
45        for start in (0..n).filter(|&i| is_core[i]) {
46            if labels[start].is_some() {
47                continue;
48            }
49            labels[start] = Some(next);
50            let mut queue = vec![start];
51            while let Some(p) = queue.pop() {
52                for &q in &neighbours[p] {
53                    if labels[q].is_none() {
54                        labels[q] = Some(next);
55                        if is_core[q] {
56                            queue.push(q); // only core points propagate the cluster
57                        }
58                    }
59                }
60            }
61            next += 1;
62        }
63        // ANCHOR_END: dbscan
64        self.core_points = (0..n).filter(|&i| is_core[i]).collect();
65        Ok(labels)
66    }
67}
68
69#[cfg(test)]
70mod tests {
71    use super::*;
72    use crate::datasets::{make_blobs, make_circles, make_moons};
73    use crate::metrics::adjusted_rand_index;
74    use ndarray::{Axis, arr2, concatenate};
75
76    #[test]
77    fn separates_nonconvex_shapes_that_defeat_k_means() {
78        let (x, l) = make_moons(150, 0.05, 1);
79        let got = Dbscan::new(0.2, 5).fit_predict(x.view()).unwrap();
80        let truth: Vec<Option<usize>> = l.iter().map(|&c| Some(c)).collect();
81        assert!(adjusted_rand_index(&got, &truth).unwrap() > 0.97);
82        let (cx, cl) = make_circles(120, 0.03, 0.4, 2);
83        let got = Dbscan::new(0.15, 4).fit_predict(cx.view()).unwrap();
84        assert!(adjusted_rand_index(&got, &cl.iter().map(|&c| Some(c)).collect::<Vec<_>>()).unwrap() > 0.95);
85    }
86
87    #[test]
88    fn noise_border_and_core_points_are_distinguished() {
89        // A dense line of five points, one border point near the end, and one far outlier.
90        let x = arr2(&[[0.0, 0.0], [0.5, 0.0], [1.0, 0.0], [1.5, 0.0], [2.0, 0.0], [2.9, 0.0], [50.0, 50.0]]);
91        let mut db = Dbscan::new(0.6, 3);
92        let labels = db.fit_predict(x.view()).unwrap();
93        assert!(labels[..5].iter().all(|l| *l == Some(0)));
94        assert_eq!(labels[5], None); // 0.9 from the nearest point: out of reach
95        assert_eq!(labels[6], None);
96        assert_eq!(db.core_points(), &[1, 2, 3]);
97        // Raising eps lets the straggler join as a border point (it is not core itself).
98        let mut wide = Dbscan::new(1.0, 3);
99        let l2 = wide.fit_predict(x.view()).unwrap();
100        assert_eq!(l2[5], Some(0));
101        assert!(!wide.core_points().contains(&5));
102    }
103
104    #[test]
105    fn parameters_control_the_outcome() {
106        let (a, _) = make_blobs(40, &[vec![0.0, 0.0], vec![6.0, 0.0]], 0.4, 3);
107        let tiny = Dbscan::new(0.001, 3).fit_predict(a.view()).unwrap();
108        assert!(tiny.iter().all(Option::is_none)); // eps too small: everything is noise
109        let huge = Dbscan::new(100.0, 3).fit_predict(a.view()).unwrap();
110        assert!(huge.iter().all(|l| *l == Some(0))); // eps too large: one blob
111        let with_outliers = concatenate(Axis(0), &[a.view(), arr2(&[[20.0, 20.0], [-20.0, 15.0]]).view()]).unwrap();
112        let l = Dbscan::new(0.8, 4).fit_predict(with_outliers.view()).unwrap();
113        assert_eq!(l.iter().flatten().collect::<std::collections::HashSet<_>>().len(), 2);
114        assert!(l[80].is_none() && l[81].is_none());
115        assert!(Dbscan::new(0.0, 3).fit_predict(a.view()).is_err());
116        assert!(Dbscan::new(1.0, 0).fit_predict(a.view()).is_err());
117    }
118}