smartcore 0.6.16

Machine Learning in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
//! # Standard-Scaling For [RealNumber](../../math/num/trait.RealNumber.html) Matricies
//! Transform a data [Matrix](../../linalg/trait.BaseMatrix.html) by removing the mean and scaling to unit variance.
//!
//! ### Usage Example
//! ```
//! use smartcore::api::{Transformer, UnsupervisedEstimator};
//! use smartcore::linalg::basic::matrix::DenseMatrix;
//! use smartcore::preprocessing::numerical;
//! let data = DenseMatrix::from_2d_vec(&vec![
//!     vec![0.0, 0.0],
//!     vec![0.0, 0.0],
//!     vec![1.0, 1.0],
//!     vec![1.0, 1.0],
//! ]).unwrap();
//!
//! let standard_scaler =
//! numerical::StandardScaler::fit(&data, numerical::StandardScalerParameters::default())
//!    .unwrap();
//! let transformed_data = standard_scaler.transform(&data).unwrap();
//! assert_eq!(
//!     transformed_data,
//!     DenseMatrix::from_2d_vec(&vec![
//!         vec![-1.0, -1.0],
//!         vec![-1.0, -1.0],
//!         vec![1.0, 1.0],
//!         vec![1.0, 1.0],
//!     ]).unwrap()
//! );
//! ```
use std::marker::PhantomData;

use crate::api::{Transformer, UnsupervisedEstimator};
use crate::error::{Failed, FailedError};
use crate::linalg::basic::arrays::Array2;
use crate::numbers::basenum::Number;
use crate::numbers::realnum::RealNumber;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Configure Behaviour of `StandardScaler`.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, Copy, Eq, PartialEq)]
#[must_use]
pub struct StandardScalerParameters {
    /// Optionaly adjust mean to be zero.
    with_mean: bool,
    /// Optionally adjust standard-deviation to be one.
    with_std: bool,
}
impl Default for StandardScalerParameters {
    fn default() -> Self {
        StandardScalerParameters {
            with_mean: true,
            with_std: true,
        }
    }
}

/// With the `StandardScaler` data can be adjusted so
/// that every column has a mean of zero and a standard
/// deviation of one. This can improve model training for
/// scaling sensitive models like neural network or nearest
/// neighbors based models.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Clone, Debug, Default, PartialEq)]
pub struct StandardScaler<T: Number + RealNumber> {
    means: Vec<f64>,
    stds: Vec<f64>,
    parameters: StandardScalerParameters,
    _phantom: PhantomData<T>,
}

#[expect(dead_code)]
impl<T: Number + RealNumber> StandardScaler<T> {
    fn new(parameters: StandardScalerParameters) -> Self
    where
        T: Number + RealNumber,
    {
        Self {
            means: vec![],
            stds: vec![],
            parameters: StandardScalerParameters {
                with_mean: parameters.with_mean,
                with_std: parameters.with_std,
            },
            _phantom: PhantomData,
        }
    }
    /// When the mean should be adjusted, the column mean
    /// should be kept. Otherwise, replace it by zero.
    fn adjust_column_mean(&self, mean: f64) -> f64 {
        if self.parameters.with_mean {
            mean
        } else {
            0f64
        }
    }
    /// When the standard-deviation should be adjusted, the column
    /// standard-deviation should be kept. Otherwise, replace it by one.
    fn adjust_column_std(&self, std: f64) -> f64 {
        if self.parameters.with_std {
            ensure_std_valid(std)
        } else {
            1f64
        }
    }
}

/// Make sure the standard deviation is valid. If it is
/// negative or zero, it should replaced by the smallest
/// positive value the type can have. That way we can savely
/// divide the columns with the resulting scalar.
fn ensure_std_valid<T: Number + RealNumber>(value: T) -> T {
    value.max(T::min_positive_value())
}

