Skip to main content

mlprep_train_test_split_seeded/
train_test_split_seeded.rs

1//! # Companion example: seeded, shuffled train/test split (matten-mlprep, RFC-077)
2//!
3//! Run: cargo run -p matten-mlprep --example mlprep_train_test_split_seeded
4//!
5//! ## What this shows
6//! Splitting a `[samples, features]` matrix into train and test parts by a
7//! seeded, shuffled partition — unlike [`train_test_split`], which is ordered.
8//!
9//! ## Teaching points
10//! - `n_train = floor(n_rows * train_ratio)`, identical to the ordered split;
11//! - row order is determined by a Fisher-Yates shuffle seeded from `seed`;
12//! - the same `(x, train_ratio, seed)` always reproduces the same split.
13
14use matten::Tensor;
15use matten_mlprep::train_test_split_seeded;
16
17fn main() {
18    let x = Tensor::new(vec![10.0, 20.0, 30.0, 40.0, 50.0], &[5, 1]);
19    let (train, test) = train_test_split_seeded(&x, 0.6, 7).expect("valid split"); // 3 / 2
20    println!("train {:?}: {:?}", train.shape(), train.as_slice());
21    println!("test  {:?}: {:?}", test.shape(), test.as_slice());
22
23    assert_eq!(train.shape(), &[3, 1]);
24    assert_eq!(test.shape(), &[2, 1]);
25
26    // Re-running with the same seed reproduces the exact same split.
27    let (train2, test2) = train_test_split_seeded(&x, 0.6, 7).expect("valid split");
28    assert_eq!(train.as_slice(), train2.as_slice());
29    assert_eq!(test.as_slice(), test2.as_slice());
30    println!("same seed -> reproduced split: OK");
31
32    // A different seed shuffles differently.
33    let (train3, _) = train_test_split_seeded(&x, 0.6, 8).expect("valid split");
34    println!(
35        "different seed -> train {:?}: {:?}",
36        train3.shape(),
37        train3.as_slice()
38    );
39
40    println!("train_test_split_seeded: OK");
41}