Skip to main content

solow_preprocessing/
binarizer.rs

1//! `Binarizer` — element-wise threshold transformer.
2
3use ndarray::{Array2, ArrayView2};
4use solow_core::{Error, Result};
5
6/// Fitted Binarizer.
7#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
8#[derive(Clone, Debug, PartialEq)]
9pub struct Binarizer {
10    /// Threshold value.
11    pub threshold: f64,
12    /// Column count seen at fit.
13    pub n_features_in: usize,
14}
15
16impl Binarizer {
17    /// Fit with the given threshold.
18    pub fn fit(x: ArrayView2<'_, f64>, threshold: f64) -> Result<Self> {
19        if x.ncols() == 0 {
20            return Err(Error::Value("Binarizer: no columns".into()));
21        }
22        if !threshold.is_finite() {
23            return Err(Error::Value("Binarizer: threshold must be finite".into()));
24        }
25        Ok(Self {
26            threshold,
27            n_features_in: x.ncols(),
28        })
29    }
30
31    /// Fit with the reference default `threshold = 0.0`.
32    pub fn fit_default(x: ArrayView2<'_, f64>) -> Result<Self> {
33        Self::fit(x, 0.0)
34    }
35
36    /// Transform.
37    pub fn transform(&self, x: ArrayView2<'_, f64>) -> Result<Array2<f64>> {
38        if x.ncols() != self.n_features_in {
39            return Err(Error::Shape("Binarizer::transform: column count mismatch".into()));
40        }
41        let mut out = Array2::<f64>::zeros((x.nrows(), x.ncols()));
42        for i in 0..x.nrows() {
43            for j in 0..x.ncols() {
44                out[[i, j]] = if x[[i, j]] > self.threshold { 1.0 } else { 0.0 };
45            }
46        }
47        Ok(out)
48    }
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54    use ndarray::array;
55
56    #[test]
57    fn binarizer_thresholds_at_zero_by_default() {
58        let x = array![[-1.0_f64, 0.0, 1.0], [0.5, -0.5, 2.0]];
59        let b = Binarizer::fit_default(x.view()).unwrap();
60        let z = b.transform(x.view()).unwrap();
61        assert_eq!(z[[0, 0]], 0.0);
62        assert_eq!(z[[0, 1]], 0.0);
63        assert_eq!(z[[0, 2]], 1.0);
64        assert_eq!(z[[1, 0]], 1.0);
65    }
66}