smartcore 0.7.0

Machine Learning in Rust.
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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
use rand::RngExt;
use std::fmt::Debug;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::error::{Failed, FailedError};
use crate::linalg::basic::arrays::MutArrayView1;
use crate::linalg::basic::arrays::{Array1, Array2};
use crate::numbers::basenum::Number;
use crate::numbers::floatnum::FloatNumber;

use crate::rand_custom::get_rng_impl;
use crate::tree::base_tree::{BaseTree, BaseTreeParameters, Splitter};
use crate::tree::criterion::{Criterion, LeafOutput};

#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone)]
/// Parameters of a base forest.
/// Some parameters here are passed directly into base estimator.
#[must_use]
pub struct BaseForestParameters {
    #[cfg_attr(feature = "serde", serde(default))]
    /// Tree max depth. See [Decision Tree Regressor](../../tree/decision_tree_regressor/index.html)
    pub max_depth: Option<u16>,
    #[cfg_attr(feature = "serde", serde(default))]
    /// The minimum number of samples required to be at a leaf node. See [Decision Tree Regressor](../../tree/decision_tree_regressor/index.html)
    pub min_samples_leaf: usize,
    #[cfg_attr(feature = "serde", serde(default))]
    /// The minimum number of samples required to split an internal node. See [Decision Tree Regressor](../../tree/decision_tree_regressor/index.html)
    pub min_samples_split: usize,
    #[cfg_attr(feature = "serde", serde(default))]
    /// The number of trees in the forest.
    pub n_trees: usize,
    #[cfg_attr(feature = "serde", serde(default))]
    /// Number of random sample of predictors to use as split candidates.
    pub m: Option<usize>,
    #[cfg_attr(feature = "serde", serde(default))]
    /// Whether to keep samples used for tree generation. This is required for OOB prediction.
    pub keep_samples: bool,
    #[cfg_attr(feature = "serde", serde(default))]
    /// Seed used for bootstrap sampling and feature selection for each tree.
    pub seed: u64,
    #[cfg_attr(feature = "serde", serde(default))]
    pub bootstrap: bool,
    #[cfg_attr(feature = "serde", serde(default))]
    pub splitter: Splitter,
}

impl<
    TX: Number + FloatNumber + PartialOrd,
    TY: Number,
    X: Array2<TX>,
    Y: Array1<TY>,
    Out: LeafOutput,
> PartialEq for BaseForest<TX, TY, X, Y, Out>
{
    fn eq(&self, other: &Self) -> bool {
        if self.trees.as_ref().unwrap().len() != other.trees.as_ref().unwrap().len() {
            false
        } else {
            self.trees
                .iter()
                .zip(other.trees.iter())
                .all(|(a, b)| a == b)
        }
    }
}

/// Base forest of decision trees. Out is the type of the leaf values. The criterion is passed to fit.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(
    feature = "serde",
    serde(bound(serialize = "Out: Serialize", deserialize = "Out: Deserialize<'de>"))
)]
#[derive(Debug)]
pub struct BaseForest<
    TX: Number + FloatNumber + PartialOrd,
    TY: Number,
    X: Array2<TX>,
    Y: Array1<TY>,
    Out: LeafOutput,
> {
    trees: Option<Vec<BaseTree<TX, TY, X, Y, Out>>>,
    num_features: Option<usize>,
    samples: Option<Vec<Vec<bool>>>,
}

impl<
    TX: Number + FloatNumber + PartialOrd,
    TY: Number,
    X: Array2<TX>,
    Y: Array1<TY>,
    Out: LeafOutput,
