sklears-ensemble 0.2.0

Ensemble methods for sklears: Random Forest, Gradient Boosting, AdaBoost
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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
//! Memory-efficient ensemble methods for large-scale machine learning
//!
//! This module provides memory-efficient implementations of ensemble methods
//! that can handle large datasets by using incremental learning, streaming
//! processing, and lazy evaluation techniques.

use scirs2_core::ndarray::{Array1, Array2, Axis};
use sklears_core::error::{Result, SklearsError};
use sklears_core::prelude::Predict;
use sklears_core::traits::{Estimator, Fit, Trained, Untrained};
use sklears_core::types::Float;
use std::collections::VecDeque;
use std::marker::PhantomData;

/// Configuration for memory-efficient ensemble methods
#[derive(Debug, Clone)]
pub struct MemoryEfficientConfig {
    /// Maximum number of estimators to keep in memory
    pub max_estimators_in_memory: usize,
    /// Batch size for incremental learning
    pub batch_size: usize,
    /// Window size for streaming data
    pub window_size: Option<usize>,
    /// Enable lazy evaluation for predictions
    pub lazy_evaluation: bool,
    /// Memory threshold in MB before triggering cleanup
    pub memory_threshold_mb: usize,
    /// Enable compression for stored models
    pub compress_models: bool,
    /// Use disk caching for overflow models
    pub use_disk_cache: bool,
    /// Disk cache directory
    pub cache_dir: Option<String>,
    /// Learning rate decay for incremental learning
    pub learning_rate_decay: Float,
    /// Forgetting factor for streaming data
    pub forgetting_factor: Float,
    /// Enable adaptive batch sizing
    pub adaptive_batch_size: bool,
}

impl Default for MemoryEfficientConfig {
    fn default() -> Self {
        Self {
            max_estimators_in_memory: 50,
            batch_size: 1000,
            window_size: Some(10000),
            lazy_evaluation: true,
            memory_threshold_mb: 512,
            compress_models: false,
            use_disk_cache: false,
            cache_dir: None,
            learning_rate_decay: 0.999,
            forgetting_factor: 0.95,
            adaptive_batch_size: true,
        }
    }
}

/// Memory-efficient ensemble that uses incremental learning and streaming
pub struct MemoryEfficientEnsemble<State = Untrained> {
    config: MemoryEfficientConfig,
    state: PhantomData<State>,
    // In-memory models
    active_models_: Option<Vec<Box<dyn IncrementalModel>>>,
    // Model weights for ensemble voting
    model_weights_: Option<Array1<Float>>,
    // Statistics for memory management
    memory_usage_: usize,
    total_models_created_: usize,
    // Streaming data buffer
    data_buffer_: Option<VecDeque<(Array1<Float>, Float)>>,
    // Lazy evaluation cache
    prediction_cache_: Option<std::collections::HashMap<u64, Float>>,
    // Performance tracking
    performance_history_: Vec<Float>,
    current_learning_rate_: Float,
}

/// Trait for incremental learning models
pub trait IncrementalModel: Send + Sync {
    /// Incrementally update the model with new data
    fn partial_fit(&mut self, x: &Array1<Float>, y: Float) -> Result<()>;

    /// Predict a single sample
    fn predict_single(&self, x: &Array1<Float>) -> Result<Float>;

    /// Get model complexity (for memory estimation)
    fn complexity(&self) -> usize;

    /// Serialize model for disk caching
    fn serialize(&self) -> Result<Vec<u8>>;

    /// Clone the model
    fn clone_model(&self) -> Box<dyn IncrementalModel>;
}

/// Helper function for deserializing incremental models
pub fn deserialize_incremental_model(data: &[u8]) -> Result<Box<dyn IncrementalModel>> {
    IncrementalLinearRegression::deserialize(data)
}

/// Simple incremental linear regression model
#[derive(Debug, Clone)]
pub struct IncrementalLinearRegression {
    weights: Array1<Float>,
    bias: Float,
    n_features: usize,
    learning_rate: Float,
    l2_reg: Float,
}

