Skip to main content

lib_jsl_machine_learning/unsupervised/clustering/
gaussian_mixture_models.rs

1//! Gaussian mixture models fitted by expectation-maximisation.
2//!
3//! See the book entry [Gaussian mixture models](https://jwkunz.github.io/lib_jsl/book/unsupervised/gaussian-mixtures.html).
4
5use crate::common::{Clusterer, argmax, check_features};
6use crate::unsupervised::clustering::k_means::KMeans;
7use lib_jsl_core::{ErrorsJSL, R1D, R2D, VR2D};
8use ndarray::Array2;
9use lib_jsl_linalg::{Cholesky, Diag, SolveTriangular, UPLO};
10
11/// The shape of each component's covariance matrix.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum CovarianceType {
14    /// A full matrix per component: arbitrary ellipsoids with any orientation.
15    Full,
16    /// Axis-aligned ellipsoids (independent features) per component: fewer parameters.
17    Diagonal,
18}
19
20/// A mixture `p(x) = Σ_k w_k N(x; μ_k, Σ_k)` fitted by EM: the E-step computes each component's
21/// responsibility for each point, the M-step re-estimates weights, means and covariances from the
22/// responsibility-weighted data, and the log-likelihood never decreases. Initialised from a k-means
23/// run. `reg_covar` is added to every covariance diagonal so components cannot collapse onto single
24/// points. Unlike k-means this is a *soft* clustering with elliptical clusters, and gives a
25/// probability model: density, membership probabilities, and the BIC/AIC for choosing `k`.
26#[derive(Debug, Clone)]
27pub struct GaussianMixture {
28    k: usize,
29    covariance: CovarianceType,
30    max_iterations: usize,
31    tolerance: f64,
32    reg_covar: f64,
33    seed: u64,
34    weights: Vec<f64>,
35    means: R2D,
36    covariances: Vec<R2D>,
37    chol: Vec<R2D>,
38    log_likelihood: f64,
39    iterations: usize,
40    samples: usize,
41}
42
43impl GaussianMixture {
44    pub fn new(k: usize, covariance: CovarianceType, seed: u64) -> Self {
45        GaussianMixture {
46            k,
47            covariance,
48            max_iterations: 200,
49            tolerance: 1e-6,
50            reg_covar: 1e-6,
51            seed,
52            weights: Vec::new(),
53            means: R2D::zeros((0, 0)),
54            covariances: Vec::new(),
55            chol: Vec::new(),
56            log_likelihood: f64::NAN,
57            iterations: 0,
58            samples: 0,
59        }
60    }
61
62    pub fn with_limits(mut self, max_iterations: usize, tolerance: f64) -> Self {
63        self.max_iterations = max_iterations;
64        self.tolerance = tolerance;
65        self
66    }
67
68    pub fn weights(&self) -> &[f64] {
69        &self.weights
70    }
71
72    pub fn means(&self) -> &R2D {
73        &self.means
74    }
75
76    pub fn covariances(&self) -> &[R2D] {
77        &self.covariances
78    }
79
80    /// The mean log-likelihood per sample on the training data.
81    pub fn mean_log_likelihood(&self) -> f64 {
82        self.log_likelihood
83    }
84
85    pub fn iterations(&self) -> usize {
86        self.iterations
87    }
88
89    fn parameter_count(&self) -> usize {
90        let p = self.means.ncols();
91        let cov = match self.covariance {
92            CovarianceType::Full => p * (p + 1) / 2,
93            CovarianceType::Diagonal => p,
94        };
95        self.k * (p + cov) + self.k - 1
96    }
97
98    /// Bayesian information criterion on the training data (lower is better).
99    pub fn bic(&self) -> f64 {
100        -2.0 * self.log_likelihood * self.samples as f64 + self.parameter_count() as f64 * (self.samples as f64).ln()
101    }
102
103    /// Akaike information criterion on the training data (lower is better).
104    pub fn aic(&self) -> f64 {
105        -2.0 * self.log_likelihood * self.samples as f64 + 2.0 * self.parameter_count() as f64
106    }
107
108    fn component_log_pdf(&self, c: usize, x: &[f64]) -> f64 {
109        let p = x.len();
110        let diff = R1D::from_iter((0..p).map(|j| x[j] - self.means[[c, j]]));
111        let l = &self.chol[c];
112        let z = l.solve_triangular(UPLO::Lower, Diag::NonUnit, &diff).expect("triangular solve");
113        let log_det: f64 = (0..p).map(|j| l[[j, j]].ln()).sum::<f64>() * 2.0;
114        -0.5 * (p as f64 * std::f64::consts::TAU.ln() + log_det + z.dot(&z))
115    }
116
117    fn log_joint(&self, x: &[f64]) -> Vec<f64> {
118        (0..self.k).map(|c| self.weights[c].max(1e-300).ln() + self.component_log_pdf(c, x)).collect()
119    }
120
121    /// Membership probabilities, `(rows, components)`.
122    pub fn predict_proba(&self, x: VR2D) -> Result<R2D, ErrorsJSL> {
123        self.check(x)?;
124        let mut out = R2D::zeros((x.nrows(), self.k));
125        for (i, row) in x.rows().into_iter().enumerate() {
126            let lj = self.log_joint(&row.to_vec());
127            let m = lj.iter().copied().fold(f64::NEG_INFINITY, f64::max);
128            let total: f64 = lj.iter().map(|v| (v - m).exp()).sum();
129            for c in 0..self.k {
130                out[[i, c]] = (lj[c] - m).exp() / total;
131            }
132        }
133        Ok(out)
134    }
135
136    /// The most probable component of each row.
137    pub fn predict(&self, x: VR2D) -> Result<Vec<usize>, ErrorsJSL> {
138        Ok(self.predict_proba(x)?.rows().into_iter().map(|r| argmax(&r.to_vec()).unwrap_or(0)).collect())
139    }
140
141    /// The log of the mixture density at each row.
142    pub fn score_samples(&self, x: VR2D) -> Result<Vec<f64>, ErrorsJSL> {
143        self.check(x)?;
144        Ok(x.rows()
145            .into_iter()
146            .map(|r| {
147                let lj = self.log_joint(&r.to_vec());
148                let m = lj.iter().copied().fold(f64::NEG_INFINITY, f64::max);
149                m + lj.iter().map(|v| (v - m).exp()).sum::<f64>().ln()
150            })
151            .collect())
152    }
153
154    fn check(&self, x: VR2D) -> Result<(), ErrorsJSL> {
155        if self.weights.is_empty() {
156            return Err(ErrorsJSL::Misconfiguration("The model has not been fitted."));
157        }
158        check_features(x)?;
159        if x.ncols() != self.means.ncols() {
160            return Err(ErrorsJSL::IncompatibleArraySizes((x.ncols(), self.means.ncols())));
161        }
162        Ok(())
163    }
164
165    /// M-step from responsibilities `r` (`n × k`).
166    fn maximise(&mut self, x: VR2D, r: &R2D) -> Result<(), ErrorsJSL> {
167        let (n, p) = x.dim();
168        self.weights = (0..self.k).map(|c| r.column(c).sum() / n as f64).collect();
169        self.means = R2D::zeros((self.k, p));
170        self.covariances = Vec::with_capacity(self.k);
171        self.chol = Vec::with_capacity(self.k);
172        for c in 0..self.k {
173            let nk = r.column(c).sum().max(1e-12);
174            for j in 0..p {
175                self.means[[c, j]] = (0..n).map(|i| r[[i, c]] * x[[i, j]]).sum::<f64>() / nk;
176            }
177            let mut cov = Array2::<f64>::zeros((p, p));
178            for i in 0..n {
179                let d: Vec<f64> = (0..p).map(|j| x[[i, j]] - self.means[[c, j]]).collect();
180                for a in 0..p {
181                    match self.covariance {
182                        CovarianceType::Full => (0..p).for_each(|b| cov[[a, b]] += r[[i, c]] * d[a] * d[b]),
183                        CovarianceType::Diagonal => cov[[a, a]] += r[[i, c]] * d[a] * d[a],
184                    }
185                }
186            }
187            cov /= nk;
188            for a in 0..p {
189                cov[[a, a]] += self.reg_covar;
190            }
191            let l = cov.cholesky(UPLO::Lower).map_err(|_| ErrorsJSL::RuntimeError("A component covariance is not positive definite."))?;
192            self.covariances.push(cov);
193            self.chol.push(l);
194        }
195        Ok(())
196    }
197}
198
199impl Clusterer for GaussianMixture {
200    fn fit_predict(&mut self, x: VR2D) -> Result<Vec<Option<usize>>, ErrorsJSL> {
201        check_features(x)?;
202        let n = x.nrows();
203        if self.k == 0 || self.k > n {
204            return Err(ErrorsJSL::InvalidInputRange("k must be between 1 and the number of samples."));
205        }
206        // Initial responsibilities from k-means (hard assignments).
207        let init = KMeans::new(self.k, self.seed).fit_predict(x)?;
208        let mut resp = R2D::zeros((n, self.k));
209        for (i, l) in init.iter().enumerate() {
210            resp[[i, l.expect("k-means labels every point")]] = 1.0;
211        }
212        self.samples = n;
213        self.maximise(x, &resp)?;
214        let mut previous = f64::NEG_INFINITY;
215        self.iterations = 0;
216        // ANCHOR: em
217        for it in 1..=self.max_iterations {
218            self.iterations = it;
219            // E-step.
220            let mut total = 0.0;
221            for (i, row) in x.rows().into_iter().enumerate() {
222                let lj = self.log_joint(&row.to_vec());
223                let m = lj.iter().copied().fold(f64::NEG_INFINITY, f64::max);
224                let s: f64 = lj.iter().map(|v| (v - m).exp()).sum();
225                total += m + s.ln();
226                for c in 0..self.k {
227                    resp[[i, c]] = (lj[c] - m).exp() / s;
228                }
229            }
230            self.log_likelihood = total / n as f64;
231            if (self.log_likelihood - previous).abs() < self.tolerance {
232                break;
233            }
234            previous = self.log_likelihood;
235            self.maximise(x, &resp)?;
236            if it == self.max_iterations {
237                // Stopped at the limit after an M-step: report the likelihood of the final parameters.
238                self.log_likelihood = self.score_samples(x)?.iter().sum::<f64>() / n as f64;
239            }
240        }
241        // ANCHOR_END: em
242        Ok(self.predict(x)?.into_iter().map(Some).collect())
243    }
244}
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249    use crate::datasets::make_blobs;
250    use crate::metrics::adjusted_rand_index;
251    use ndarray::{Axis, concatenate};
252
253    fn truth(l: &[usize]) -> Vec<Option<usize>> {
254        l.iter().map(|&c| Some(c)).collect()
255    }
256
257    #[test]
258    fn reported_likelihood_matches_the_final_parameters_even_at_the_iteration_limit() {
259        let (x, _) = make_blobs(60, &[vec![0.0, 0.0], vec![3.0, 1.0]], 1.0, 2);
260        for limit in [1, 2, 5] {
261            let mut g = GaussianMixture::new(2, CovarianceType::Full, 1).with_limits(limit, 0.0);
262            g.fit_predict(x.view()).unwrap();
263            let mean = g.score_samples(x.view()).unwrap().iter().sum::<f64>() / x.nrows() as f64;
264            assert!((g.mean_log_likelihood() - mean).abs() < 1e-12, "limit {limit}");
265        }
266    }
267
268    #[test]
269    fn recovers_blob_parameters() {
270        let centres = vec![vec![0.0, 0.0], vec![6.0, 1.0], vec![2.0, 7.0]];
271        let (x, l) = make_blobs(150, &centres, 0.7, 4);
272        let mut g = GaussianMixture::new(3, CovarianceType::Full, 1);
273        let got = g.fit_predict(x.view()).unwrap();
274        assert!((adjusted_rand_index(&got, &truth(&l)).unwrap() - 1.0).abs() < 1e-9);
275        for w in g.weights() {
276            assert!((w - 1.0 / 3.0).abs() < 0.02);
277        }
278        // Every true centre has a fitted mean within a small distance, and variance ≈ 0.49.
279        for c in &centres {
280            let best = (0..3).map(|k| ((g.means()[[k, 0]] - c[0]).powi(2) + (g.means()[[k, 1]] - c[1]).powi(2)).sqrt()).fold(f64::INFINITY, f64::min);
281            assert!(best < 0.2, "{best}");
282        }
283        // The clusters barely overlap, so each fitted covariance is the sample covariance (divisor n)
284        // of the points generated from the matching centre.
285        for k in 0..3 {
286            let c = (0..3).min_by(|&a, &b| {
287                let d = |c: usize| (g.means()[[k, 0]] - centres[c][0]).powi(2) + (g.means()[[k, 1]] - centres[c][1]).powi(2);
288                d(a).total_cmp(&d(b))
289            }).unwrap();
290            let idx: Vec<usize> = (0..x.nrows()).filter(|&i| l[i] == c).collect();
291            let m: Vec<f64> = (0..2).map(|j| idx.iter().map(|&i| x[[i, j]]).sum::<f64>() / idx.len() as f64).collect();
292            for (a, b) in [(0, 0), (0, 1), (1, 1)] {
293                let sample = idx.iter().map(|&i| (x[[i, a]] - m[a]) * (x[[i, b]] - m[b])).sum::<f64>() / idx.len() as f64;
294                assert!((g.covariances()[k][[a, b]] - sample).abs() < 1e-3, "{} vs {sample}", g.covariances()[k][[a, b]]);
295            }
296        }
297        assert!(g.iterations() >= 1 && g.mean_log_likelihood().is_finite());
298    }
299
300    #[test]
301    fn fits_elongated_clusters_that_k_means_splits_wrongly_and_bic_picks_k() {
302        // Two long, thin, parallel Gaussians: full covariances capture them, k-means cuts across.
303        let (mut a, _) = make_blobs(200, &[vec![0.0, 0.0]], 1.0, 1);
304        let (mut b, _) = make_blobs(200, &[vec![0.0, 0.0]], 1.0, 2);
305        a.column_mut(0).mapv_inplace(|v| v * 4.0);
306        b.column_mut(0).mapv_inplace(|v| v * 4.0);
307        b.column_mut(1).mapv_inplace(|v| v + 4.0);
308        let x = concatenate(Axis(0), &[a.view(), b.view()]).unwrap();
309        let t: Vec<Option<usize>> = (0..400).map(|i| Some(usize::from(i >= 200))).collect();
310        let mut gm = GaussianMixture::new(2, CovarianceType::Full, 3);
311        let gl = gm.fit_predict(x.view()).unwrap();
312        let km = KMeans::new(2, 3).fit_predict(x.view()).unwrap();
313        // The best possible labelling is the optimal rule for the true model, y > 2; the mixture
314        // should match it (the classes overlap, so neither is perfect).
315        let optimal: Vec<Option<usize>> = (0..400).map(|i| Some(usize::from(x[[i, 1]] > 2.0))).collect();
316        assert!(adjusted_rand_index(&gl, &t).unwrap() >= adjusted_rand_index(&optimal, &t).unwrap() - 0.02);
317        assert!(adjusted_rand_index(&gl, &t).unwrap() > adjusted_rand_index(&km, &t).unwrap());
318        // BIC is minimised at the true number of components on well-separated blobs.
319        let (bx, _) = make_blobs(100, &[vec![0.0, 0.0], vec![8.0, 0.0], vec![0.0, 8.0]], 0.8, 6);
320        let bic = |k: usize| {
321            let mut g = GaussianMixture::new(k, CovarianceType::Full, 1);
322            g.fit_predict(bx.view()).unwrap();
323            g.bic()
324        };
325        assert!(bic(3) < bic(2) && bic(3) < bic(5), "{} {} {}", bic(2), bic(3), bic(5));
326    }
327
328    #[test]
329    fn soft_assignments_density_and_diagonal_covariance() {
330        let (x, _) = make_blobs(80, &[vec![0.0, 0.0], vec![5.0, 0.0]], 0.6, 8);
331        let mut g = GaussianMixture::new(2, CovarianceType::Diagonal, 2);
332        g.fit_predict(x.view()).unwrap();
333        let p = g.predict_proba(x.view()).unwrap();
334        assert!(p.rows().into_iter().all(|r| (r.sum() - 1.0).abs() < 1e-12));
335        // A point midway between the blobs is uncertain; one at a centre is confident.
336        let mid = g.predict_proba(ndarray::arr2(&[[2.5, 0.0], [0.0, 0.0]]).view()).unwrap();
337        assert!(mid[[0, 0]].max(mid[[0, 1]]) < 0.9 && mid[[1, 0]].max(mid[[1, 1]]) > 0.99);
338        let dens = g.score_samples(ndarray::arr2(&[[0.0, 0.0], [30.0, 30.0]]).view()).unwrap();
339        assert!(dens[0] > dens[1]);
340        assert!(g.covariances().iter().all(|c| c[[0, 1]] == 0.0));
341        let mut full = GaussianMixture::new(2, CovarianceType::Full, 2);
342        full.fit_predict(x.view()).unwrap();
343        assert!(g.aic() < full.aic() + 20.0); // fewer parameters, comparable fit
344    }
345
346    #[test]
347    fn errors() {
348        let (x, _) = make_blobs(5, &[vec![0.0, 0.0]], 1.0, 1);
349        assert!(GaussianMixture::new(0, CovarianceType::Full, 1).fit_predict(x.view()).is_err());
350        assert!(GaussianMixture::new(6, CovarianceType::Full, 1).fit_predict(x.view()).is_err());
351        assert!(GaussianMixture::new(2, CovarianceType::Full, 1).predict(x.view()).is_err());
352        // Identical points: the regulariser keeps the covariance positive definite.
353        let same = R2D::ones((20, 2));
354        assert!(GaussianMixture::new(1, CovarianceType::Full, 1).fit_predict(same.view()).is_ok());
355    }
356}