> BaseForest<TX, TY, X, Y, Out>
{
    /// The trees of the forest. Call only after `fit`.
    pub(crate) fn trees(&self) -> &[BaseTree<TX, TY, X, Y, Out>] {
        self.trees.as_ref().unwrap()
    }

    /// For each tree, the rows it used in training. `None` if `keep_samples` was false.
    pub(crate) fn samples(&self) -> Option<&[Vec<bool>]> {
        self.samples.as_deref()
    }

    /// Build a forest of trees from the training set.
    /// * `x` - _NxM_ matrix with _N_ observations and _M_ features in each observation.
    /// * `y` - the target class values
    /// * `sample_weights`: optional sample_weights to use during fitting
    pub fn fit<C: Criterion<Output = Out>>(
        x: &X,
        y: &Y,
        sample_weights: Option<&[f64]>,
        criterion: &C,
        parameters: BaseForestParameters,
    ) -> Result<BaseForest<TX, TY, X, Y, Out>, Failed> {
        let (n_rows, num_attributes) = x.shape();

        if n_rows != y.shape() {
            return Err(Failed::fit("Number of rows in X should = len(y)"));
        }
        if n_rows == 0 || num_attributes == 0 {
            return Err(Failed::because(
                FailedError::ParametersError,
                "Training data must contain at least one sample and one feature.",
            ));
        }

        let mtry = parameters
            .m
            .unwrap_or((num_attributes as f64).sqrt().floor() as usize);

        let mut rng = get_rng_impl(Some(parameters.seed));
        let n_trees = parameters.n_trees;
        let mut trees: Vec<BaseTree<TX, TY, X, Y, Out>> = Vec::with_capacity(n_trees);

        let mut maybe_all_samples: Option<Vec<Vec<bool>>> = Option::None;
        if parameters.keep_samples {
            maybe_all_samples = Some(Vec::with_capacity(n_trees));
        }

        let mut samples: Vec<usize> = (0..n_rows).map(|_| 1).collect();

        let dist = sample_weights
            .map(|weights| {
                rand::distr::weighted::WeightedIndex::new(weights)
                    .map_err(|e| Failed::fit(&e.to_string()))
            })
            .transpose()?;

        // Compute the order of each attribute once
        let mut order: Vec<Vec<usize>> = Vec::with_capacity(num_attributes);

        for i in 0..num_attributes {
            let mut col_i: Vec<TX> = x.get_col(i).iterator(0).copied().collect();
            order.push(col_i.argsort_mut());
        }

        for tree_idx in 0..parameters.n_trees {
            if parameters.bootstrap {
                samples = BaseForest::<TX, TY, X, Y, Out>::sample_with_replacement(
                    n_rows,
                    &mut rng,
                    dist.as_ref(),
                );
            }

            // keep samples is flag is on
            if let Some(ref mut all_samples) = maybe_all_samples {
                all_samples.push(samples.iter().map(|x| *x != 0).collect())
            }

            let params = BaseTreeParameters {
                max_depth: parameters.max_depth,
                min_samples_leaf: parameters.min_samples_leaf,
                min_samples_split: parameters.min_samples_split,
                seed: Some(parameters.seed.wrapping_add(tree_idx as u64)), // give each tree its own fixed seed
                splitter: parameters.splitter,
            };
            // Only use sample weights on base tree if not already applied during bootstrapping
            let sample_weights_for_base_tree = if parameters.bootstrap {
                None
            } else {
                sample_weights
            };
            let tree = BaseTree::fit_weak_learner(
                x,
                y,
                sample_weights_for_base_tree,
                samples.clone(),
                mtry,
                &order,
                criterion,
                params,
            )?;
            trees.push(tree);
        }

        Ok(BaseForest {
            trees: Some(trees),
            num_features: Some(x.shape().1),
            samples: maybe_all_samples,
        })
    }

    fn sample_with_replacement(
        nrows: usize,
        rng: &mut impl rand::Rng,
        distribution: Option<&rand::distr::weighted::WeightedIndex<f64>>,
    ) -> Vec<usize> {
        let mut samples = vec![0; nrows];
        for _ in 0..nrows {
            let xi = match distribution {
                Some(dist) => rng.sample(dist),
                None => rng.random_range(0..nrows),
            };
            samples[xi] += 1;
        }

        samples
    }

    /// Mean of the normalized tree importances, normalized again.
    pub fn compute_feature_importances(&self) -> Result<Vec<f64>, Failed> {
        match (&self.trees, self.num_features) {
            (Some(trees), Some(num_features)) => {
                let mut importances = vec![0.0f64; num_features];
                let mut scratch = vec![0.0f64; num_features];

                for tree in trees {
                    tree.compute_feature_importances(true, &mut scratch);
                    for (i, s) in importances.iter_mut().zip(scratch.iter()) {
                        *i += s;
                    }
                }

                // compute the mean of each feature importance
                let num_trees = trees.len() as f64;
                for i in importances.iter_mut() {
                    *i /= num_trees;
                }

                // normalize once more
                let sum: f64 = importances.iter().sum();
                if sum > 0.0 {
                    for i in importances.iter_mut() {
                        *i /= sum;
                    }
                }

                Ok(importances)
            }
            _ => Err(Failed::predict(
                "'fit' should be called before calling 'compute_feature_importances'",
            )),
        }
    }
}