/// During `fit` the `StandardScaler` computes the column means and standard deviation.
impl<T: Number + RealNumber, M: Array2<T>> UnsupervisedEstimator<M, StandardScalerParameters>
    for StandardScaler<T>
{
    fn fit(x: &M, parameters: StandardScalerParameters) -> Result<Self, Failed>
    where
        T: Number + RealNumber,
        M: Array2<T>,
    {
        Ok(Self {
            means: x.column_mean(),
            stds: x.std_dev(0),
            parameters,
            _phantom: Default::default(),
        })
    }
}

/// During `transform` the `StandardScaler` applies the summary statistics
/// computed during `fit` to set the mean of each column to zero and the
/// standard deviation to one.
impl<T: Number + RealNumber, M: Array2<T>> Transformer<M> for StandardScaler<T> {
    fn transform(&self, x: &M) -> Result<M, Failed> {
        let (nrows, ncols) = x.shape();
        if ncols != self.means.len() {
            return Err(Failed::because(
                FailedError::TransformFailed,
                &format!(
                    "Expected {} columns, but got {} columns instead.",
                    self.means.len(),
                    ncols,
                ),
            ));
        }

        let mut output = M::fill(nrows, ncols, T::zero());
        let col_params: Vec<(T, T)> = (0..ncols)
            .map(|j| {
                let mean = T::from(self.adjust_column_mean(self.means[j])).unwrap();
                let std = T::from(self.adjust_column_std(self.stds[j])).unwrap();
                (mean, std)
            })
            .collect();
        for i in 0..nrows {
            for (j, &(mean, std)) in col_params.iter().enumerate() {
                let val = *x.get((i, j));
                output.set((i, j), (val - mean) / std);
            }
        }
        Ok(output)
    }
}

#[cfg(test)]
mod tests {

    mod helper_functionality {
        use super::super::ensure_std_valid;

        #[test]
        fn negative_value_should_be_replace_with_minimal_positive_value() {
            assert_eq!(ensure_std_valid(-1.0), f64::MIN_POSITIVE)
        }

        #[test]
        fn zero_should_be_replace_with_minimal_positive_value() {
            assert_eq!(ensure_std_valid(0.0), f64::MIN_POSITIVE)
        }
    }
    mod standard_scaler {
        use super::super::{StandardScaler, StandardScalerParameters};
        use crate::api::{Transformer, UnsupervisedEstimator};
        use crate::linalg::basic::arrays::Array2;
        use crate::linalg::basic::matrix::DenseMatrix;

        #[test]
        fn dont_adjust_mean_if_used() {
            assert_eq!(
                (StandardScaler::<f64>::new(StandardScalerParameters {
                    with_mean: true,
                    with_std: true
                }))
                .adjust_column_mean(1.0),
                1.0
            )
        }
        #[test]
        fn replace_mean_with_zero_if_not_used() {
            assert_eq!(
                (StandardScaler::<f64>::new(StandardScalerParameters {
                    with_mean: false,
                    with_std: true
                }))
                .adjust_column_mean(1.0),
                0.0
            )
        }
        #[test]
        fn dont_adjust_std_if_used() {
            assert_eq!(
                (StandardScaler::<f64>::new(StandardScalerParameters {
                    with_mean: true,
                    with_std: true
                }))
                .adjust_column_std(10.0),
                10.0
            )
        }
        #[test]
        fn replace_std_with_one_if_not_used() {
            assert_eq!(
                (StandardScaler::<f64>::new(StandardScalerParameters {
                    with_mean: true,
                    with_std: false
                }))
                .adjust_column_std(10.0),
                1.0
            )
        }

        /// Helper function to apply fit as well as transform at the same time.
        fn fit_transform_with_default_standard_scaler(
            values_to_be_transformed: &DenseMatrix<f64>,
        ) -> DenseMatrix<f64> {
            StandardScaler::fit(
                values_to_be_transformed,
                StandardScalerParameters::default(),
            )
            .unwrap()
            .transform(values_to_be_transformed)
            .unwrap()
        }

