ferricml 0.2.1

A lean, pure-Rust toolkit for classical machine learning
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
//! Deterministic dense standardization.

use crate::api::{Capabilities, Estimator, HasCapabilities, HasParams, ModelError, Transformer};
use crate::artifact::{ArtifactError, STANDARD_SCALER_ARTIFACT_KIND, StageArtifact};
use crate::data::{MatrixView, SampleWeights};

use super::scaling::{
    BASE_PAYLOAD_VERSION, ScalerHeader, ScalerParameters, decode_flag, decode_scaler_artifact,
    encode_scaler_artifact, inverse_transform_allocating, substituted_divisor,
    transform_preflighted, validate_inverse_request, validate_transform_request,
};

/// Parameters for [`StandardScaler`].
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StandardScalerParams {
    with_mean: bool,
    with_std: bool,
}

impl Default for StandardScalerParams {
    fn default() -> Self {
        Self {
            with_mean: true,
            with_std: true,
        }
    }
}

impl StandardScalerParams {
    /// Enables or disables centering during transformation.
    #[must_use]
    pub fn with_mean(mut self, with_mean: bool) -> Self {
        self.with_mean = with_mean;
        self
    }

    /// Enables or disables population-standard-deviation scaling.
    #[must_use]
    pub fn with_std(mut self, with_std: bool) -> Self {
        self.with_std = with_std;
        self
    }

    /// Returns whether transformed values are centered.
    pub const fn mean_enabled(&self) -> bool {
        self.with_mean
    }

    /// Returns whether transformed values are divided by fitted scales.
    pub const fn std_enabled(&self) -> bool {
        self.with_std
    }
}

/// Fitted per-feature population standardization state.
///
/// Each column is centred on its fitted mean and divided by its fitted
/// population standard deviation, so a transformed column has mean zero and
/// unit scale. This is what a penalized linear model needs in front of it:
/// without it, a feature's units decide how strongly the penalty hits it.
///
/// ```
/// use ferricml::data::DenseMatrix;
/// use ferricml::preprocessing::{StandardScaler, StandardScalerParams};
///
/// // One column in metres, one in millimetres — a thousandfold difference.
/// let data = DenseMatrix::new(
///     vec![1.0, 1000.0, 2.0, 2000.0, 3.0, 3000.0, 4.0, 4000.0],
///     4,
///     2,
/// )?;
///
/// let scaler = StandardScaler::fit(&data.as_view(), StandardScalerParams::default())?;
/// let scaled = scaler.transform(&data.as_view())?;
///
/// // After scaling the two columns are identical: the units are gone.
/// for row in 0..4 {
///     let left = scaled.get(row, 0).expect("in bounds");
///     let right = scaled.get(row, 1).expect("in bounds");
///     assert!((left - right).abs() < 1e-5);
/// }
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// A constant column has no spread to divide by. It keeps a divisor of exactly
/// one rather than producing a non-finite value, so a constant feature survives
/// as a constant:
///
/// ```
/// use ferricml::data::DenseMatrix;
/// use ferricml::preprocessing::{StandardScaler, StandardScalerParams};
///
/// let data = DenseMatrix::new(vec![5.0, 5.0, 5.0, 5.0], 4, 1)?;
/// let scaler = StandardScaler::fit(&data.as_view(), StandardScalerParams::default())?;
///
/// let scaled = scaler.transform(&data.as_view())?;
/// assert!(scaled.as_slice().iter().all(|value| value.is_finite()));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct StandardScaler {
    n_features_in: usize,
    params: StandardScalerParams,
    means: Vec<f64>,
    variances: Vec<f64>,
    scales: Vec<f64>,
}

impl StandardScaler {
    /// Fits unweighted population statistics in fixed row order.
    pub fn fit(data: &MatrixView<'_>, params: StandardScalerParams) -> Result<Self, ModelError> {
        Self::fit_internal(data, None, params)
    }

    /// Fits weighted population statistics in fixed row order.
    pub fn fit_weighted(
        data: &MatrixView<'_>,
        sample_weights: &SampleWeights,
        params: StandardScalerParams,
    ) -> Result<Self, ModelError> {
        Self::fit_internal(data, Some(sample_weights), params)
    }

