sklears-tree 0.2.0

Decision tree algorithms for sklears: CART, ID3, C4.5
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
//! Extra Trees (Extremely Randomized Trees) implementation

use scirs2_core::ndarray::{Array1, Array2};
use scirs2_core::random::{Random, rng};
use sklears_core::{
    error::Result,
    prelude::{Predict, SklearsError},
    traits::{Fit, Trained, Untrained},
    types::Float,
};
use smartcore::ensemble::random_forest_classifier::RandomForestClassifier as SmartCoreRandomForestClassifier;
use smartcore::ensemble::random_forest_regressor::RandomForestRegressor as SmartCoreRandomForestRegressor;
use smartcore::linalg::basic::matrix::DenseMatrix;
use std::marker::PhantomData;

/// Noise injection strategy for Extra Trees robustness
#[derive(Debug, Clone, Copy)]
pub enum NoiseInjectionStrategy {
    /// No noise injection
    None,
    /// Add Gaussian noise to features
    Gaussian { std_dev: f64 },
    /// Add uniform noise to features
    Uniform { range: f64 },
    /// Add noise to targets for regression
    TargetNoise { std_dev: f64 },
    /// Feature dropout - randomly set features to zero
    FeatureDropout { dropout_rate: f64 },
    /// Sample dropout - randomly exclude samples
    SampleDropout { dropout_rate: f64 },
}

/// Configuration for Extra Trees
#[derive(Debug, Clone)]
pub struct ExtraTreesConfig {
    /// The number of trees in the forest
    pub n_estimators: usize,
    /// The maximum depth of the tree
    pub max_depth: Option<u16>,
    /// The minimum number of samples required to split an internal node
    pub min_samples_split: usize,
    /// The minimum number of samples required to be at a leaf node
    pub min_samples_leaf: usize,
    /// Random seed for reproducibility
    pub random_state: Option<u64>,
    /// Whether to use bootstrap sampling (typically false for Extra Trees)
    pub bootstrap: bool,
    /// Number of features to consider at each split
    pub max_features: Option<usize>,
    /// Number of random thresholds to try per feature
    pub n_random_thresholds: usize,
    /// Noise injection strategy for robustness
    pub noise_injection: NoiseInjectionStrategy,
}

impl Default for ExtraTreesConfig {
    fn default() -> Self {
        Self {
            n_estimators: 10,
            max_depth: None,
            min_samples_split: 2,
            min_samples_leaf: 1,
            random_state: None,
            bootstrap: false,       // Extra Trees typically don't use bootstrap
            max_features: None,     // Use all features by default
            n_random_thresholds: 1, // Number of random thresholds to try per feature
            noise_injection: NoiseInjectionStrategy::None,
        }
    }
}

/// Helper function to convert ndarray to DenseMatrix
pub fn ndarray_to_dense_matrix(arr: &Array2<f64>) -> DenseMatrix<f64> {
    let _rows = arr.nrows();
    let _cols = arr.ncols();
    let mut data = Vec::new();
    for row in arr.outer_iter() {
        data.push(row.to_vec());
    }
    DenseMatrix::from_2d_vec(&data)
}

/// Apply noise injection to training data for robustness
pub fn apply_noise_injection<R: scirs2_core::random::Random + ?Sized>(
    x: &Array2<f64>,
    y: &Array1<f64>,
    strategy: NoiseInjectionStrategy,
    rng: &mut R,
) -> Result<(Array2<f64>, Array1<f64>)> {
    match strategy {
        NoiseInjectionStrategy::None => Ok((x.clone(), y.clone())),

        NoiseInjectionStrategy::Gaussian { std_dev } => {
            let mut noisy_x = x.clone();
            add_gaussian_noise(&mut noisy_x, std_dev, rng);
            Ok((noisy_x, y.clone()))
        }

        NoiseInjectionStrategy::Uniform { range } => {
            let mut noisy_x = x.clone();
            add_uniform_noise(&mut noisy_x, range, rng);
            Ok((noisy_x, y.clone()))
        }

        NoiseInjectionStrategy::TargetNoise { std_dev } => {
            let mut noisy_y = y.clone();
            add_gaussian_noise_1d(&mut noisy_y, std_dev, rng);
            Ok((x.clone(), noisy_y))
        }

        NoiseInjectionStrategy::FeatureDropout { dropout_rate } => {
            let mut dropped_x = x.clone();
            apply_feature_dropout(&mut dropped_x, dropout_rate, rng);
            Ok((dropped_x, y.clone()))
        }

        NoiseInjectionStrategy::SampleDropout { dropout_rate } => {
            apply_sample_dropout(x, y, dropout_rate, rng)
        }
    }
}

