Skip to main content

mlprep_train_test_split/
train_test_split.rs

1//! # Companion example: deterministic train/test split (matten-mlprep)
2//!
3//! Run: cargo run -p matten-mlprep --example mlprep_train_test_split
4//!
5//! ## What this shows
6//! Splitting a `[samples, features]` matrix into train and test parts by an
7//! ordered fraction.
8//!
9//! ## Teaching points
10//! - rows are samples; the split keeps the first fraction as train, the rest as test;
11//! - it is deterministic and ordered — no shuffling, no hidden randomness, no seed;
12//! - shuffling, if wanted, is the caller's responsibility before splitting.
13
14use matten::Tensor;
15use matten_mlprep::train_test_split;
16
17fn main() {
18    // 5 samples, 2 features: rows 0..=4.
19    let x = Tensor::new((0..10).map(|v| v as f64).collect(), &[5, 2]);
20    let (train, test) = train_test_split(&x, 0.6).expect("valid split"); // 3 / 2
21    println!("train {:?}: {:?}", train.shape(), train.as_slice());
22    println!("test  {:?}: {:?}", test.shape(), test.as_slice());
23
24    // Deterministic ordered split: first 3 rows -> train, last 2 rows -> test.
25    assert_eq!(train.shape(), &[3, 2]);
26    assert_eq!(test.shape(), &[2, 2]);
27    assert_eq!(train.as_slice(), &[0.0, 1.0, 2.0, 3.0, 4.0, 5.0]);
28    assert_eq!(test.as_slice(), &[6.0, 7.0, 8.0, 9.0]);
29    println!("train_test_split: OK");
30}