Skip to main content

lib_jsl_machine_learning/
preprocessing.rs

1//! Feature scaling, splitting and expansion.
2//!
3//! See the book entry [Foundations](https://jwkunz.github.io/lib_jsl/book/machine_learning/foundations.html#scaling).
4
5use crate::common::{MlRng, Transformer, check_features};
6use lib_jsl_core::{ErrorsJSL, R1D, R2D, VR1D, VR2D};
7
8/// Standardises each column to zero mean and unit variance (constant columns are only centred).
9#[derive(Debug, Clone, Default)]
10pub struct StandardScaler {
11    mean: Vec<f64>,
12    scale: Vec<f64>,
13}
14
15impl StandardScaler {
16    pub fn new() -> Self {
17        Self::default()
18    }
19    pub fn mean(&self) -> &[f64] {
20        &self.mean
21    }
22    pub fn scale(&self) -> &[f64] {
23        &self.scale
24    }
25    /// Undoes [`Transformer::transform`].
26    pub fn inverse_transform(&self, z: VR2D) -> Result<R2D, ErrorsJSL> {
27        self.check_width(z)?;
28        Ok(R2D::from_shape_fn(z.dim(), |(i, j)| z[[i, j]] * self.scale[j] + self.mean[j]))
29    }
30    fn check_width(&self, x: VR2D) -> Result<(), ErrorsJSL> {
31        if self.mean.is_empty() {
32            return Err(ErrorsJSL::Misconfiguration("The scaler has not been fitted."));
33        }
34        if x.ncols() != self.mean.len() {
35            return Err(ErrorsJSL::IncompatibleArraySizes((x.ncols(), self.mean.len())));
36        }
37        Ok(())
38    }
39}
40
41impl Transformer for StandardScaler {
42    fn fit(&mut self, x: VR2D) -> Result<(), ErrorsJSL> {
43        check_features(x)?;
44        let n = x.nrows() as f64;
45        self.mean = x.columns().into_iter().map(|c| c.sum() / n).collect();
46        self.scale = x
47            .columns()
48            .into_iter()
49            .zip(&self.mean)
50            .map(|(c, &m)| {
51                let sd = (c.iter().map(|v| (v - m) * (v - m)).sum::<f64>() / n).sqrt();
52                if sd > 1e-12 { sd } else { 1.0 }
53            })
54            .collect();
55        Ok(())
56    }
57    fn transform(&self, x: VR2D) -> Result<R2D, ErrorsJSL> {
58        self.check_width(x)?;
59        Ok(R2D::from_shape_fn(x.dim(), |(i, j)| (x[[i, j]] - self.mean[j]) / self.scale[j]))
60    }
61}
62
63/// Rescales each column linearly onto `[0, 1]` (constant columns map to 0).
64#[derive(Debug, Clone, Default)]
65pub struct MinMaxScaler {
66    min: Vec<f64>,
67    range: Vec<f64>,
68}
69
70impl MinMaxScaler {
71    pub fn new() -> Self {
72        Self::default()
73    }
74}
75
76impl Transformer for MinMaxScaler {
77    fn fit(&mut self, x: VR2D) -> Result<(), ErrorsJSL> {
78        check_features(x)?;
79        self.min = x.columns().into_iter().map(|c| c.iter().copied().fold(f64::INFINITY, f64::min)).collect();
80        self.range = x
81            .columns()
82            .into_iter()
83            .zip(&self.min)
84            .map(|(c, &lo)| {
85                let r = c.iter().copied().fold(f64::NEG_INFINITY, f64::max) - lo;
86                if r > 1e-12 { r } else { 1.0 }
87            })
88            .collect();
89        Ok(())
90    }
91    fn transform(&self, x: VR2D) -> Result<R2D, ErrorsJSL> {
92        if self.min.is_empty() {
93            return Err(ErrorsJSL::Misconfiguration("The scaler has not been fitted."));
94        }
95        if x.ncols() != self.min.len() {
96            return Err(ErrorsJSL::IncompatibleArraySizes((x.ncols(), self.min.len())));
97        }
98        Ok(R2D::from_shape_fn(x.dim(), |(i, j)| (x[[i, j]] - self.min[j]) / self.range[j]))
99    }
100}
101
102/// Shuffles sample indices and splits them into `(train, test)` index lists, with
103/// `test_fraction` of the samples (at least one, and leaving at least one) in the test set.
104pub fn train_test_split(samples: usize, test_fraction: f64, seed: u64) -> Result<(Vec<usize>, Vec<usize>), ErrorsJSL> {
105    if samples < 2 || !(0.0..1.0).contains(&test_fraction) {
106        return Err(ErrorsJSL::InvalidInputRange("Need at least two samples and a test fraction in [0, 1)."));
107    }
108    let mut idx: Vec<usize> = (0..samples).collect();
109    MlRng::new(seed).shuffle(&mut idx);
110    let n_test = ((samples as f64 * test_fraction).round() as usize).clamp(1, samples - 1);
111    let test = idx.split_off(samples - n_test);
112    Ok((idx, test))
113}
114
115/// Selects rows of a matrix.
116pub fn select_rows(x: VR2D, indices: &[usize]) -> R2D {
117    R2D::from_shape_fn((indices.len(), x.ncols()), |(i, j)| x[[indices[i], j]])
118}
119
120/// Selects entries of a vector.
121pub fn select(y: VR1D, indices: &[usize]) -> R1D {
122    R1D::from_iter(indices.iter().map(|&i| y[i]))
123}
124
125/// Selects entries of a label slice.
126pub fn select_labels(labels: &[usize], indices: &[usize]) -> Vec<usize> {
127    indices.iter().map(|&i| labels[i]).collect()
128}
129
130/// Polynomial feature expansion of a single column up to `degree` (columns `x, x², ..., x^degree`).
131pub fn polynomial_features(x: VR2D, degree: usize) -> Result<R2D, ErrorsJSL> {
132    if x.ncols() != 1 || degree == 0 {
133        return Err(ErrorsJSL::InvalidInputRange("Polynomial expansion needs one input column and degree >= 1."));
134    }
135    Ok(R2D::from_shape_fn((x.nrows(), degree), |(i, j)| x[[i, 0]].powi(j as i32 + 1)))
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141    use ndarray::arr2;
142
143    #[test]
144    fn scalers_round_trip_and_normalise() {
145        let x = arr2(&[[1.0, 10.0, 5.0], [2.0, 20.0, 5.0], [3.0, 60.0, 5.0]]);
146        let mut s = StandardScaler::new();
147        let z = s.fit_transform(x.view()).unwrap();
148        for c in 0..2 {
149            let col = z.column(c);
150            assert!(col.sum().abs() < 1e-12 && (col.iter().map(|v| v * v).sum::<f64>() / 3.0 - 1.0).abs() < 1e-12);
151        }
152        assert!(z.column(2).iter().all(|v| *v == 0.0)); // constant column only centred
153        let back = s.inverse_transform(z.view()).unwrap();
154        assert!(back.iter().zip(x.iter()).all(|(a, b)| (a - b).abs() < 1e-12));
155        let mut m = MinMaxScaler::new();
156        let u = m.fit_transform(x.view()).unwrap();
157        assert_eq!((u[[0, 1]], u[[2, 1]], u[[1, 2]]), (0.0, 1.0, 0.0));
158        assert!(StandardScaler::new().transform(x.view()).is_err());
159        assert!(s.transform(arr2(&[[1.0]]).view()).is_err());
160    }
161
162    #[test]
163    fn splitting_and_selection() {
164        let (train, test) = train_test_split(10, 0.3, 1).unwrap();
165        assert_eq!((train.len(), test.len()), (7, 3));
166        let mut all: Vec<usize> = train.iter().chain(&test).copied().collect();
167        all.sort_unstable();
168        assert_eq!(all, (0..10).collect::<Vec<_>>());
169        assert_eq!(train_test_split(10, 0.3, 1).unwrap(), (train, test)); // deterministic
170        assert!(train_test_split(1, 0.5, 1).is_err() && train_test_split(10, 1.0, 1).is_err());
171        let x = arr2(&[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]);
172        assert_eq!(select_rows(x.view(), &[2, 0]), arr2(&[[5.0, 6.0], [1.0, 2.0]]));
173        assert_eq!(select_labels(&[7, 8, 9], &[2, 2, 0]), vec![9, 9, 7]);
174        let p = polynomial_features(arr2(&[[2.0], [3.0]]).view(), 3).unwrap();
175        assert_eq!(p, arr2(&[[2.0, 4.0, 8.0], [3.0, 9.0, 27.0]]));
176        assert!(polynomial_features(x.view(), 2).is_err());
177    }
178}