/// Mean of the tree predictions for each row of `x`.
pub(crate) fn predict_mean<TX, TY, X, Y>(
    forest: &BaseForest<TX, TY, X, Y, f64>,
    x: &X,
) -> Result<Y, Failed>
where
    TX: Number + FloatNumber,
    TY: Number,
    X: Array2<TX>,
    Y: Array1<TY>,
{
    let (n, _) = x.shape();
    let mut result = Y::zeros(n);
    let num_trees = TY::from_usize(forest.trees().len()).unwrap();

    for row in 0..n {
        let mut sum = TY::zero();
        for tree in forest.trees() {
            sum += TY::from_f64(*tree.leaf_output_for_row(x, row)).unwrap();
        }
        result.set(row, sum / num_trees);
    }
    Ok(result)
}

/// Mean of the out-of-bag tree predictions for each row of `x`.
/// `x` is expected to be equal to the dataset used in training.
pub(crate) fn predict_mean_oob<TX, TY, X, Y>(
    forest: &BaseForest<TX, TY, X, Y, f64>,
    x: &X,
) -> Result<Y, Failed>
where
    TX: Number + FloatNumber,
    TY: Number,
    X: Array2<TX>,
    Y: Array1<TY>,
{
    let (n, _) = x.shape();

    let samples = match forest.samples() {
        Some(s) => s,
        None => {
            return Err(Failed::because(
                FailedError::PredictFailed,
                "Need samples=true for OOB predictions.",
            ));
        }
    };

    if samples[0].len() != n {
        return Err(Failed::because(
            FailedError::PredictFailed,
            "Prediction matrix must match matrix used in training for OOB predictions.",
        ));
    }

    let mut result = Y::zeros(n);

    for row in 0..n {
        let mut sum = TY::zero();
        let mut n_trees = 0usize;
        for (tree, in_bag) in forest.trees().iter().zip(samples) {
            if !in_bag[row] {
                sum += TY::from_f64(*tree.leaf_output_for_row(x, row)).unwrap();
                n_trees += 1;
            }
        }
        // TODO: What to do if there are no oob trees?
        result.set(row, sum / TY::from_usize(n_trees).unwrap());
    }

    Ok(result)
}

#[cfg(test)]
mod tests {

    use super::*;
    use crate::linalg::basic::arrays::Array;
    use crate::linalg::basic::matrix::DenseMatrix;
    use crate::tree::criterion::MSECriterion;

    #[test]
    fn test_base_forest_keep_samples() {
        let x = DenseMatrix::from_2d_array(&[&[1.0, 2.0], &[3.0, 4.0], &[5.0, 6.0]]).unwrap();
        let y = vec![1.0, 2.0, 3.0];
        let params = BaseForestParameters {
            max_depth: None,
            min_samples_leaf: 1,
            min_samples_split: 2,
            n_trees: 5,
            m: None,
            keep_samples: true,
            seed: 42,
            bootstrap: true,
            splitter: crate::tree::base_tree::Splitter::Best,
        };
        let regressor = BaseForest::fit(&x, &y, None, &MSECriterion, params).unwrap();
        assert_eq!(regressor.trees.unwrap().len(), 5);
        assert!(regressor.samples.is_some());
    }