        /// Fit transform with random generated values, expected values taken from
        /// sklearn.
        #[test]
        fn fit_transform_random_values() {
            let transformed_values = fit_transform_with_default_standard_scaler(
                &DenseMatrix::from_2d_array(&[
                    &[0.1004222429, 0.2194113576, 0.9310663354, 0.3313593793],
                    &[0.2045493861, 0.1683865411, 0.5071506765, 0.7257355264],
                    &[0.5708488802, 0.1846414616, 0.9590802982, 0.5591871046],
                    &[0.8387612750, 0.5754861361, 0.5537109852, 0.1077646442],
                ])
                .unwrap(),
            );
            println!("{transformed_values}");
            assert!(
                transformed_values.approximate_eq(
                    &DenseMatrix::from_2d_array(&[
                        &[-1.1154020653, -0.4031985330, 0.9284605204, -0.4271473866],
                        &[-0.7615464283, -0.7076698384, -1.1075452562, 1.2632979631],
                        &[0.4832504303, -0.6106747444, 1.0630075435, 0.5494084257],
                        &[1.3936980634, 1.7215431158, -0.8839228078, -1.3855590021],
                    ])
                    .unwrap(),
                    1.0
                )
            )
        }

        /// Test `fit` and `transform` for a column with zero variance.
        #[test]
        fn fit_transform_with_zero_variance() {
            assert_eq!(
                fit_transform_with_default_standard_scaler(
                    &DenseMatrix::from_2d_array(&[&[1.0], &[1.0], &[1.0], &[1.0]]).unwrap()
                ),
                DenseMatrix::from_2d_array(&[&[0.0], &[0.0], &[0.0], &[0.0]]).unwrap(),
                "When scaling values with zero variance, zero is expected as return value"
            )
        }

        /// Test `fit` for columns with nice summary statistics.
        #[test]
        fn fit_for_simple_values() {
            assert_eq!(
                StandardScaler::fit(
                    &DenseMatrix::from_2d_array(&[
                        &[1.0, 1.0, 1.0],
                        &[1.0, 2.0, 5.0],
                        &[1.0, 1.0, 1.0],
                        &[1.0, 2.0, 5.0]
                    ])
                    .unwrap(),
                    StandardScalerParameters::default(),
                ),
                Ok(StandardScaler {
                    means: vec![1.0, 1.5, 3.0],
                    stds: vec![0.0, 0.5, 2.0],
                    parameters: StandardScalerParameters {
                        with_mean: true,
                        with_std: true
                    },
                    _phantom: Default::default(),
                })
            )
        }
        /// Test `fit` for random generated values.
        #[test]
        fn fit_for_random_values() {
            let fitted_scaler = StandardScaler::fit(
                &DenseMatrix::from_2d_array(&[
                    &[0.1004222429, 0.2194113576, 0.9310663354, 0.3313593793],
                    &[0.2045493861, 0.1683865411, 0.5071506765, 0.7257355264],
                    &[0.5708488802, 0.1846414616, 0.9590802982, 0.5591871046],
                    &[0.8387612750, 0.5754861361, 0.5537109852, 0.1077646442],
                ])
                .unwrap(),
                StandardScalerParameters::default(),
            )
            .unwrap();

            assert_eq!(
                fitted_scaler.means,
                vec![0.42864544605, 0.2869813741, 0.737752073825, 0.431011663625],
            );

            assert!(
                &DenseMatrix::<f64>::from_2d_vec(&vec![fitted_scaler.stds])
                    .unwrap()
                    .approximate_eq(
                        &DenseMatrix::from_2d_array(&[&[
                            0.29426447500954,
                            0.16758497615485,
                            0.20820945786863,
                            0.23329718831165
                        ],])
                        .unwrap(),
                        0.00000000000001
                    )
            )
        }