impl IncrementalLinearRegression {
    pub fn new(n_features: usize, learning_rate: Float, l2_reg: Float) -> Self {
        Self {
            weights: Array1::zeros(n_features),
            bias: 0.0,
            n_features,
            learning_rate,
            l2_reg,
        }
    }
}

impl IncrementalModel for IncrementalLinearRegression {
    fn partial_fit(&mut self, x: &Array1<Float>, y: Float) -> Result<()> {
        if x.len() != self.n_features {
            return Err(SklearsError::ShapeMismatch {
                expected: format!("{} features", self.n_features),
                actual: format!("{} features", x.len()),
            });
        }

        // Compute prediction
        let y_pred = self.weights.dot(x) + self.bias;

        // Compute error
        let error = y - y_pred;

        // Update weights with regularization
        for i in 0..self.n_features {
            self.weights[i] += self.learning_rate * (error * x[i] - self.l2_reg * self.weights[i]);
        }

        // Update bias
        self.bias += self.learning_rate * error;

        Ok(())
    }

    fn predict_single(&self, x: &Array1<Float>) -> Result<Float> {
        if x.len() != self.n_features {
            return Err(SklearsError::ShapeMismatch {
                expected: format!("{} features", self.n_features),
                actual: format!("{} features", x.len()),
            });
        }

        Ok(self.weights.dot(x) + self.bias)
    }

    fn complexity(&self) -> usize {
        // Rough estimate: weights + bias + metadata
        self.n_features * 8 + 8 + 32
    }

    fn serialize(&self) -> Result<Vec<u8>> {
        // Simple serialization for demonstration
        // In practice, you might use serde or bincode
        let mut data = Vec::new();

        // Write n_features
        data.extend_from_slice(&self.n_features.to_le_bytes());

        // Write learning_rate
        data.extend_from_slice(&self.learning_rate.to_le_bytes());

        // Write l2_reg
        data.extend_from_slice(&self.l2_reg.to_le_bytes());

        // Write bias
        data.extend_from_slice(&self.bias.to_le_bytes());

        // Write weights
        for &weight in self.weights.iter() {
            data.extend_from_slice(&weight.to_le_bytes());
        }

        Ok(data)
    }

    fn clone_model(&self) -> Box<dyn IncrementalModel> {
        Box::new(self.clone())
    }
}

impl IncrementalLinearRegression {
    pub fn deserialize(data: &[u8]) -> Result<Box<dyn IncrementalModel>> {
        if data.len() < 32 {
            return Err(SklearsError::InvalidInput(
                "Insufficient data for deserialization".to_string(),
            ));
        }

        let mut offset = 0;

        // Read n_features
        let n_features = usize::from_le_bytes(
            data[offset..offset + 8]
                .try_into()
                .expect("type conversion should succeed"),
        );
        offset += 8;

        // Read learning_rate
        let learning_rate = Float::from_le_bytes(
            data[offset..offset + 8]
                .try_into()
                .expect("type conversion should succeed"),
        );
        offset += 8;

        // Read l2_reg
        let l2_reg = Float::from_le_bytes(
            data[offset..offset + 8]
                .try_into()
                .expect("type conversion should succeed"),
        );
        offset += 8;

        // Read bias
        let bias = Float::from_le_bytes(
            data[offset..offset + 8]
                .try_into()
                .expect("type conversion should succeed"),
        );
        offset += 8;

        // Read weights
        let mut weights = Array1::zeros(n_features);
        for i in 0..n_features {
            weights[i] = Float::from_le_bytes(
                data[offset..offset + 8]
                    .try_into()
                    .expect("type conversion should succeed"),
            );
            offset += 8;
        }

        Ok(Box::new(IncrementalLinearRegression {
            weights,
            bias,
            n_features,
            learning_rate,
            l2_reg,
        }))
    }
}

impl<State> MemoryEfficientEnsemble<State> {
    /// Get current memory usage estimate in bytes
    pub fn memory_usage(&self) -> usize {
        self.memory_usage_
    }