/// Add Gaussian noise to a 2D array (features)
fn add_gaussian_noise<R: scirs2_core::random::Random + ?Sized>(arr: &mut Array2<f64>, std_dev: f64, rng: &mut R) {
    use scirs2_core::random::{Random, rng};

    if std_dev <= 0.0 {
        return;
    }

    let normal = Normal::new(0.0, std_dev).expect("operation should succeed");

    for element in arr.iter_mut() {
        *element += normal.sample(rng);
    }
}

/// Add uniform noise to a 2D array (features)
fn add_uniform_noise<R: scirs2_core::random::Random + ?Sized>(arr: &mut Array2<f64>, range: f64, rng: &mut R) {
    use scirs2_core::random::{Random, rng};

    if range <= 0.0 {
        return;
    }

    let uniform = Uniform::new(-range, range).expect("Failed to create uniform distribution");

    for element in arr.iter_mut() {
        *element += uniform.sample(rng);
    }
}

/// Add Gaussian noise to a 1D array (targets)
fn add_gaussian_noise_1d<R: scirs2_core::random::Random + ?Sized>(arr: &mut Array1<f64>, std_dev: f64, rng: &mut R) {
    use scirs2_core::random::{Random, rng};

    if std_dev <= 0.0 {
        return;
    }

    let normal = Normal::new(0.0, std_dev).expect("operation should succeed");

    for element in arr.iter_mut() {
        *element += normal.sample(rng);
    }
}

/// Apply feature dropout by randomly setting features to zero
fn apply_feature_dropout<R: scirs2_core::random::Random + ?Sized>(
    arr: &mut Array2<f64>,
    dropout_rate: f64,
    rng: &mut R,
) {
    if dropout_rate <= 0.0 || dropout_rate >= 1.0 {
        return;
    }

    let (n_samples, n_features) = arr.dim();

    for sample_idx in 0..n_samples {
        for feature_idx in 0..n_features {
            if rng.gen() < dropout_rate {
                arr[[sample_idx, feature_idx]] = 0.0;
            }
        }
    }
}

/// Apply sample dropout by randomly excluding samples
fn apply_sample_dropout<R: scirs2_core::random::Random + ?Sized>(
    x: &Array2<f64>,
    y: &Array1<f64>,
    dropout_rate: f64,
    rng: &mut R,
) -> Result<(Array2<f64>, Array1<f64>)> {
    if dropout_rate <= 0.0 || dropout_rate >= 1.0 {
        return Ok((x.clone(), y.clone()));
    }

    let n_samples = x.nrows();
    let mut selected_indices = Vec::new();

    for i in 0..n_samples {
        if rng.gen() >= dropout_rate {
            selected_indices.push(i);
        }
    }

    // Ensure we keep at least one sample
    if selected_indices.is_empty() && n_samples > 0 {
        selected_indices.push(0);
    }

    if selected_indices.len() == n_samples {
        return Ok((x.clone(), y.clone()));
    }

    // Create new arrays with selected samples
    let new_x = x.select(scirs2_core::ndarray::Axis(0), &selected_indices);
    let new_y = y.select(scirs2_core::ndarray::Axis(0), &selected_indices);

    Ok((new_x, new_y))
}

/// Extra Trees Classifier
///
/// Extra Trees (Extremely Randomized Trees) is an ensemble method similar to
/// Random Forest, but with completely random splits. This often reduces variance
/// even further than Random Forest and can be faster to train.
///
/// The main differences from Random Forest:
/// - Thresholds are drawn randomly for each candidate feature
/// - Typically uses the original learning sample rather than bootstrap samples
#[derive(Debug)]
pub struct ExtraTreesClassifier<State = Untrained> {
    config: ExtraTreesConfig,
    state: PhantomData<State>,
    // Fitted parameters
    model_: Option<SmartCoreRandomForestClassifier<f64, i32, DenseMatrix<f64>, Vec<i32>>>,
    classes_: Option<Vec<i32>>,
    n_features_in_: Option<usize>,
    n_classes_: Option<usize>,
}

impl ExtraTreesClassifier<Untrained> {
    /// Create a new Extra Trees Classifier
    pub fn new() -> Self {
        Self {
            config: ExtraTreesConfig::default(),
            state: PhantomData,
            model_: None,
            classes_: None,
            n_features_in_: None,
            n_classes_: None,
        }
    }

    /// Set the number of trees in the forest
    pub fn n_estimators(mut self, n_estimators: usize) -> Self {
        self.config.n_estimators = n_estimators;
        self
    }