        /// If `with_std` is set to `false` the values should not be
        /// adjusted to have a std of one.
        #[test]
        fn transform_without_std() {
            let standard_scaler = StandardScaler {
                means: vec![1.0, 3.0],
                stds: vec![1.0, 2.0],
                parameters: StandardScalerParameters {
                    with_mean: true,
                    with_std: false,
                },
                _phantom: Default::default(),
            };

            assert_eq!(
                standard_scaler
                    .transform(&DenseMatrix::from_2d_array(&[&[0.0, 2.0], &[2.0, 4.0]]).unwrap()),
                Ok(DenseMatrix::from_2d_array(&[&[-1.0, -1.0], &[1.0, 1.0]]).unwrap())
            )
        }

        /// If `with_mean` is set to `false` the values should not be adjusted
        /// to have a mean of zero.
        #[test]
        fn transform_without_mean() {
            let standard_scaler = StandardScaler {
                means: vec![1.0, 2.0],
                stds: vec![2.0, 3.0],
                parameters: StandardScalerParameters {
                    with_mean: false,
                    with_std: true,
                },
                _phantom: Default::default(),
            };

            assert_eq!(
                standard_scaler
                    .transform(&DenseMatrix::from_2d_array(&[&[0.0, 9.0], &[4.0, 12.0]]).unwrap()),
                Ok(DenseMatrix::from_2d_array(&[&[0.0, 3.0], &[2.0, 4.0]]).unwrap())
            )
        }

        /// Verify transform correctness across all parameter combinations.
        #[test]
        fn transform_all_parameter_combinations() {
            let data = DenseMatrix::from_2d_vec(&vec![
                vec![1.0, 10.0, 100.0],
                vec![2.0, 20.0, 200.0],
                vec![3.0, 30.0, 300.0],
                vec![4.0, 40.0, 400.0],
            ])
            .unwrap();

            // Default: with_mean=true, with_std=true
            // std = population std: sqrt(mean of squared deviations)
            // For [1,2,3,4]: mean=2.5, pop_std = sqrt(5/4) ≈ 1.1180339887
            let scaler = StandardScaler::fit(&data, StandardScalerParameters::default()).unwrap();
            let result = scaler.transform(&data).unwrap();
            let expected = DenseMatrix::from_2d_vec(&vec![
                vec![
                    -1.3416407864998738,
                    -1.3416407864998738,
                    -1.3416407864998738,
                ],
                vec![
                    -0.4472135954999579,
                    -0.4472135954999579,
                    -0.4472135954999579,
                ],
                vec![0.4472135954999579, 0.4472135954999579, 0.4472135954999579],
                vec![1.3416407864998738, 1.3416407864998738, 1.3416407864998738],
            ])
            .unwrap();
            assert!(
                result.approximate_eq(&expected, 1e-10),
                "Default transform failed:\n{result}\nexpected:\n{expected}"
            );

            // with_mean=true, with_std=false
            let scaler = StandardScaler::fit(
                &data,
                StandardScalerParameters {
                    with_mean: true,
                    with_std: false,
                },
            )
            .unwrap();
            let result = scaler.transform(&data).unwrap();
            let expected = DenseMatrix::from_2d_vec(&vec![
                vec![-1.5, -15.0, -150.0],
                vec![-0.5, -5.0, -50.0],
                vec![0.5, 5.0, 50.0],
                vec![1.5, 15.0, 150.0],
            ])
            .unwrap();
            assert!(
                result.approximate_eq(&expected, 1e-10),
                "with_mean=true, with_std=false transform failed:\n{result}\nexpected:\n{expected}"
            );

            // with_mean=false, with_std=true: (x - 0) / std = x / std
            let scaler = StandardScaler::fit(
                &data,
                StandardScalerParameters {
                    with_mean: false,
                    with_std: true,
                },
            )
            .unwrap();
            let result = scaler.transform(&data).unwrap();
            let expected = DenseMatrix::from_2d_vec(&vec![
                vec![0.8944271909999159, 0.8944271909999159, 0.8944271909999159],
                vec![1.7888543819998317, 1.7888543819998317, 1.7888543819998317],
                vec![2.6832815729997477, 2.6832815729997477, 2.6832815729997477],
                vec![3.5777087639996634, 3.5777087639996634, 3.5777087639996634],
            ])
            .unwrap();
            assert!(
                result.approximate_eq(&expected, 1e-10),
                "with_mean=false, with_std=true transform failed:\n{result}\nexpected:\n{expected}"
            );

            // with_mean=false, with_std=false (passthrough)
            let scaler = StandardScaler::fit(
                &data,
                StandardScalerParameters {
                    with_mean: false,
                    with_std: false,
                },
            )
            .unwrap();
            let result = scaler.transform(&data).unwrap();
            assert!(
                result.approximate_eq(&data, 1e-10),
                "with_mean=false, with_std=false should return data unchanged:\n{result}\nexpected:\n{data}"
            );

            // Zero-variance column mixed with normal columns
            let mixed = DenseMatrix::from_2d_vec(&vec![
                vec![1.0, 5.0],
                vec![2.0, 5.0],
                vec![3.0, 5.0],
                vec![4.0, 5.0],
            ])
            .unwrap();
            let scaler = StandardScaler::fit(&mixed, StandardScalerParameters::default()).unwrap();
            let result = scaler.transform(&mixed).unwrap();
            let expected = DenseMatrix::from_2d_vec(&vec![
                vec![-1.3416407864998738, 0.0],
                vec![-0.4472135954999579, 0.0],
                vec![0.4472135954999579, 0.0],
                vec![1.3416407864998738, 0.0],
            ])
            .unwrap();
            assert!(
                result.approximate_eq(&expected, 1e-10),
                "Zero-variance mixed column transform failed:\n{result}\nexpected:\n{expected}"
            );

            // Column count mismatch returns error: scaler expects 2 cols, data has 1
            let narrow = DenseMatrix::from_2d_vec(&vec![vec![1.0]]).unwrap();
            assert!(scaler.transform(&narrow).is_err());
        }

