Skip to main content

lib_jsl_machine_learning/supervised/classification/
naive_bayes.rs

1//! Naive Bayes classifiers.
2//!
3//! See the book entry [Naive Bayes](https://jwkunz.github.io/lib_jsl/book/machine_learning/naive-bayes.html).
4
5use crate::common::{Classifier, argmax, check_features, check_xy, class_count};
6use lib_jsl_core::{ErrorsJSL, R2D, VR2D};
7
8/// Gaussian naive Bayes: each class models every feature as an independent normal distribution
9/// (the "naive" independence assumption), and a point goes to the class with the highest posterior
10/// `P(class) Π P(x_j | class)`. Fast, needs little data, and surprisingly strong when features are
11/// roughly independent given the class. `var_smoothing` adds a fraction of the largest feature
12/// variance to every variance, which keeps constant features from causing division by zero.
13#[derive(Debug, Clone)]
14pub struct GaussianNaiveBayes {
15    var_smoothing: f64,
16    log_prior: Vec<f64>,
17    mean: Vec<Vec<f64>>,
18    var: Vec<Vec<f64>>,
19}
20
21impl GaussianNaiveBayes {
22    pub fn new() -> Self {
23        GaussianNaiveBayes { var_smoothing: 1e-9, log_prior: Vec::new(), mean: Vec::new(), var: Vec::new() }
24    }
25
26    pub fn with_var_smoothing(mut self, smoothing: f64) -> Self {
27        self.var_smoothing = smoothing;
28        self
29    }
30
31    /// Per-class feature means (`[class][feature]`).
32    pub fn class_means(&self) -> &[Vec<f64>] {
33        &self.mean
34    }
35
36    // ANCHOR: gaussian_nb
37    /// Joint log-likelihood `log P(class) + Σ log P(x_j | class)` as a `(rows, classes)` matrix.
38    pub fn joint_log_likelihood(&self, x: VR2D) -> Result<R2D, ErrorsJSL> {
39        if self.mean.is_empty() {
40            return Err(ErrorsJSL::Misconfiguration("The model has not been fitted."));
41        }
42        check_features(x)?;
43        if x.ncols() != self.mean[0].len() {
44            return Err(ErrorsJSL::IncompatibleArraySizes((x.ncols(), self.mean[0].len())));
45        }
46        Ok(R2D::from_shape_fn((x.nrows(), self.mean.len()), |(i, c)| {
47            self.log_prior[c]
48                - 0.5
49                    * (0..x.ncols())
50                        .map(|j| (std::f64::consts::TAU * self.var[c][j]).ln() + (x[[i, j]] - self.mean[c][j]).powi(2) / self.var[c][j])
51                        .sum::<f64>()
52        }))
53    }
54    // ANCHOR_END: gaussian_nb
55
56    /// Posterior class probabilities.
57    pub fn predict_proba(&self, x: VR2D) -> Result<R2D, ErrorsJSL> {
58        let mut jll = self.joint_log_likelihood(x)?;
59        for mut row in jll.rows_mut() {
60            let max = row.iter().copied().fold(f64::NEG_INFINITY, f64::max);
61            row.mapv_inplace(|v| (v - max).exp());
62            let total = row.sum();
63            row.mapv_inplace(|v| v / total);
64        }
65        Ok(jll)
66    }
67}
68
69impl Default for GaussianNaiveBayes {
70    fn default() -> Self {
71        Self::new()
72    }
73}
74
75impl Classifier for GaussianNaiveBayes {
76    fn fit(&mut self, x: VR2D, labels: &[usize]) -> Result<(), ErrorsJSL> {
77        check_xy(x, labels.len())?;
78        let (n, p) = x.dim();
79        let classes = class_count(labels);
80        let counts: Vec<usize> = (0..classes).map(|c| labels.iter().filter(|&&l| l == c).count()).collect();
81        if counts.contains(&0) {
82            return Err(ErrorsJSL::InvalidInputRange("Every class label in 0..classes must occur."));
83        }
84        let max_var = (0..p)
85            .map(|j| {
86                let m = x.column(j).sum() / n as f64;
87                x.column(j).iter().map(|v| (v - m).powi(2)).sum::<f64>() / n as f64
88            })
89            .fold(0.0, f64::max);
90        let eps = self.var_smoothing * max_var.max(1e-12);
91        self.mean = vec![vec![0.0; p]; classes];
92        self.var = vec![vec![0.0; p]; classes];
93        for (row, &c) in x.rows().into_iter().zip(labels) {
94            for j in 0..p {
95                self.mean[c][j] += row[j] / counts[c] as f64;
96            }
97        }
98        for (row, &c) in x.rows().into_iter().zip(labels) {
99            for j in 0..p {
100                self.var[c][j] += (row[j] - self.mean[c][j]).powi(2) / counts[c] as f64;
101            }
102        }
103        self.var.iter_mut().flatten().for_each(|v| *v += eps);
104        self.log_prior = counts.iter().map(|&c| (c as f64 / n as f64).ln()).collect();
105        Ok(())
106    }
107
108    fn predict(&self, x: VR2D) -> Result<Vec<usize>, ErrorsJSL> {
109        Ok(self.joint_log_likelihood(x)?.rows().into_iter().map(|r| argmax(&r.to_vec()).unwrap_or(0)).collect())
110    }
111}
112
113/// Multinomial naive Bayes for count features (word counts, histograms): the class-conditional
114/// feature distribution is multinomial with Laplace/Lidstone smoothing `alpha`.
115#[derive(Debug, Clone)]
116pub struct MultinomialNaiveBayes {
117    alpha: f64,
118    log_prior: Vec<f64>,
119    log_likelihood: Vec<Vec<f64>>,
120}
121
122impl MultinomialNaiveBayes {
123    pub fn new(alpha: f64) -> Self {
124        MultinomialNaiveBayes { alpha, log_prior: Vec::new(), log_likelihood: Vec::new() }
125    }
126}
127
128impl Classifier for MultinomialNaiveBayes {
129    fn fit(&mut self, x: VR2D, labels: &[usize]) -> Result<(), ErrorsJSL> {
130        check_xy(x, labels.len())?;
131        if x.iter().any(|&v| v < 0.0) || self.alpha.is_nan() || self.alpha < 0.0 {
132            return Err(ErrorsJSL::InvalidInputRange("Counts must be non-negative and alpha >= 0."));
133        }
134        let (n, p) = x.dim();
135        let classes = class_count(labels);
136        let mut totals = vec![vec![0.0; p]; classes];
137        let mut counts = vec![0usize; classes];
138        for (row, &c) in x.rows().into_iter().zip(labels) {
139            counts[c] += 1;
140            for j in 0..p {
141                totals[c][j] += row[j];
142            }
143        }
144        if counts.contains(&0) {
145            return Err(ErrorsJSL::InvalidInputRange("Every class label in 0..classes must occur."));
146        }
147        self.log_prior = counts.iter().map(|&c| (c as f64 / n as f64).ln()).collect();
148        self.log_likelihood = totals
149            .iter()
150            .map(|t| {
151                let denom = t.iter().sum::<f64>() + self.alpha * p as f64;
152                t.iter().map(|&v| ((v + self.alpha) / denom).ln()).collect()
153            })
154            .collect();
155        Ok(())
156    }
157
158    fn predict(&self, x: VR2D) -> Result<Vec<usize>, ErrorsJSL> {
159        if self.log_prior.is_empty() {
160            return Err(ErrorsJSL::Misconfiguration("The model has not been fitted."));
161        }
162        check_features(x)?;
163        if x.ncols() != self.log_likelihood[0].len() {
164            return Err(ErrorsJSL::IncompatibleArraySizes((x.ncols(), self.log_likelihood[0].len())));
165        }
166        Ok(x.rows()
167            .into_iter()
168            .map(|r| {
169                let scores: Vec<f64> = (0..self.log_prior.len()).map(|c| {
170                        // Absent features contribute nothing: with alpha = 0 an unseen feature has a
171                        // log-likelihood of -inf, and 0 * -inf would be NaN.
172                        self.log_prior[c] + r.iter().zip(&self.log_likelihood[c]).filter(|(v, _)| **v != 0.0).map(|(v, l)| v * l).sum::<f64>()
173                    })
174                    .collect();
175                argmax(&scores).unwrap_or(0)
176            })
177            .collect())
178    }
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184    use crate::datasets::{make_blobs, make_classification};
185    use crate::metrics::accuracy;
186    use crate::preprocessing::{select_labels, select_rows, train_test_split};
187    use ndarray::arr2;
188
189    #[test]
190    fn gaussian_nb_classifies_overlapping_classes() {
191        let (x, l) = make_classification(120, 7);
192        let (tr, te) = train_test_split(x.nrows(), 0.3, 2).unwrap();
193        let mut m = GaussianNaiveBayes::new();
194        m.fit(select_rows(x.view(), &tr).view(), &select_labels(&l, &tr)).unwrap();
195        let acc = accuracy(&select_labels(&l, &te), &m.predict(select_rows(x.view(), &te).view()).unwrap()).unwrap();
196        assert!(acc > 0.8, "{acc}");
197        let p = m.predict_proba(x.view()).unwrap();
198        assert!(p.rows().into_iter().all(|r| (r.sum() - 1.0).abs() < 1e-12));
199        assert_eq!(m.class_means().len(), 3);
200    }
201
202    #[test]
203    fn priors_matter_and_constant_features_are_safe() {
204        // Two identical blobs but 9:1 class imbalance -> the prior dominates at the shared centre.
205        let (a, _) = make_blobs(90, &[vec![0.0, 0.0]], 1.0, 1);
206        let (b, _) = make_blobs(10, &[vec![0.0, 0.0]], 1.0, 2);
207        let x = ndarray::concatenate(ndarray::Axis(0), &[a.view(), b.view()]).unwrap();
208        let labels: Vec<usize> = std::iter::repeat_n(0, 90).chain(std::iter::repeat_n(1, 10)).collect();
209        let mut m = GaussianNaiveBayes::new();
210        m.fit(x.view(), &labels).unwrap();
211        assert_eq!(m.predict(arr2(&[[0.0, 0.0]]).view()).unwrap(), vec![0]);
212        let with_const = arr2(&[[1.0, 5.0], [1.2, 5.0], [3.0, 5.0], [3.1, 5.0]]);
213        let mut c = GaussianNaiveBayes::new();
214        c.fit(with_const.view(), &[0, 0, 1, 1]).unwrap();
215        assert_eq!(c.predict(with_const.view()).unwrap(), vec![0, 0, 1, 1]);
216    }
217
218    #[test]
219    fn multinomial_nb_on_word_counts() {
220        // Features: counts of ["goal", "match", "vote", "law"]; class 0 = sport, 1 = politics.
221        let x = arr2(&[[3.0, 2.0, 0.0, 0.0], [2.0, 4.0, 1.0, 0.0], [0.0, 1.0, 3.0, 2.0], [0.0, 0.0, 4.0, 3.0]]);
222        let mut m = MultinomialNaiveBayes::new(1.0);
223        m.fit(x.view(), &[0, 0, 1, 1]).unwrap();
224        assert_eq!(m.predict(arr2(&[[1.0, 3.0, 0.0, 0.0], [0.0, 0.0, 2.0, 5.0]]).view()).unwrap(), vec![0, 1]);
225        assert!(MultinomialNaiveBayes::new(1.0).fit(arr2(&[[-1.0]]).view(), &[0]).is_err());
226        assert!(MultinomialNaiveBayes::new(1.0).predict(x.view()).is_err());
227        // Without smoothing, a word never seen in a class rules that class out only when it occurs.
228        let mut unsmoothed = MultinomialNaiveBayes::new(0.0);
229        unsmoothed.fit(x.view(), &[0, 0, 1, 1]).unwrap();
230        assert_eq!(unsmoothed.predict(arr2(&[[1.0, 3.0, 0.0, 0.0], [0.0, 0.0, 2.0, 5.0]]).view()).unwrap(), vec![0, 1]);
231    }
232
233    #[test]
234    fn errors() {
235        let x = arr2(&[[0.0], [1.0]]);
236        assert!(GaussianNaiveBayes::new().fit(x.view(), &[0, 2]).is_err()); // class 1 missing
237        assert!(GaussianNaiveBayes::new().predict(x.view()).is_err());
238        let mut m = GaussianNaiveBayes::new();
239        m.fit(x.view(), &[0, 1]).unwrap();
240        assert!(m.predict(arr2(&[[1.0, 2.0]]).view()).is_err());
241    }
242}