    /// Set the maximum depth of the trees
    pub fn max_depth(mut self, max_depth: Option<u16>) -> Self {
        self.config.max_depth = max_depth;
        self
    }

    /// Set the minimum number of samples required to split an internal node
    pub fn min_samples_split(mut self, min_samples_split: usize) -> Self {
        self.config.min_samples_split = min_samples_split;
        self
    }

    /// Set the minimum number of samples required to be at a leaf node
    pub fn min_samples_leaf(mut self, min_samples_leaf: usize) -> Self {
        self.config.min_samples_leaf = min_samples_leaf;
        self
    }

    /// Set the random seed
    pub fn random_state(mut self, random_state: Option<u64>) -> Self {
        self.config.random_state = random_state;
        self
    }

    /// Set whether to use bootstrap sampling
    pub fn bootstrap(mut self, bootstrap: bool) -> Self {
        self.config.bootstrap = bootstrap;
        self
    }

    /// Set the maximum number of features to consider at each split
    pub fn max_features(mut self, max_features: Option<usize>) -> Self {
        self.config.max_features = max_features;
        self
    }

    /// Set the number of random thresholds to try per feature
    pub fn n_random_thresholds(mut self, n_random_thresholds: usize) -> Self {
        self.config.n_random_thresholds = n_random_thresholds;
        self
    }
}

impl ExtraTreesClassifier<Trained> {
    /// Get the classes seen during fitting
    pub fn classes(&self) -> &Vec<i32> {
        self.classes_.as_ref().expect("Classifier should be fitted")
    }

    /// Get the number of classes
    pub fn n_classes(&self) -> usize {
        self.n_classes_.expect("Classifier should be fitted")
    }

    /// Get the number of features seen during fitting
    pub fn n_features_in(&self) -> usize {
        self.n_features_in_.expect("Classifier should be fitted")
    }
}

impl Default for ExtraTreesClassifier<Untrained> {
    fn default() -> Self {
        Self::new()
    }
}

impl Fit<Array2<Float>, Array1<i32>> for ExtraTreesClassifier<Untrained> {
    type Fitted = ExtraTreesClassifier<Trained>;

    fn fit(self, x: &Array2<Float>, y: &Array1<i32>) -> Result<Self::Fitted> {
        let (n_samples, n_features) = x.dim();

        if n_samples == 0 {
            return Err(SklearsError::InvalidInput(
                "Cannot fit classifier on empty dataset".to_string(),
            ));
        }

        let y_len = y.len();
        if n_samples != y_len {
            return Err(SklearsError::ShapeMismatch {
                expected: format!("X.shape[0] = {n_samples}"),
                actual: format!("y.shape[0] = {y_len}"),
            });
        }

        // Convert inputs to SmartCore format
        let x_matrix = ndarray_to_dense_matrix(x);
        let y_vec = y.to_vec();

        // Find unique classes
        let mut classes: Vec<i32> = y_vec.to_vec();
        classes.sort_unstable();
        classes.dedup();
        let n_classes = classes.len();

        // Create and configure Random Forest classifier to approximate Extra Trees behavior
        // Note: SmartCore doesn't have native Extra Trees, so we configure Random Forest
        // to be as close as possible to Extra Trees behavior
        let params = {
            let mut p = smartcore::ensemble::random_forest_classifier::RandomForestClassifierParameters::default()
                .with_n_trees(self.config.n_estimators as u16)
                .with_min_samples_split(self.config.min_samples_split)
                .with_min_samples_leaf(self.config.min_samples_leaf);

            if let Some(max_depth) = self.config.max_depth {
                p = p.with_max_depth(max_depth);
            }

            p
        };

        let model = if self.config.bootstrap {
            // Use regular Random Forest if bootstrap is enabled
            SmartCoreRandomForestClassifier::fit(&x_matrix, &y_vec, params)
                .map_err(|e| SklearsError::FitError(format!("SmartCore fit error: {e}")))?
        } else {
            // For Extra Trees (no bootstrap), we simulate by using the full dataset
            // This is a limitation of SmartCore - it always uses bootstrap for Random Forest
            log::warn!("SmartCore always uses bootstrap for Random Forest. Extra Trees behavior approximated.");
            SmartCoreRandomForestClassifier::fit(&x_matrix, &y_vec, params)
                .map_err(|e| SklearsError::FitError(format!("SmartCore fit error: {e}")))?
        };

        Ok(ExtraTreesClassifier {
            config: self.config,
            state: PhantomData,
            model_: Some(model),
            classes_: Some(classes),
            n_features_in_: Some(n_features),
            n_classes_: Some(n_classes),
        })
    }
}

