Skip to main content

lib_jsl_machine_learning/
model_selection.rs

1//! Model selection: k-fold and stratified cross-validation, and grid search over
2//! hyperparameters.
3//!
4//! See the book entry [Cross-validation and grid search](https://jwkunz.github.io/lib_jsl/book/learning/model-selection.html).
5
6use crate::common::{Classifier, MlRng, Regressor};
7use lib_jsl_core::{ErrorsJSL, R1D, R2D, VR1D, VR2D};
8use ndarray::Axis;
9
10/// A train/test split as index lists.
11pub type Split = (Vec<usize>, Vec<usize>);
12
13/// `folds` train/test splits of `0..samples`: every sample is tested exactly once, and fold sizes
14/// differ by at most one. With a seed the samples are shuffled first.
15pub fn k_fold(samples: usize, folds: usize, shuffle_seed: Option<u64>) -> Result<Vec<Split>, ErrorsJSL> {
16    if folds < 2 || folds > samples {
17        return Err(ErrorsJSL::InvalidInputRange("Need 2 <= folds <= samples."));
18    }
19    let mut order: Vec<usize> = (0..samples).collect();
20    if let Some(seed) = shuffle_seed {
21        MlRng::new(seed).shuffle(&mut order);
22    }
23    Ok((0..folds)
24        .map(|f| {
25            let (start, end) = (f * samples / folds, (f + 1) * samples / folds);
26            let test = order[start..end].to_vec();
27            let train = order[..start].iter().chain(&order[end..]).copied().collect();
28            (train, test)
29        })
30        .collect())
31}
32
33/// Stratified k-fold: each class is dealt round-robin across the folds (after a seeded shuffle
34/// within the class), so every fold has nearly the overall class proportions.
35// ANCHOR: stratified
36pub fn stratified_k_fold(labels: &[usize], folds: usize, seed: u64) -> Result<Vec<Split>, ErrorsJSL> {
37    if folds < 2 || folds > labels.len() {
38        return Err(ErrorsJSL::InvalidInputRange("Need 2 <= folds <= samples."));
39    }
40    let classes = labels.iter().max().map_or(0, |m| m + 1);
41    let mut rng = MlRng::new(seed);
42    let mut assignment = vec![0usize; labels.len()];
43    let mut next = 0;
44    for c in 0..classes {
45        let mut members: Vec<usize> = (0..labels.len()).filter(|&i| labels[i] == c).collect();
46        rng.shuffle(&mut members);
47        for i in members {
48            assignment[i] = next % folds;
49            next += 1;
50        }
51    }
52    Ok((0..folds).map(|f| ((0..labels.len()).filter(|&i| assignment[i] != f).collect(), (0..labels.len()).filter(|&i| assignment[i] == f).collect())).collect())
53}
54// ANCHOR_END: stratified
55
56fn rows(x: VR2D, idx: &[usize]) -> R2D {
57    x.select(Axis(0), idx)
58}
59
60/// Scores a regressor on each split: `make` builds a fresh model, which is fitted on the training
61/// rows and scored on the test rows by `score(truth, predicted)`.
62pub fn cross_validate_regressor<M, F, S>(make: F, x: VR2D, y: VR1D, splits: &[Split], score: S) -> Result<Vec<f64>, ErrorsJSL>
63where
64    M: Regressor,
65    F: Fn() -> M,
66    S: Fn(VR1D, VR1D) -> Result<f64, ErrorsJSL>,
67{
68    if x.nrows() != y.len() {
69        return Err(ErrorsJSL::IncompatibleArraySizes((x.nrows(), y.len())));
70    }
71    splits
72        .iter()
73        .map(|(train, test)| {
74            let mut model = make();
75            let ytrain: R1D = train.iter().map(|&i| y[i]).collect();
76            model.fit(rows(x, train).view(), ytrain.view())?;
77            let predicted = model.predict(rows(x, test).view())?;
78            let truth: R1D = test.iter().map(|&i| y[i]).collect();
79            score(truth.view(), predicted.view())
80        })
81        .collect()
82}
83
84/// Scores a classifier on each split (see [`cross_validate_regressor`]).
85pub fn cross_validate_classifier<M, F, S>(make: F, x: VR2D, labels: &[usize], splits: &[Split], score: S) -> Result<Vec<f64>, ErrorsJSL>
86where
87    M: Classifier,
88    F: Fn() -> M,
89    S: Fn(&[usize], &[usize]) -> Result<f64, ErrorsJSL>,
90{
91    if x.nrows() != labels.len() {
92        return Err(ErrorsJSL::IncompatibleArraySizes((x.nrows(), labels.len())));
93    }
94    splits
95        .iter()
96        .map(|(train, test)| {
97            let mut model = make();
98            let ltrain: Vec<usize> = train.iter().map(|&i| labels[i]).collect();
99            model.fit(rows(x, train).view(), &ltrain)?;
100            let predicted = model.predict(rows(x, test).view())?;
101            let truth: Vec<usize> = test.iter().map(|&i| labels[i]).collect();
102            score(&truth, &predicted)
103        })
104        .collect()
105}
106
107/// Every combination of the values on each axis (the Cartesian product), first axis slowest.
108pub fn parameter_grid(axes: &[Vec<f64>]) -> Vec<Vec<f64>> {
109    axes.iter().fold(vec![Vec::new()], |acc, axis| acc.iter().flat_map(|prefix| axis.iter().map(move |&v| [prefix.as_slice(), &[v]].concat())).collect())
110}
111
112/// The outcome of a grid search.
113#[derive(Debug, Clone)]
114#[non_exhaustive]
115pub struct GridSearchResult<P> {
116    pub best: P,
117    pub best_score: f64,
118    /// Every candidate with its score, in the order given.
119    pub scores: Vec<(P, f64)>,
120}
121
122/// Evaluates every candidate (typically by the mean of a cross-validation) and keeps the best,
123/// by largest score with `greater_is_better` or smallest otherwise. Candidates whose evaluation
124/// fails or returns NaN are skipped.
125// ANCHOR: grid_search
126pub fn grid_search<P: Clone, E: Fn(&P) -> Result<f64, ErrorsJSL>>(candidates: &[P], evaluate: E, greater_is_better: bool) -> Result<GridSearchResult<P>, ErrorsJSL> {
127    let scores: Vec<(P, f64)> = candidates.iter().filter_map(|c| evaluate(c).ok().filter(|s| !s.is_nan()).map(|s| (c.clone(), s))).collect();
128    let better = |a: f64, b: f64| if greater_is_better { a > b } else { a < b };
129    let (best, best_score) = scores.iter().fold(None, |acc: Option<(P, f64)>, (p, s)| match acc {
130        Some((_, b)) if !better(*s, b) => acc,
131        _ => Some((p.clone(), *s)),
132    }).ok_or(ErrorsJSL::RuntimeError("No candidate could be evaluated."))?;
133    Ok(GridSearchResult { best, best_score, scores })
134}
135// ANCHOR_END: grid_search
136
137/// The mean of a slice of scores.
138pub fn mean_score(scores: &[f64]) -> f64 {
139    scores.iter().sum::<f64>() / scores.len() as f64
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145    use crate::datasets::{make_moons, make_regression};
146    use crate::metrics::{accuracy, mean_squared_error};
147    use crate::supervised::classification::KNearestNeighbors;
148    use crate::supervised::regression::Ridge;
149
150    #[test]
151    fn folds_partition_the_samples() {
152        let splits = k_fold(23, 5, Some(1)).unwrap();
153        let mut tested: Vec<usize> = splits.iter().flat_map(|(_, t)| t.clone()).collect();
154        tested.sort_unstable();
155        assert_eq!(tested, (0..23).collect::<Vec<_>>());
156        assert!(splits.iter().all(|(train, test)| train.len() + test.len() == 23 && (4..=5).contains(&test.len())));
157        assert!(splits.iter().all(|(train, test)| test.iter().all(|i| !train.contains(i))));
158        // Stratification keeps the 1 : 3 class ratio in every fold.
159        let labels: Vec<usize> = (0..40).map(|i| usize::from(i % 4 != 0)).collect();
160        for (_, test) in stratified_k_fold(&labels, 5, 2).unwrap() {
161            assert_eq!(test.iter().filter(|&&i| labels[i] == 0).count(), 2);
162            assert_eq!(test.len(), 8);
163        }
164        assert!(k_fold(3, 4, None).is_err() && k_fold(3, 1, None).is_err());
165        assert_eq!(parameter_grid(&[vec![1.0, 2.0], vec![10.0, 20.0, 30.0]]).len(), 6);
166        assert_eq!(parameter_grid(&[vec![1.0, 2.0], vec![10.0]])[1], vec![2.0, 10.0]);
167    }
168
169    #[test]
170    fn grid_search_with_cross_validation_tunes_hyperparameters() {
171        // Ridge on noisy linear data: heavy regularisation clearly hurts.
172        let (x, y, _, _) = make_regression(120, 5, 0.5, 3);
173        let splits = k_fold(120, 5, Some(4)).unwrap();
174        let alphas = vec![1e-3, 1e-1, 10.0, 1e3, 1e5];
175        let search = grid_search(&alphas, |&a| Ok(mean_score(&cross_validate_regressor(|| Ridge::new(a), x.view(), y.view(), &splits, mean_squared_error)?)), false).unwrap();
176        assert!(search.best <= 10.0, "{:?}", search.scores);
177        assert!(search.scores.last().unwrap().1 > 10.0 * search.best_score);
178        // k-NN on two moons: k = 1 overfits the noise less than k = 150 underfits.
179        let (xm, lm) = make_moons(300, 0.25, 5);
180        let folds = stratified_k_fold(&lm, 5, 6).unwrap();
181        let ks = vec![1usize, 5, 15, 150];
182        let search = grid_search(&ks, |&k| Ok(mean_score(&cross_validate_classifier(|| KNearestNeighbors::new(k), xm.view(), &lm, &folds, accuracy)?)), true).unwrap();
183        assert!(search.best == 5 || search.best == 15, "{:?}", search.scores);
184        assert!(search.best_score > 0.9 && search.scores[3].1 < search.best_score);
185    }
186}