    fn fit_internal(
        data: &MatrixView<'_>,
        sample_weights: Option<&SampleWeights>,
        params: StandardScalerParams,
    ) -> Result<Self, ModelError> {
        if let Some(weights) = sample_weights
            && weights.len() != data.rows()
        {
            return Err(ModelError::SampleWeightLength {
                rows: data.rows(),
                weights: weights.len(),
            });
        }

        let columns = data.columns();
        let total_weight = sample_weights
            .map(SampleWeights::total)
            .unwrap_or(data.rows() as f64);
        let mut means = vec![0.0_f64; columns];
        for (row_index, row) in data.iter_rows().enumerate() {
            let weight = sample_weights
                .map(|weights| f64::from(weights.as_slice()[row_index]))
                .unwrap_or(1.0);
            for (mean, &value) in means.iter_mut().zip(row) {
                *mean += weight * f64::from(value);
            }
        }
        for mean in &mut means {
            *mean /= total_weight;
        }

        let mut variances = vec![0.0_f64; columns];
        for (row_index, row) in data.iter_rows().enumerate() {
            let weight = sample_weights
                .map(|weights| f64::from(weights.as_slice()[row_index]))
                .unwrap_or(1.0);
            for ((variance, &mean), &value) in variances.iter_mut().zip(&means).zip(row) {
                let difference = f64::from(value) - mean;
                *variance += weight * difference * difference;
            }
        }
        for variance in &mut variances {
            *variance /= total_weight;
        }
        // A zero-variance column keeps a divisor of one through the crate-wide
        // degeneracy rule; the square root is what is particular to
        // standardization. Substituting before the root rather than after is
        // the same value either way, since `1.0.sqrt()` is `1.0`.
        let scales = variances
            .iter()
            .map(|&variance| substituted_divisor(variance).sqrt())
            .collect();

        Ok(Self {
            n_features_in: columns,
            params,
            means,
            variances,
            scales,
        })
    }

    /// Returns fitted feature means as `f64` values.
    pub fn means(&self) -> &[f64] {
        &self.means
    }

    /// Returns fitted population variances as `f64` values.
    pub fn variances(&self) -> &[f64] {
        &self.variances
    }

    /// Returns fitted standard-deviation divisors; constant columns use one.
    pub fn scales(&self) -> &[f64] {
        &self.scales
    }

    /// Returns the fitted input width.
    pub const fn n_features_in(&self) -> usize {
        self.n_features_in
    }

    /// Returns the fitted output width.
    pub const fn n_features_out(&self) -> usize {
        self.n_features_in
    }

    /// Returns the exact transformation parameters.
    pub const fn get_params(&self) -> &StandardScalerParams {
        &self.params
    }

    /// Transforms a batch into caller-owned row-major storage.
    pub fn transform_into<'output>(
        &self,
        data: &MatrixView<'_>,
        output: &'output mut [f32],
    ) -> Result<MatrixView<'output>, ModelError> {
        <Self as Transformer>::transform_into(self, data, output)
    }

    /// Transforms a batch into a newly allocated dense matrix.
    pub fn transform(&self, data: &MatrixView<'_>) -> Result<crate::data::DenseMatrix, ModelError> {
        <Self as Transformer>::transform(self, data)
    }

    /// Undoes [`StandardScaler::transform`] into caller-owned storage.
    ///
    /// The inverse of `(x - mean) / scale` is `x * scale + mean`, applied only
    /// through the toggles that were enabled at fit time.
    ///
    /// # Exactness
    ///
    /// The round trip is **exact by construction** only when both statistics
    /// are disabled, and on a degenerate column whose divisor was substituted
    /// to one. Everywhere else it is exact only when the arithmetic happens to
    /// be: dividing by a scale and multiplying back is not an identity in
    /// floating point, and neither is subtracting a mean and adding it back.
    /// Callers needing an exact recovery keep the original values.
    pub fn inverse_transform_into<'output>(
        &self,
        data: &MatrixView<'_>,
        output: &'output mut [f32],
    ) -> Result<MatrixView<'output>, ModelError> {
        validate_inverse_request(self.n_features_in, data, output)?;
        match (self.params.with_mean, self.params.with_std) {
            (false, false) => transform_preflighted(data, output, |value, _| value),
            (true, false) => transform_preflighted(data, output, |value, column| {
                (f64::from(value) + self.means[column]) as f32
            }),
            (false, true) => transform_preflighted(data, output, |value, column| {
                (f64::from(value) * self.scales[column]) as f32
            }),
            (true, true) => transform_preflighted(data, output, |value, column| {
                (f64::from(value) * self.scales[column] + self.means[column]) as f32
            }),
        }
    }

    /// Undoes [`StandardScaler::transform`], allocating the output matrix.
    pub fn inverse_transform(
        &self,
        data: &MatrixView<'_>,
    ) -> Result<crate::data::DenseMatrix, ModelError> {
        inverse_transform_allocating(self.n_features_in, data, |batch, output| {
            self.inverse_transform_into(batch, output).map(|_| ())
        })
    }

    #[cfg(test)]
    fn transformed_value(&self, value: f32, column: usize) -> f32 {
        let mut transformed = f64::from(value);
        if self.params.with_mean {
            transformed -= self.means[column];
        }
        if self.params.with_std {
            transformed /= self.scales[column];
        }
        transformed as f32
    }
}