    /// Get number of active models in memory
    pub fn active_model_count(&self) -> usize {
        self.active_models_
            .as_ref()
            .map_or(0, |models| models.len())
    }

    /// Get total number of models created
    pub fn total_models_created(&self) -> usize {
        self.total_models_created_
    }

    /// Check if memory cleanup is needed
    pub fn needs_cleanup(&self) -> bool {
        self.memory_usage_ > self.config.memory_threshold_mb * 1024 * 1024
    }
}

impl MemoryEfficientEnsemble<Untrained> {
    /// Create a new memory-efficient ensemble
    pub fn new() -> Self {
        Self {
            config: MemoryEfficientConfig::default(),
            state: PhantomData,
            active_models_: None,
            model_weights_: None,
            memory_usage_: 0,
            total_models_created_: 0,
            data_buffer_: None,
            prediction_cache_: None,
            performance_history_: Vec::new(),
            current_learning_rate_: 0.01,
        }
    }

    /// Set maximum number of estimators to keep in memory
    pub fn max_estimators_in_memory(mut self, max_estimators: usize) -> Self {
        self.config.max_estimators_in_memory = max_estimators;
        self
    }

    /// Set batch size for incremental learning
    pub fn batch_size(mut self, batch_size: usize) -> Self {
        self.config.batch_size = batch_size;
        self
    }

    /// Set window size for streaming data
    pub fn window_size(mut self, window_size: Option<usize>) -> Self {
        self.config.window_size = window_size;
        self
    }

    /// Enable lazy evaluation
    pub fn lazy_evaluation(mut self, enabled: bool) -> Self {
        self.config.lazy_evaluation = enabled;
        self
    }

    /// Set memory threshold in MB
    pub fn memory_threshold_mb(mut self, threshold: usize) -> Self {
        self.config.memory_threshold_mb = threshold;
        self
    }

    /// Enable model compression
    pub fn compress_models(mut self, enabled: bool) -> Self {
        self.config.compress_models = enabled;
        self
    }

    /// Enable disk caching
    pub fn use_disk_cache(mut self, enabled: bool, cache_dir: Option<String>) -> Self {
        self.config.use_disk_cache = enabled;
        self.config.cache_dir = cache_dir;
        self
    }

    /// Set learning rate decay
    pub fn learning_rate_decay(mut self, decay: Float) -> Self {
        self.config.learning_rate_decay = decay;
        self
    }

    /// Set forgetting factor for streaming
    pub fn forgetting_factor(mut self, factor: Float) -> Self {
        self.config.forgetting_factor = factor;
        self
    }

    /// Enable adaptive batch sizing
    pub fn adaptive_batch_size(mut self, enabled: bool) -> Self {
        self.config.adaptive_batch_size = enabled;
        self
    }

    /// Create a memory-efficient ensemble with optimal settings for large datasets
    pub fn for_large_datasets() -> Self {
        Self::new()
            .max_estimators_in_memory(20)
            .batch_size(5000)
            .window_size(Some(50000))
            .lazy_evaluation(true)
            .memory_threshold_mb(1024)
            .compress_models(true)
            .use_disk_cache(
                true,
                Some(
                    std::env::temp_dir()
                        .join("sklears_cache")
                        .display()
                        .to_string(),
                ),
            )
            .learning_rate_decay(0.995)
            .adaptive_batch_size(true)
    }

    /// Create a streaming ensemble with optimal settings
    pub fn for_streaming() -> Self {
        Self::new()
            .max_estimators_in_memory(10)
            .batch_size(100)
            .window_size(Some(5000))
            .lazy_evaluation(true)
            .memory_threshold_mb(256)
            .forgetting_factor(0.9)
            .adaptive_batch_size(true)
    }
}

