Skip to main content

mlprep_standardize_columns/
standardize_columns.rs

1//! # Companion example: standardize feature columns (matten-mlprep)
2//!
3//! Run: cargo run -p matten-mlprep --example mlprep_standardize_columns
4//!
5//! ## What this shows
6//! Standardizing each feature column of a `[samples, features]` matrix to zero
7//! mean and unit standard deviation (the z-score).
8//!
9//! ## Teaching points
10//! - rows are samples, columns are features;
11//! - the transform is deterministic — no randomness and no fitted model state;
12//! - `matten-mlprep` is small preprocessing, not an ML training framework.
13
14use matten::Tensor;
15use matten_mlprep::standardize_columns;
16
17fn main() {
18    // 3 samples, 2 features.
19    let x = Tensor::new(vec![1.0, 10.0, 2.0, 20.0, 3.0, 30.0], &[3, 2]);
20    let z = standardize_columns(&x).expect("two non-constant columns");
21    println!("input  shape {:?}: {:?}", x.shape(), x.as_slice());
22    println!("z-score      {:?}: {:?}", z.shape(), z.as_slice());
23
24    // Shape is preserved and each standardized column has (near) zero mean.
25    assert_eq!(z.shape(), x.shape());
26    let zs = z.as_slice();
27    let col0_mean = (zs[0] + zs[2] + zs[4]) / 3.0;
28    let col1_mean = (zs[1] + zs[3] + zs[5]) / 3.0;
29    assert!(col0_mean.abs() < 1e-9 && col1_mean.abs() < 1e-9);
30    println!("standardize_columns: OK");
31}