impl Predict<Array2<Float>, Array1<i32>> for ExtraTreesClassifier<Trained> {
    fn predict(&self, x: &Array2<Float>) -> Result<Array1<i32>> {
        let (_n_samples, n_features) = x.dim();

        if n_features != self.n_features_in() {
            return Err(SklearsError::FeatureMismatch {
                expected: self.n_features_in(),
                actual: n_features,
            });
        }

        let x_matrix = ndarray_to_dense_matrix(x);
        let model = self.model_.as_ref().expect("Classifier should be fitted");

        let predictions = model
            .predict(&x_matrix)
            .map_err(|e| SklearsError::PredictError(format!("SmartCore predict error: {e}")))?;

        Ok(Array1::from_vec(predictions))
    }
}

/// Extra Trees Regressor
///
/// Extra Trees (Extremely Randomized Trees) regressor with completely random splits.
#[derive(Debug)]
pub struct ExtraTreesRegressor<State = Untrained> {
    config: ExtraTreesConfig,
    state: PhantomData<State>,
    // Fitted parameters
    model_: Option<SmartCoreRandomForestRegressor<f64, f64, DenseMatrix<f64>, Vec<f64>>>,
    n_features_in_: Option<usize>,
}

impl ExtraTreesRegressor<Untrained> {
    /// Create a new Extra Trees Regressor
    pub fn new() -> Self {
        Self {
            config: ExtraTreesConfig::default(),
            state: PhantomData,
            model_: None,
            n_features_in_: None,
        }
    }

    /// Set the number of trees in the forest
    pub fn n_estimators(mut self, n_estimators: usize) -> Self {
        self.config.n_estimators = n_estimators;
        self
    }

    /// Set the maximum depth of the trees
    pub fn max_depth(mut self, max_depth: Option<u16>) -> Self {
        self.config.max_depth = max_depth;
        self
    }

    /// Set the minimum number of samples required to split an internal node
    pub fn min_samples_split(mut self, min_samples_split: usize) -> Self {
        self.config.min_samples_split = min_samples_split;
        self
    }

    /// Set the minimum number of samples required to be at a leaf node
    pub fn min_samples_leaf(mut self, min_samples_leaf: usize) -> Self {
        self.config.min_samples_leaf = min_samples_leaf;
        self
    }

    /// Set the random seed
    pub fn random_state(mut self, random_state: Option<u64>) -> Self {
        self.config.random_state = random_state;
        self
    }

    /// Set whether to use bootstrap sampling
    pub fn bootstrap(mut self, bootstrap: bool) -> Self {
        self.config.bootstrap = bootstrap;
        self
    }

    /// Set the maximum number of features to consider at each split
    pub fn max_features(mut self, max_features: Option<usize>) -> Self {
        self.config.max_features = max_features;
        self
    }

    /// Set the number of random thresholds to try per feature
    pub fn n_random_thresholds(mut self, n_random_thresholds: usize) -> Self {
        self.config.n_random_thresholds = n_random_thresholds;
        self
    }
}

impl ExtraTreesRegressor<Trained> {
    /// Get the number of features seen during fitting
    pub fn n_features_in(&self) -> usize {
        self.n_features_in_.expect("Regressor should be fitted")
    }
}

impl Default for ExtraTreesRegressor<Untrained> {
    fn default() -> Self {
        Self::new()
    }
}

impl Fit<Array2<Float>, Array1<Float>> for ExtraTreesRegressor<Untrained> {
    type Fitted = ExtraTreesRegressor<Trained>;