impl MemoryEfficientEnsemble<Trained> {
    /// Predict with lazy evaluation
    pub fn predict_lazy(&self, x: &Array2<Float>) -> Result<Array1<Float>> {
        if !self.config.lazy_evaluation {
            return self.predict(x);
        }

        let mut predictions = Array1::zeros(x.nrows());

        // Use cached predictions if available
        if let Some(cache) = &self.prediction_cache_ {
            for (i, row) in x.axis_iter(Axis(0)).enumerate() {
                let hash = self.hash_input(&row.to_owned())?;
                if let Some(&cached_pred) = cache.get(&hash) {
                    predictions[i] = cached_pred;
                } else {
                    predictions[i] = self.predict_single_internal(&row.to_owned())?;
                }
            }
        } else {
            for (i, row) in x.axis_iter(Axis(0)).enumerate() {
                predictions[i] = self.predict_single_internal(&row.to_owned())?;
            }
        }

        Ok(predictions)
    }

    /// Predict a single sample with ensemble voting
    fn predict_single_internal(&self, x: &Array1<Float>) -> Result<Float> {
        if let Some(models) = &self.active_models_ {
            if models.is_empty() {
                return Err(SklearsError::NotFitted {
                    operation: "prediction".to_string(),
                });
            }

            let mut weighted_sum = 0.0;
            let mut total_weight = 0.0;

            for (i, model) in models.iter().enumerate() {
                let prediction = model.predict_single(x)?;
                let weight = self.model_weights_.as_ref().map(|w| w[i]).unwrap_or(1.0);

                weighted_sum += prediction * weight;
                total_weight += weight;
            }

            if total_weight > 0.0 {
                Ok(weighted_sum / total_weight)
            } else {
                Ok(0.0)
            }
        } else {
            Err(SklearsError::NotFitted {
                operation: "prediction".to_string(),
            })
        }
    }

    /// Update the ensemble with new streaming data
    pub fn partial_fit(&mut self, x: &Array1<Float>, y: Float) -> Result<()> {
        // Add to buffer
        if let Some(buffer) = &mut self.data_buffer_ {
            buffer.push_back((x.clone(), y));

            // Maintain window size
            if let Some(window_size) = self.config.window_size {
                while buffer.len() > window_size {
                    buffer.pop_front();
                }
            }
        } else {
            self.data_buffer_ = Some(VecDeque::new());
            self.data_buffer_
                .as_mut()
                .expect("operation should succeed")
                .push_back((x.clone(), y));
        }

        // Update active models
        if let Some(models) = &mut self.active_models_ {
            for model in models.iter_mut() {
                model.partial_fit(x, y)?;
            }
        }

        // Check if we need to add a new model
        if self.should_add_model() {
            self.add_new_model(x.len())?;
        }

        // Update learning rate
        self.current_learning_rate_ *= self.config.learning_rate_decay;

        // Check for memory cleanup
        if self.needs_cleanup() {
            self.cleanup_memory()?;
        }

        Ok(())
    }

    /// Check if a new model should be added
    fn should_add_model(&self) -> bool {
        // Add model if performance has degraded or we don't have enough diversity
        if self.performance_history_.len() < 10 {
            return true;
        }

        let recent_performance = self
            .performance_history_
            .iter()
            .rev()
            .take(5)
            .sum::<Float>()
            / 5.0;
        let older_performance = self
            .performance_history_
            .iter()
            .rev()
            .skip(5)
            .take(5)
            .sum::<Float>()
            / 5.0;

        recent_performance < older_performance * 0.95 // 5% degradation threshold
    }

    /// Add a new incremental model to the ensemble
    fn add_new_model(&mut self, n_features: usize) -> Result<()> {
        if let Some(models) = &mut self.active_models_ {
            // Create new model
            let new_model = Box::new(IncrementalLinearRegression::new(
                n_features,
                self.current_learning_rate_,
                0.001, // L2 regularization
            ));

            models.push(new_model as Box<dyn IncrementalModel>);
            self.total_models_created_ += 1;

            // Update memory usage
            self.memory_usage_ += n_features * 8 + 64; // Rough estimate

            // Remove oldest model if we exceed memory limit
            if models.len() > self.config.max_estimators_in_memory && !models.is_empty() {
                let removed_model = models.remove(0);
                self.memory_usage_ = self
                    .memory_usage_
                    .saturating_sub(removed_model.complexity());
            }

            // Update weights
            self.update_model_weights()?;
        } else {
            // Initialize ensemble
            let mut models = Vec::new();
            let new_model = Box::new(IncrementalLinearRegression::new(
                n_features,
                self.current_learning_rate_,
                0.001,
            ));
            models.push(new_model as Box<dyn IncrementalModel>);
            self.active_models_ = Some(models);
            self.total_models_created_ = 1;
            self.memory_usage_ = n_features * 8 + 64;
            self.update_model_weights()?;
        }

        Ok(())
    }