    #[test]
    fn test_fit_on_empty_data_returns_error() {
        // 2 rows x 2 features — values are arbitrary; only the empty-row case is under test
        let full = DenseMatrix::from_2d_vec(&vec![vec![1.0, 2.0], vec![3.0, 4.0]]).unwrap();
        let empty = full.take(&[] as &[usize], 0);
        assert_eq!(empty.shape(), (0, 2));

        let y: Vec<f64> = vec![];
        let result = BaseForest::fit(
            &empty,
            &y,
            None,
            &MSECriterion,
            BaseForestParameters {
                max_depth: None,
                min_samples_leaf: 1,
                min_samples_split: 2,
                n_trees: 5,
                m: None,
                keep_samples: false,
                seed: 0,
                bootstrap: true,
                splitter: crate::tree::base_tree::Splitter::Best,
            },
        );
        assert!(result.is_err());
        assert_eq!(result.err().unwrap().error(), FailedError::ParametersError);
    }

    #[test]
    fn test_fit_on_zero_features_returns_error() {
        // 2 rows x 2 features — values are arbitrary; only the zero-feature case is under test
        let full = DenseMatrix::from_2d_vec(&vec![vec![1.0, 2.0], vec![3.0, 4.0]]).unwrap();
        let no_features = full.take(&[] as &[usize], 1);
        assert_eq!(no_features.shape(), (2, 0));

        let y: Vec<f64> = vec![1.0, 2.0];
        let result = BaseForest::fit(
            &no_features,
            &y,
            None,
            &MSECriterion,
            BaseForestParameters {
                max_depth: None,
                min_samples_leaf: 1,
                min_samples_split: 2,
                n_trees: 5,
                m: None,
                keep_samples: false,
                seed: 0,
                bootstrap: true,
                splitter: crate::tree::base_tree::Splitter::Best,
            },
        );
        assert!(result.is_err());
        assert_eq!(result.err().unwrap().error(), FailedError::ParametersError);
    }

    #[test]
    fn balance_property() {
        // Test the balance property on a random dataset
        // Fit random forest with bootstrapping = False.
        // The (weighted) average of predictions on the training data should equal the
        // weighted average of the actual targets of the training data
        let x: DenseMatrix<f64> = DenseMatrix::rand(1000, 10);
        let model_parameters = (0..=9).map(|x| x as f64).collect::<Vec<_>>();
        let y: Vec<f64> = model_parameters.xa(true, &x);

        let forest_parameters = BaseForestParameters {
            max_depth: None,
            min_samples_leaf: 1,
            min_samples_split: 2,
            n_trees: 5,
            m: None,
            keep_samples: true,
            seed: 42,
            bootstrap: false,
            splitter: crate::tree::base_tree::Splitter::Best,
        };

        let forest = BaseForest::fit(&x, &y, None, &MSECriterion, forest_parameters.clone())
            .expect("Fit should work");
        let y_hat = predict_mean(&forest, &x).expect("Predict should work");
        assert!((y_hat.iter().sum::<f64>() - y.iter().sum::<f64>()).abs() < 1e-9);

        // Seeded RNG: the test gives the same result on each run
        let mut rng = get_rng_impl(Some(42));

        // Positive weights in [0.5, 2.0)
        let sample_weights: Vec<f64> = (0..1000).map(|_| rng.random_range(0.5..2.0)).collect();
        let forest = BaseForest::fit(
            &x,
            &y,
            Some(&sample_weights),
            &MSECriterion,
            forest_parameters.clone(),
        )
        .expect("Fit should work");
        let y_hat = predict_mean(&forest, &x).expect("Predict should work");

        let s: f64 = sample_weights.iter().sum();
        let normalized_weights = sample_weights.iter().map(|w| *w / s).collect::<Vec<_>>();

        let expected = y
            .iter()
            .zip(normalized_weights.iter())
            .map(|(&yi, &w)| yi * w)
            .sum::<f64>();
        let actual = y_hat
            .iter()
            .zip(normalized_weights.iter())
            .map(|(&yi, &w)| yi * w)
            .sum::<f64>();

        assert!((expected - actual).abs() < 1e-9);
    }