impl StageArtifact for StandardScaler {
    const ARTIFACT_KIND: u16 = STANDARD_SCALER_ARTIFACT_KIND;

    /// Encodes fitted scaling state with explicit input and transformed schemas.
    fn to_artifact(
        &self,
        input_schema: [u8; 32],
        transformed_schema: [u8; 32],
    ) -> Result<Vec<u8>, ArtifactError> {
        encode_scaler_artifact(
            Self::ARTIFACT_KIND,
            input_schema,
            transformed_schema,
            self.n_features_in,
            ScalerParameters {
                version: BASE_PAYLOAD_VERSION,
                flags: &[
                    u32::from(self.params.with_mean),
                    u32::from(self.params.with_std),
                ],
                reals: &[],
            },
            3,
            |feature, state| {
                state.f64(self.means[feature]);
                state.f64(self.variances[feature]);
                state.f64(self.scales[feature]);
            },
        )
    }

    /// Decodes fitted scaling state after checking both schemas.
    fn from_artifact(
        bytes: &[u8],
        input_schema: [u8; 32],
        transformed_schema: [u8; 32],
    ) -> Result<Self, ArtifactError> {
        let ScalerHeader {
            n_features_in,
            flags,
            mut state,
            ..
        } = decode_scaler_artifact(
            bytes,
            Self::ARTIFACT_KIND,
            input_schema,
            transformed_schema,
            BASE_PAYLOAD_VERSION,
            2,
            0,
        )?;
        let with_mean = decode_flag(flags[0])?;
        let with_std = decode_flag(flags[1])?;
        // Three `f64` fields per feature: the reservation is clamped to the
        // bytes actually present, never to the declared width alone.
        let capacity = state.bounded_capacity(n_features_in, 3 * 8);
        let mut means = Vec::with_capacity(capacity);
        let mut variances = Vec::with_capacity(capacity);
        let mut scales = Vec::with_capacity(capacity);
        for _ in 0..n_features_in {
            let mean = state.f64()?;
            let variance = state.f64()?;
            let scale = state.f64()?;
            if !mean.is_finite()
                || !variance.is_finite()
                || variance < 0.0
                || !scale.is_finite()
                || scale <= 0.0
                || (variance == 0.0 && scale != 1.0)
                || (variance > 0.0 && scale != variance.sqrt())
            {
                return Err(ArtifactError::InvalidPayload);
            }
            means.push(mean);
            variances.push(variance);
            scales.push(scale);
        }
        if !state.is_empty() {
            return Err(ArtifactError::TrailingBytes);
        }
        Ok(Self {
            n_features_in,
            params: StandardScalerParams {
                with_mean,
                with_std,
            },
            means,
            variances,
            scales,
        })
    }
}

impl Estimator for StandardScaler {
    fn n_features_in(&self) -> usize {
        self.n_features_in
    }
}

/// Weighted fitting and persistence, and it is the *only* scaler that declares
/// the first.
///
/// A mean and a variance are weighted sums, so a per-sample weight has a
/// well-defined effect on both and the weighted fit is the same formula on
/// reweighted moments. Its order-statistic siblings — `MaxAbsScaler`,
/// `MinMaxScaler`, `RobustScaler` — cannot say that, which is why the field
/// differs across otherwise identically shaped transformers. The classifier
/// fields have no meaning for a transformer at all.
impl HasCapabilities for StandardScaler {
    const CAPABILITIES: Capabilities = Capabilities::NONE
        .with_sample_weights(true)
        .with_artifact(true);
}

impl HasParams for StandardScaler {
    type Params = StandardScalerParams;

    fn get_params(&self) -> &Self::Params {
        &self.params
    }
}

impl Transformer for StandardScaler {
    fn n_features_out(&self) -> usize {
        self.n_features_in
    }