    /// Update model weights based on performance
    fn update_model_weights(&mut self) -> Result<()> {
        if let Some(models) = &self.active_models_ {
            let n_models = models.len();
            if n_models == 0 {
                return Ok(());
            }

            // Simple equal weighting for now
            // In practice, you'd use performance-based weighting
            let weights = Array1::from_elem(n_models, 1.0 / n_models as Float);
            self.model_weights_ = Some(weights);
        }

        Ok(())
    }

    /// Cleanup memory by removing least important models
    fn cleanup_memory(&mut self) -> Result<()> {
        if let Some(models) = &mut self.active_models_ {
            let target_size = self.config.max_estimators_in_memory / 2;

            while models.len() > target_size {
                if !models.is_empty() {
                    let removed_model = models.remove(0);
                    self.memory_usage_ = self
                        .memory_usage_
                        .saturating_sub(removed_model.complexity());
                }
            }

            // Update weights after cleanup
            self.update_model_weights()?;
        }

        // Clear prediction cache
        if let Some(cache) = &mut self.prediction_cache_ {
            cache.clear();
        }

        Ok(())
    }

    /// Hash input for caching
    fn hash_input(&self, x: &Array1<Float>) -> Result<u64> {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        for &val in x.iter() {
            val.to_bits().hash(&mut hasher);
        }
        Ok(hasher.finish())
    }
}

// Implement core traits
impl Estimator for MemoryEfficientEnsemble<Untrained> {
    type Config = MemoryEfficientConfig;
    type Error = SklearsError;
    type Float = Float;

    fn config(&self) -> &Self::Config {
        &self.config
    }
}

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

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

        if n_samples != y.len() {
            return Err(SklearsError::ShapeMismatch {
                expected: format!("{} samples", n_samples),
                actual: format!("{} samples", y.len()),
            });
        }

        // Initialize ensemble
        let config = self.config.clone();
        let mut ensemble = MemoryEfficientEnsemble::<Trained> {
            config: config.clone(),
            state: PhantomData,
            active_models_: Some(Vec::new()),
            model_weights_: None,
            memory_usage_: 0,
            total_models_created_: 0,
            data_buffer_: Some(VecDeque::new()),
            prediction_cache_: if self.config.lazy_evaluation {
                Some(std::collections::HashMap::new())
            } else {
                None
            },
            performance_history_: Vec::new(),
            current_learning_rate_: 0.01,
        };

        // Process data in batches
        let batch_size = config.batch_size;
        let mut current_batch_size = batch_size;

        for start_idx in (0..n_samples).step_by(current_batch_size) {
            let end_idx = (start_idx + current_batch_size).min(n_samples);

            // Process batch
            for i in start_idx..end_idx {
                let x_sample = x.row(i).to_owned();
                let y_sample = y[i];

                // Add first model if needed
                if ensemble
                    .active_models_
                    .as_ref()
                    .expect("operation should succeed")
                    .is_empty()
                {
                    ensemble.add_new_model(n_features)?;
                }

                // Partial fit
                ensemble.partial_fit(&x_sample, y_sample)?;
            }

            // Adaptive batch size adjustment
            if config.adaptive_batch_size {
                if ensemble.memory_usage_ > config.memory_threshold_mb * 1024 * 1024 / 2 {
                    current_batch_size /= 2;
                } else if ensemble.memory_usage_ < config.memory_threshold_mb * 1024 * 1024 / 4 {
                    current_batch_size = (current_batch_size * 3 / 2).min(batch_size * 2);
                }
                current_batch_size = current_batch_size.max(100); // Minimum batch size
            }
        }

        Ok(ensemble)
    }
}