    #[test]
    fn test_each_tree_gets_different_bootstrap_sample() {
        // actual data uses is irrelevant
        let n_rows = 100;
        let x: DenseMatrix<f64> =
            DenseMatrix::from_iterator((0..2 * n_rows).map(|k| k as f64), n_rows, 2, 0);
        let y: Vec<f64> = (0..n_rows).map(|i| i as f64).collect();
        let sample_weights: Vec<f64> = (0..n_rows).map(|i| 1.0 + (i % 4) as f64).collect();

        for weights in [None, Some(sample_weights.as_slice())] {
            let params = BaseForestParameters {
                max_depth: Some(1),
                min_samples_leaf: 1,
                min_samples_split: 2,
                n_trees: 10,
                m: None,
                keep_samples: true, // keep samples used for each tree, so we can check that they are different
                seed: 42,
                bootstrap: true, // Use bootstrapping
                splitter: crate::tree::base_tree::Splitter::Best,
            };
            let regressor = BaseForest::fit(&x, &y, weights, &MSECriterion, params).unwrap();
            let samples = regressor.samples.unwrap();

            for (t, in_bag) in samples.iter().enumerate() {
                assert!(
                    in_bag.iter().any(|b| !b),
                    "tree {t} has no out-of-bag rows (weights: {weights:?})"
                );
                for (u, other) in samples.iter().enumerate().skip(t + 1) {
                    assert_ne!(
                        in_bag, other,
                        "trees {t} and {u} have the same bootstrap sample (weights: {weights:?})"
                    );
                }
            }
        }
    }

    #[test]
    fn each_tree_gets_different_feature_sample() {
        // Without bootstrap, all trees get the same rows. With m = 1, each node uses one
        // random feature, thus the trees must be different. If all trees use the same seed,
        // all trees are equal. The Random splitter also uses this rng for the thresholds.

        // Create some data
        let n_rows = 30;
        let x: DenseMatrix<f64> = DenseMatrix::from_iterator(
            (0..4 * n_rows).map(|k| ((k * 7919) % 101) as f64),
            n_rows,
            4,
            0,
        );
        let y: Vec<f64> = (0..n_rows).map(|i| ((i * 31) % 17) as f64).collect();

        for splitter in [Splitter::Best, Splitter::Random] {
            let params = BaseForestParameters {
                max_depth: None,
                min_samples_leaf: 1,
                min_samples_split: 2,
                n_trees: 10,
                m: Some(1),
                keep_samples: false,
                seed: 42,
                bootstrap: false,
                splitter: splitter.clone(),
            };
            let forest = BaseForest::fit(&x, &y, None, &MSECriterion, params).unwrap();
            let trees = forest.trees.unwrap();
            assert!(
                trees.iter().any(|tree| tree != &trees[0]),
                "all trees are equal (splitter: {splitter:?})"
            );
        }
    }