    fn transform_into<'output>(
        &self,
        data: &MatrixView<'_>,
        output: &'output mut [f32],
    ) -> Result<MatrixView<'output>, ModelError> {
        validate_transform_request(self.n_features_in, data, output)?;

        match (self.params.with_mean, self.params.with_std) {
            (false, false) => transform_preflighted(data, output, |value, _| value),
            (true, false) => transform_preflighted(data, output, |value, column| {
                (f64::from(value) - self.means[column]) as f32
            }),
            (false, true) => transform_preflighted(data, output, |value, column| {
                (f64::from(value) / self.scales[column]) as f32
            }),
            (true, true) => transform_preflighted(data, output, |value, column| {
                ((f64::from(value) - self.means[column]) / self.scales[column]) as f32
            }),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data::DenseMatrix;

    fn matrix() -> DenseMatrix {
        DenseMatrix::new(vec![1.0, 2.0, 5.0, 3.0, 4.0, 5.0, 5.0, 6.0, 5.0], 3, 3).unwrap()
    }

    fn legacy_transform(scaler: &StandardScaler, data: &MatrixView<'_>) -> Vec<f32> {
        data.as_slice()
            .iter()
            .enumerate()
            .map(|(index, &value)| scaler.transformed_value(value, index % data.columns()))
            .collect()
    }

    #[test]
    fn fits_population_statistics_and_constant_scale() {
        let scaler =
            StandardScaler::fit(&matrix().as_view(), StandardScalerParams::default()).unwrap();
        assert_eq!(scaler.means(), &[3.0, 4.0, 5.0]);
        assert_eq!(scaler.variances(), &[8.0 / 3.0, 8.0 / 3.0, 0.0]);
        assert_eq!(scaler.scales()[2], 1.0);
        let transformed = scaler.transform(&matrix().as_view()).unwrap();
        assert_eq!(transformed.get(1, 0), Some(0.0));
        assert_eq!(transformed.get(0, 2), Some(0.0));
    }

    #[test]
    fn weighted_statistics_and_parameter_toggles_are_deterministic() {
        let weights = SampleWeights::new(vec![1.0, 2.0, 1.0]).unwrap();
        let params = StandardScalerParams::default()
            .with_mean(false)
            .with_std(true);
        let first =
            StandardScaler::fit_weighted(&matrix().as_view(), &weights, params.clone()).unwrap();
        let second = StandardScaler::fit_weighted(&matrix().as_view(), &weights, params).unwrap();
        assert_eq!(first, second);
        assert_eq!(first.means(), &[3.0, 4.0, 5.0]);
        assert_eq!(first.variances(), &[2.0, 2.0, 0.0]);
        assert_eq!(
            first.transform(&matrix().as_view()).unwrap().get(0, 0),
            Some(1.0 / 2.0_f32.sqrt())
        );
    }

    #[test]
    fn every_transform_mode_matches_the_legacy_bit_pattern() {
        let data = matrix();
        for with_mean in [false, true] {
            for with_std in [false, true] {
                let scaler = StandardScaler::fit(
                    &data.as_view(),
                    StandardScalerParams::default()
                        .with_mean(with_mean)
                        .with_std(with_std),
                )
                .unwrap();
                let expected = legacy_transform(&scaler, &data.as_view());
                let actual = scaler.transform(&data.as_view()).unwrap();
                assert_eq!(
                    actual
                        .as_slice()
                        .iter()
                        .map(|value| value.to_bits())
                        .collect::<Vec<_>>(),
                    expected
                        .iter()
                        .map(|value| value.to_bits())
                        .collect::<Vec<_>>()
                );
            }
        }
    }

    #[test]
    fn validates_workspace_before_writing() {
        let scaler =
            StandardScaler::fit(&matrix().as_view(), StandardScalerParams::default()).unwrap();
        let mut output = [91.0; 8];
        assert_eq!(
            scaler
                .transform_into(&matrix().as_view(), &mut output)
                .unwrap_err(),
            ModelError::OutputLength {
                expected: 9,
                actual: 8
            }
        );
        assert_eq!(output, [91.0; 8]);
    }

    #[test]
    fn near_constant_columns_are_scaled_but_overflow_is_reported_before_writes() {
        let near = DenseMatrix::new(vec![1.0, 1.0 + f32::EPSILON], 2, 1).unwrap();
        let scaler = StandardScaler::fit(&near.as_view(), StandardScalerParams::default()).unwrap();
        assert!(scaler.variances()[0] > 0.0);
        assert_ne!(scaler.scales()[0], 1.0);

        let extreme = DenseMatrix::new(vec![f32::MAX], 1, 1).unwrap();
        let mut output = [73.0];
        assert_eq!(
            scaler
                .transform_into(&extreme.as_view(), &mut output)
                .unwrap_err(),
            ModelError::NonFiniteTransform { row: 0, column: 0 }
        );
        assert_eq!(output, [73.0]);
    }

    #[test]
    fn overflow_reports_the_first_row_major_location_without_partial_writes() {
        let fitted =
            DenseMatrix::new(vec![1.0, 1.0, 1.0 + f32::EPSILON, 1.0 + f32::EPSILON], 2, 2).unwrap();
        let scaler =
            StandardScaler::fit(&fitted.as_view(), StandardScalerParams::default()).unwrap();
        let extreme = DenseMatrix::new(vec![1.0, 1.0, 1.0, f32::MAX], 2, 2).unwrap();
        let mut output = [73.0; 4];
        assert_eq!(
            scaler
                .transform_into(&extreme.as_view(), &mut output)
                .unwrap_err(),
            ModelError::NonFiniteTransform { row: 1, column: 1 }
        );
        assert_eq!(output, [73.0; 4]);
    }

    #[test]
    fn unsafe_extrema_fall_back_to_the_first_row_major_error() {
        let fitted =
            DenseMatrix::new(vec![1.0, 1.0, 1.0 + f32::EPSILON, 1.0 + f32::EPSILON], 2, 2).unwrap();
        let scaler =
            StandardScaler::fit(&fitted.as_view(), StandardScalerParams::default()).unwrap();
        let extreme = DenseMatrix::new(vec![1.0, f32::MAX, f32::MAX, 1.0], 2, 2).unwrap();
        let mut output = [41.0; 4];
        assert_eq!(
            scaler
                .transform_into(&extreme.as_view(), &mut output)
                .unwrap_err(),
            ModelError::NonFiniteTransform { row: 0, column: 1 }
        );
        assert_eq!(output, [41.0; 4]);
    }

    #[test]
    fn the_inverse_round_trips_within_a_bounded_envelope_and_exactly_where_promised() {
        let data = matrix();
        let base = StandardScalerParams::default();

        // Exact by construction: nothing is removed.
        let identity = StandardScaler::fit(
            &data.as_view(),
            base.clone().with_mean(false).with_std(false),
        )
        .unwrap();
        let transformed = identity.transform(&data.as_view()).unwrap();
        assert_eq!(
            identity
                .inverse_transform(&transformed.as_view())
                .unwrap()
                .as_slice(),
            data.as_slice()
        );

        // General case: a bound, not an identity.
        let scaler = StandardScaler::fit(&data.as_view(), base).unwrap();
        let transformed = scaler.transform(&data.as_view()).unwrap();
        let recovered = scaler.inverse_transform(&transformed.as_view()).unwrap();
        for (original, recovered) in data.as_slice().iter().zip(recovered.as_slice()) {
            let tolerance = 8.0 * f32::EPSILON * original.abs().max(1.0);
            assert!(
                (original - recovered).abs() <= tolerance,
                "{original} recovered as {recovered}"
            );
        }

        // Out-of-sample rows invert too: the inverse is a map, not a lookup.
        let unseen = DenseMatrix::new(vec![9.0, -4.0, 0.5], 1, 3).unwrap();
        let recovered = scaler.inverse_transform(&unseen.as_view()).unwrap();
        let back = scaler.transform(&recovered.as_view()).unwrap();
        for (original, back) in unseen.as_slice().iter().zip(back.as_slice()) {
            assert!((original - back).abs() <= 8.0 * f32::EPSILON * original.abs().max(1.0));
        }

        let mut short = [91.0; 8];
        assert_eq!(
            scaler
                .inverse_transform_into(&data.as_view(), &mut short)
                .unwrap_err(),
            ModelError::OutputLength {
                expected: 9,
                actual: 8
            }
        );
        assert_eq!(short, [91.0; 8]);
    }

    #[test]
    fn artifact_is_deterministic_and_schema_bound() {
        let scaler =
            StandardScaler::fit(&matrix().as_view(), StandardScalerParams::default()).unwrap();
        let bytes = scaler.to_artifact([1; 32], [2; 32]).unwrap();
        assert_eq!(bytes, scaler.to_artifact([1; 32], [2; 32]).unwrap());
        assert_eq!(
            StandardScaler::from_artifact(&bytes, [1; 32], [2; 32]).unwrap(),
            scaler
        );
        assert_eq!(
            StandardScaler::from_artifact(&bytes, [3; 32], [2; 32]).unwrap_err(),
            ArtifactError::FeatureSchemaMismatch
        );
    }
}