        /// Same as `fit_for_random_values` test, but using a `StandardScaler` that has been
        /// serialized and deserialized.
        #[cfg_attr(
            all(target_arch = "wasm32", not(target_os = "wasi")),
            wasm_bindgen_test::wasm_bindgen_test
        )]
        #[test]
        #[cfg(feature = "serde")]
        fn serde_fit_for_random_values() {
            let fitted_scaler = StandardScaler::fit(
                &DenseMatrix::from_2d_array(&[
                    &[0.1004222429, 0.2194113576, 0.9310663354, 0.3313593793],
                    &[0.2045493861, 0.1683865411, 0.5071506765, 0.7257355264],
                    &[0.5708488802, 0.1846414616, 0.9590802982, 0.5591871046],
                    &[0.8387612750, 0.5754861361, 0.5537109852, 0.1077646442],
                ])
                .unwrap(),
                StandardScalerParameters::default(),
            )
            .unwrap();

            let deserialized_scaler: StandardScaler<f64> =
                serde_json::from_str(&serde_json::to_string(&fitted_scaler).unwrap()).unwrap();

            assert_eq!(
                deserialized_scaler.means,
                vec![0.42864544605, 0.2869813741, 0.737752073825, 0.431011663625],
            );

            assert!(
                &DenseMatrix::from_2d_vec(&vec![deserialized_scaler.stds])
                    .unwrap()
                    .approximate_eq(
                        &DenseMatrix::from_2d_array(&[&[
                            0.29426447500954,
                            0.16758497615485,
                            0.20820945786863,
                            0.23329718831165
                        ],])
                        .unwrap(),
                        0.00000000000001
                    )
            )
        }
    }
}