    #[test]
    fn fit_with_weights_predicts_approx_weighted_mean() {
        // 20 rows, 1 feature. Stumps (max_depth = 0): each tree predicts the
        // weighted mean of y over its bootstrap sample (which is also weighted)
        let x: DenseMatrix<f64> = DenseMatrix::from_iterator((0..20).map(|i| i as f64), 20, 1, 0);
        let y: Vec<f64> = (0..20).map(|i| if i < 10 { 0.0 } else { 10.0 }).collect();
        // Rows with y = 10 have weight 9, rows with y = 0 have weight 1.
        let sample_weights: Vec<f64> = (0..20).map(|i| if i < 10 { 1.0 } else { 9.0 }).collect();

        let parameters = BaseForestParameters {
            max_depth: Some(0),
            min_samples_leaf: 1,
            min_samples_split: 2,
            n_trees: 10,
            m: None,
            keep_samples: true,
            seed: 42,
            bootstrap: false, // No bootstrapping
            splitter: crate::tree::base_tree::Splitter::Best,
        };

        let forest = BaseForest::fit(
            &x,
            &y,
            Some(&sample_weights),
            &MSECriterion,
            parameters.clone(),
        )
        .expect("Fit should work");
        let y_hat = predict_mean(&forest, &x).expect("Predict should work");

        // weighted mean is (10.0 * 0 + 90*10) / 100 = 9
        for p in y_hat.iter() {
            assert!(
                (p - 9.0f64).abs() < 1e-9,
                "expected value very close to 9, got {p}"
            );
        }

        // Without weights, the predicted value should be close to 5
        let forest =
            BaseForest::fit(&x, &y, None, &MSECriterion, parameters).expect("Fit should work");
        let y_hat = predict_mean(&forest, &x).expect("Predict should work");

        for p in y_hat.iter() {
            assert!(
                (p - 5.0).abs() < 1e-9,
                "expected value very close to 5, got {p}"
            );
        }

        // Use bootstrapping
        let parameters = BaseForestParameters {
            max_depth: Some(0), // Match sibling test on RandomForestRegressor
            min_samples_leaf: 1,
            min_samples_split: 2,
            n_trees: 500, // Use more trees than before to smooth out randomness
            m: None,
            keep_samples: true, // keep samples used for each tree, so we can check that they are different
            seed: 42,
            bootstrap: true, // Use bootstrapping
            splitter: crate::tree::base_tree::Splitter::Best,
        };

        let forest = BaseForest::fit(
            &x,
            &y,
            Some(&sample_weights),
            &MSECriterion,
            parameters.clone(),
        )
        .expect("Fit should work");
        let y_hat = predict_mean(&forest, &x).expect("Predict should work");

        // with bootstrapping the weight should be close to 9, but not extremely close
        for p in y_hat.iter() {
            assert!(
                (p - 9.0).abs() < 0.1,
                "expected value reasonably close to 9, got {p}"
            );
        }

        // Without weights, the predicted value should be reasonably close to 5
        let forest =
            BaseForest::fit(&x, &y, None, &MSECriterion, parameters).expect("Fit should work");
        let y_hat = predict_mean(&forest, &x).expect("Predict should work");

        // The bootstrapping makes that we will not be very close to 5
        for p in y_hat.iter() {
            assert!(
                (p - 5.0).abs() < 0.1,
                "expected value reasonably close to 5, got {p}"
            );
        }
    }

    #[test]
    fn fit_twice_with_same_seed_gives_identical_forest() {
        // With bootstrap, m = 1 and the Random splitter, each random path is used:
        // bootstrap sample, feature selection and random thresholds.
        let n_rows = 30;
        let x: DenseMatrix<f64> = DenseMatrix::from_iterator(
            (0..4 * n_rows).map(|k| ((k * 7919) % 101) as f64),
            n_rows,
            4,
            0,
        );
        let y: Vec<f64> = (0..n_rows).map(|i| ((i * 31) % 17) as f64).collect();
        let sample_weights: Vec<f64> = (0..n_rows).map(|i| 1.0 + (i % 4) as f64).collect();

        for splitter in [Splitter::Best, Splitter::Random] {
            for weights in [None, Some(sample_weights.as_slice())] {
                let params = BaseForestParameters {
                    max_depth: None,
                    min_samples_leaf: 1,
                    min_samples_split: 2,
                    n_trees: 10,
                    m: Some(1),
                    keep_samples: true,
                    seed: 42,
                    bootstrap: true,
                    splitter: splitter.clone(),
                };

                let forest_a = BaseForest::fit(&x, &y, weights, &MSECriterion, params.clone())
                    .expect("Fit should work");
                let forest_b = BaseForest::fit(&x, &y, weights, &MSECriterion, params.clone())
                    .expect("Fit should work");

                assert_eq!(
                    forest_a, forest_b,
                    "forests differ (splitter: {splitter:?}, weights: {weights:?})"
                );
                assert_eq!(
                    forest_a.samples, forest_b.samples,
                    "bootstrap samples differ (splitter: {splitter:?}, weights: {weights:?})"
                );
                assert_eq!(
                    predict_mean(&forest_a, &x).unwrap(),
                    predict_mean(&forest_b, &x).unwrap(),
                    "predictions differ (splitter: {splitter:?}, weights: {weights:?})"
                );

                // A different seed must give a different forest, else the check above is trivial
                let forest_c = BaseForest::fit(
                    &x,
                    &y,
                    weights,
                    &MSECriterion,
                    BaseForestParameters { seed: 43, ..params },
                )
                .expect("Fit should work");
                assert_ne!(
                    forest_a, forest_c,
                    "seeds 42 and 43 give the same forest (splitter: {splitter:?}, weights: {weights:?})"
                );
            }
        }
    }
}