Skip to main content

lib_jsl_machine_learning/unsupervised/clustering/
k_means.rs

1//! k-means clustering.
2//!
3//! See the book entry [k-means and k-medoids](https://jwkunz.github.io/lib_jsl/book/unsupervised/k-means.html).
4
5use crate::common::{Clusterer, MlRng, check_features, squared_distance};
6use lib_jsl_core::{ErrorsJSL, R2D, VR2D};
7
8/// One Lloyd run: final centres, labels, inertia and iteration count.
9type LloydRun = (Vec<Vec<f64>>, Vec<usize>, f64, usize);
10
11/// Lloyd's k-means with k-means++ seeding: alternately assign each point to its nearest centroid
12/// and move each centroid to the mean of its points, minimising the within-cluster sum of squared
13/// distances (the inertia). The run is repeated `n_init` times from different seedings and the
14/// lowest-inertia result kept, because the algorithm only finds a local optimum. A cluster that
15/// loses all its points is re-seeded at the point farthest from its centroid.
16#[derive(Debug, Clone)]
17pub struct KMeans {
18    k: usize,
19    n_init: usize,
20    max_iterations: usize,
21    tolerance: f64,
22    seed: u64,
23    centroids: R2D,
24    inertia: f64,
25    iterations: usize,
26}
27
28impl KMeans {
29    pub fn new(k: usize, seed: u64) -> Self {
30        KMeans { k, n_init: 5, max_iterations: 300, tolerance: 1e-8, seed, centroids: R2D::zeros((0, 0)), inertia: f64::NAN, iterations: 0 }
31    }
32
33    pub fn with_restarts(mut self, n_init: usize) -> Self {
34        self.n_init = n_init.max(1);
35        self
36    }
37
38    pub fn with_limits(mut self, max_iterations: usize, tolerance: f64) -> Self {
39        self.max_iterations = max_iterations;
40        self.tolerance = tolerance;
41        self
42    }
43
44    pub fn centroids(&self) -> &R2D {
45        &self.centroids
46    }
47
48    /// The sum of squared distances from each point to its centroid, for the best restart.
49    pub fn inertia(&self) -> f64 {
50        self.inertia
51    }
52
53    /// Lloyd iterations used by the best restart.
54    pub fn iterations(&self) -> usize {
55        self.iterations
56    }
57
58    /// The nearest centroid of each row.
59    pub fn predict(&self, x: VR2D) -> Result<Vec<usize>, ErrorsJSL> {
60        if self.centroids.nrows() == 0 {
61            return Err(ErrorsJSL::Misconfiguration("The model has not been fitted."));
62        }
63        check_features(x)?;
64        if x.ncols() != self.centroids.ncols() {
65            return Err(ErrorsJSL::IncompatibleArraySizes((x.ncols(), self.centroids.ncols())));
66        }
67        let c: Vec<Vec<f64>> = self.centroids.rows().into_iter().map(|r| r.to_vec()).collect();
68        Ok(x.rows().into_iter().map(|r| nearest(&r.to_vec(), &c).0).collect())
69    }
70
71    /// k-means++: the first centre uniformly, each next with probability proportional to the
72    /// squared distance to the closest chosen centre.
73    // ANCHOR: kmeanspp
74    fn seed_centres(&self, pts: &[Vec<f64>], rng: &mut MlRng) -> Vec<Vec<f64>> {
75        let mut centres = vec![pts[rng.below(pts.len())].clone()];
76        let mut d2: Vec<f64> = pts.iter().map(|p| squared_distance(p, &centres[0])).collect();
77        while centres.len() < self.k {
78            let total: f64 = d2.iter().sum();
79            let pick = if total <= 0.0 {
80                rng.below(pts.len())
81            } else {
82                let mut target = rng.uniform() * total;
83                let mut chosen = pts.len() - 1;
84                for (i, &w) in d2.iter().enumerate() {
85                    if target < w {
86                        chosen = i;
87                        break;
88                    }
89                    target -= w;
90                }
91                chosen
92            };
93            centres.push(pts[pick].clone());
94            for (i, p) in pts.iter().enumerate() {
95                d2[i] = d2[i].min(squared_distance(p, centres.last().expect("non-empty")));
96            }
97        }
98        centres
99    }
100    // ANCHOR_END: kmeanspp
101
102    // ANCHOR: lloyd
103    fn lloyd(&self, pts: &[Vec<f64>], mut centres: Vec<Vec<f64>>) -> LloydRun {
104        let (n, dims) = (pts.len(), pts[0].len());
105        let mut labels = vec![0usize; n];
106        let mut iterations = 0;
107        for it in 1..=self.max_iterations {
108            iterations = it;
109            let mut dist = vec![0.0; n];
110            for (i, p) in pts.iter().enumerate() {
111                let (c, d) = nearest(p, &centres);
112                labels[i] = c;
113                dist[i] = d;
114            }
115            let mut sums = vec![vec![0.0; dims]; self.k];
116            let mut counts = vec![0usize; self.k];
117            for (p, &l) in pts.iter().zip(&labels) {
118                counts[l] += 1;
119                sums[l].iter_mut().zip(p).for_each(|(s, v)| *s += v);
120            }
121            let mut shift: f64 = 0.0;
122            for c in 0..self.k {
123                let new: Vec<f64> = if counts[c] == 0 {
124                    // Re-seed an empty cluster at the worst-fitted point.
125                    let far = dist.iter().enumerate().max_by(|a, b| a.1.total_cmp(b.1)).map_or(0, |(i, _)| i);
126                    dist[far] = 0.0;
127                    pts[far].clone()
128                } else {
129                    sums[c].iter().map(|s| s / counts[c] as f64).collect()
130                };
131                shift = shift.max(squared_distance(&new, &centres[c]));
132                centres[c] = new;
133            }
134            if shift <= self.tolerance * self.tolerance {
135                break;
136            }
137        }
138        let mut inertia = 0.0;
139        for (i, p) in pts.iter().enumerate() {
140            let (c, d) = nearest(p, &centres);
141            labels[i] = c;
142            inertia += d;
143        }
144        (centres, labels, inertia, iterations)
145    }
146    // ANCHOR_END: lloyd
147}
148
149/// The nearest centre's index and squared distance.
150fn nearest(p: &[f64], centres: &[Vec<f64>]) -> (usize, f64) {
151    centres.iter().enumerate().map(|(i, c)| (i, squared_distance(p, c))).fold((0, f64::INFINITY), |b, c| if c.1 < b.1 { c } else { b })
152}
153
154impl Clusterer for KMeans {
155    fn fit_predict(&mut self, x: VR2D) -> Result<Vec<Option<usize>>, ErrorsJSL> {
156        check_features(x)?;
157        if self.k == 0 || self.k > x.nrows() {
158            return Err(ErrorsJSL::InvalidInputRange("k must be between 1 and the number of samples."));
159        }
160        let pts: Vec<Vec<f64>> = x.rows().into_iter().map(|r| r.to_vec()).collect();
161        let mut rng = MlRng::new(self.seed);
162        let mut best: Option<LloydRun> = None;
163        for _ in 0..self.n_init {
164            let seeds = self.seed_centres(&pts, &mut rng);
165            let run = self.lloyd(&pts, seeds);
166            if best.as_ref().is_none_or(|b| run.2 < b.2) {
167                best = Some(run);
168            }
169        }
170        let (centres, labels, inertia, iterations) = best.expect("at least one restart");
171        self.centroids = R2D::from_shape_fn((self.k, x.ncols()), |(i, j)| centres[i][j]);
172        self.inertia = inertia;
173        self.iterations = iterations;
174        Ok(labels.into_iter().map(Some).collect())
175    }
176}
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181    use crate::datasets::{make_blobs, make_moons};
182    use crate::metrics::adjusted_rand_index;
183    use ndarray::arr2;
184
185    fn truth(l: &[usize]) -> Vec<Option<usize>> {
186        l.iter().map(|&c| Some(c)).collect()
187    }
188
189    #[test]
190    fn recovers_well_separated_blobs() {
191        let (x, l) = make_blobs(50, &[vec![0.0, 0.0], vec![8.0, 0.0], vec![4.0, 7.0], vec![-6.0, 5.0]], 0.8, 3);
192        let mut km = KMeans::new(4, 1);
193        let got = km.fit_predict(x.view()).unwrap();
194        assert!((adjusted_rand_index(&got, &truth(&l)).unwrap() - 1.0).abs() < 1e-12);
195        assert_eq!(km.centroids().dim(), (4, 2));
196        assert_eq!(km.predict(x.view()).unwrap(), got.iter().map(|g| g.unwrap()).collect::<Vec<_>>());
197        assert!(km.iterations() >= 1 && km.inertia() > 0.0);
198    }
199
200    #[test]
201    fn inertia_decreases_with_k_and_restarts_never_hurt() {
202        let (x, _) = make_blobs(40, &[vec![0.0, 0.0], vec![6.0, 6.0], vec![0.0, 9.0]], 1.0, 5);
203        let inertia = |k: usize, n_init: usize| {
204            let mut km = KMeans::new(k, 2).with_restarts(n_init);
205            km.fit_predict(x.view()).unwrap();
206            km.inertia()
207        };
208        assert!(inertia(1, 3) > inertia(2, 3) && inertia(2, 3) > inertia(3, 3) && inertia(3, 3) > inertia(6, 3));
209        assert!(inertia(3, 10) <= inertia(3, 1) + 1e-9);
210        // k-means cannot separate interleaved moons: the grouping disagrees with the truth.
211        let (mx, ml) = make_moons(100, 0.05, 1);
212        let mut km = KMeans::new(2, 1);
213        let got = km.fit_predict(mx.view()).unwrap();
214        assert!(adjusted_rand_index(&got, &truth(&ml)).unwrap() < 0.6);
215    }
216
217    #[test]
218    fn edge_cases() {
219        let x = arr2(&[[0.0, 0.0], [0.0, 0.0], [5.0, 5.0], [5.0, 5.0]]);
220        let mut km = KMeans::new(2, 7);
221        let got = km.fit_predict(x.view()).unwrap();
222        assert_eq!(got[0], got[1]);
223        assert_ne!(got[0], got[2]);
224        assert!(km.inertia() < 1e-12);
225        // As many clusters as points, with duplicates, still yields k non-empty centroids.
226        let mut all = KMeans::new(4, 1);
227        all.fit_predict(x.view()).unwrap();
228        assert_eq!(all.centroids().nrows(), 4);
229        assert!(KMeans::new(0, 1).fit_predict(x.view()).is_err());
230        assert!(KMeans::new(5, 1).fit_predict(x.view()).is_err());
231        assert!(KMeans::new(2, 1).predict(x.view()).is_err());
232        assert!(km.predict(arr2(&[[1.0]]).view()).is_err());
233    }
234}