impl Predict<Array2<Float>, Array1<Float>> for MemoryEfficientEnsemble<Trained> {
    fn predict(&self, x: &Array2<Float>) -> Result<Array1<Float>> {
        let mut predictions = Array1::zeros(x.nrows());

        for (i, row) in x.axis_iter(Axis(0)).enumerate() {
            predictions[i] = self.predict_single_internal(&row.to_owned())?;
        }

        Ok(predictions)
    }
}

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

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

    #[test]
    fn test_memory_efficient_ensemble_basic() {
        let x = Array2::from_shape_vec(
            (10, 2),
            vec![
                1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0, 5.0, 5.0, 6.0, 6.0, 7.0, 7.0, 8.0, 8.0, 9.0,
                9.0, 10.0, 10.0, 11.0,
            ],
        )
        .expect("operation should succeed");

        let y = array![3.0, 5.0, 7.0, 9.0, 11.0, 13.0, 15.0, 17.0, 19.0, 21.0];

        let ensemble = MemoryEfficientEnsemble::new()
            .max_estimators_in_memory(5)
            .batch_size(3);

        let trained = ensemble.fit(&x, &y).expect("model fitting should succeed");

        assert!(trained.active_model_count() > 0);
        assert!(trained.memory_usage() > 0);

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

    #[test]
    fn test_incremental_learning() {
        let ensemble = MemoryEfficientEnsemble::new()
            .max_estimators_in_memory(3)
            .batch_size(2);

        // Initial training
        let x = Array2::from_shape_vec((4, 2), vec![1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0, 5.0])
            .expect("shape and data length should match");
        let y = array![3.0, 5.0, 7.0, 9.0];

        let mut trained = ensemble.fit(&x, &y).expect("model fitting should succeed");

        // Incremental updates
        let x_new = array![5.0, 6.0];
        trained
            .partial_fit(&x_new, 11.0)
            .expect("operation should succeed");

        assert!(trained.active_model_count() > 0);

        // Test prediction
        let test_x = Array2::from_shape_vec((1, 2), vec![3.0, 4.0])
            .expect("shape and data length should match");
        let predictions = trained.predict(&test_x).expect("prediction should succeed");
        assert_eq!(predictions.len(), 1);
    }

    #[test]
    fn test_memory_management() {
        let ensemble = MemoryEfficientEnsemble::new()
            .max_estimators_in_memory(2)
            .memory_threshold_mb(1); // Very low threshold

        let x = Array2::from_shape_vec((20, 5), (0..100).map(|i| i as Float).collect())
            .expect("shape and data length should match");
        let y = Array1::from_shape_vec(20, (0..20).map(|i| i as Float).collect())
            .expect("shape and data length should match");

        let trained = ensemble.fit(&x, &y).expect("model fitting should succeed");

        // Should have limited number of models due to memory constraints
        assert!(trained.active_model_count() <= 2);
        assert!(trained.total_models_created() >= trained.active_model_count());
    }

    #[test]
    fn test_lazy_evaluation() {
        let ensemble = MemoryEfficientEnsemble::new()
            .lazy_evaluation(true)
            .max_estimators_in_memory(3);

        let x = Array2::from_shape_vec(
            (6, 2),
            vec![1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0, 5.0, 5.0, 6.0, 6.0, 7.0],
        )
        .expect("operation should succeed");
        let y = array![3.0, 5.0, 7.0, 9.0, 11.0, 13.0];

        let trained = ensemble.fit(&x, &y).expect("model fitting should succeed");

        // Test lazy prediction
        let predictions = trained.predict_lazy(&x).expect("operation should succeed");
        assert_eq!(predictions.len(), x.nrows());

        // Test regular prediction for comparison
        let regular_predictions = trained.predict(&x).expect("prediction should succeed");
        assert_eq!(regular_predictions.len(), x.nrows());
    }
}