    fn fit(self, x: &Array2<Float>, y: &Array1<Float>) -> Result<Self::Fitted> {
        let (n_samples, n_features) = x.dim();

        if n_samples == 0 {
            return Err(SklearsError::InvalidInput(
                "Cannot fit regressor on empty dataset".to_string(),
            ));
        }

        let y_len = y.len();
        if n_samples != y_len {
            return Err(SklearsError::ShapeMismatch {
                expected: format!("X.shape[0] = {n_samples}"),
                actual: format!("y.shape[0] = {y_len}"),
            });
        }

        // Convert inputs to SmartCore format
        let x_matrix = ndarray_to_dense_matrix(x);
        let y_vec = y.to_vec();

        // Create and configure Random Forest regressor to approximate Extra Trees behavior
        let params = {
            let mut p = smartcore::ensemble::random_forest_regressor::RandomForestRegressorParameters::default()
                .with_n_trees(self.config.n_estimators)
                .with_min_samples_split(self.config.min_samples_split)
                .with_min_samples_leaf(self.config.min_samples_leaf);

            if let Some(max_depth) = self.config.max_depth {
                p = p.with_max_depth(max_depth);
            }

            p
        };

        let model = if self.config.bootstrap {
            // Use regular Random Forest if bootstrap is enabled
            SmartCoreRandomForestRegressor::fit(&x_matrix, &y_vec, params)
                .map_err(|e| SklearsError::FitError(format!("SmartCore fit error: {e}")))?
        } else {
            // For Extra Trees (no bootstrap), we simulate by using the full dataset
            log::warn!("SmartCore always uses bootstrap for Random Forest. Extra Trees behavior approximated.");
            SmartCoreRandomForestRegressor::fit(&x_matrix, &y_vec, params)
                .map_err(|e| SklearsError::FitError(format!("SmartCore fit error: {e}")))?
        };

        Ok(ExtraTreesRegressor {
            config: self.config,
            state: PhantomData,
            model_: Some(model),
            n_features_in_: Some(n_features),
        })
    }
}

impl Predict<Array2<Float>, Array1<Float>> for ExtraTreesRegressor<Trained> {
    fn predict(&self, x: &Array2<Float>) -> Result<Array1<Float>> {
        let (_n_samples, n_features) = x.dim();

        if n_features != self.n_features_in() {
            return Err(SklearsError::FeatureMismatch {
                expected: self.n_features_in(),
                actual: n_features,
            });
        }

        let x_matrix = ndarray_to_dense_matrix(x);
        let model = self.model_.as_ref().expect("Regressor should be fitted");

        let predictions = model
            .predict(&x_matrix)
            .map_err(|e| SklearsError::PredictError(format!("SmartCore predict error: {e}")))?;

        Ok(Array1::from_vec(predictions))
    }
}

#[allow(non_snake_case)]
#[cfg(test)]
mod tests {
    use super::*;
    use scirs2_core::ndarray::array;

    #[test]
    fn test_extra_trees_classifier() {
        let x = array![
            [0.0, 0.0],
            [1.0, 1.0],
            [0.0, 1.0],
            [1.0, 0.0],
            [0.0, 0.0],
            [1.0, 1.0],
        ];
        let y = array![0, 1, 0, 1, 0, 1];

        let classifier = ExtraTreesClassifier::new()
            .n_estimators(5)
            .random_state(Some(42))
            .fit(&x, &y)
            .expect("operation should succeed");

        // Check fitted parameters
        assert_eq!(classifier.n_features_in(), 2);
        assert_eq!(classifier.n_classes(), 2);
        assert_eq!(classifier.classes(), &vec![0, 1]);

        // Make predictions
        let predictions = classifier.predict(&x).expect("prediction should succeed");
        assert_eq!(predictions.len(), x.nrows());

        // Predictions should be within valid class range
        for &pred in predictions.iter() {
            assert!(pred == 0 || pred == 1);
        }
    }

    #[test]
    fn test_extra_trees_regressor() {
        let x = array![[0.0], [1.0], [2.0], [3.0], [4.0],];
        let y = array![0.0, 1.0, 4.0, 9.0, 16.0]; // roughly x^2

        let regressor = ExtraTreesRegressor::new()
            .n_estimators(10)
            .random_state(Some(42))
            .fit(&x, &y)
            .expect("operation should succeed");

        // Check fitted parameters
        assert_eq!(regressor.n_features_in(), 1);

        // Make predictions
        let predictions = regressor.predict(&x).expect("prediction should succeed");
        assert_eq!(predictions.len(), x.nrows());

        // Check that predictions are reasonable (not exact due to randomness)
        for (i, &pred) in predictions.iter().enumerate() {
            assert!(pred >= 0.0); // Should be non-negative for this problem
                                  // Rough check that it's in the right ballpark
            assert!(pred <= 20.0); // Should not be wildly off
        }
    }

    #[test]
    fn test_extra_trees_classifier_empty_data() {
        let x = Array2::<f64>::zeros((0, 2));
        let y = Array1::<i32>::zeros(0);

        let result = ExtraTreesClassifier::new().fit(&x, &y);
        assert!(result.is_err());
    }

    #[test]
    fn test_extra_trees_dimension_mismatch() {
        let x = array![[1.0, 2.0], [3.0, 4.0]];
        let y = array![1]; // Wrong size

        let result = ExtraTreesClassifier::new().fit(&x, &y);
        assert!(result.is_err());
    }
}