sklears-multioutput 0.1.0

Multi-output regression and classification
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
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
//! Streaming and Incremental Learning for Multi-Output Prediction
//!
//! This module provides algorithms for learning from streaming data with multiple outputs,
//! including incremental learning, online learning, and concept drift detection.

// Use SciRS2-Core for arrays and random number generation (SciRS2 Policy)
use scirs2_core::ndarray::{Array1, Array2, ArrayView1, ArrayView2, Axis};
use scirs2_core::random::Rng;
use sklears_core::{
    error::{Result as SklResult, SklearsError},
    traits::{Estimator, Fit, Predict, Untrained},
    types::Float,
};
use std::collections::VecDeque;

// ============================================================================
// Incremental Multi-Output Regression
// ============================================================================

/// Configuration for incremental multi-output regression
#[derive(Debug, Clone)]
pub struct IncrementalMultiOutputRegressionConfig {
    /// Learning rate for gradient updates
    pub learning_rate: Float,
    /// L2 regularization parameter
    pub alpha: Float,
    /// Whether to fit intercept
    pub fit_intercept: bool,
    /// Maximum number of samples to keep in memory (for computing statistics)
    pub max_samples: usize,
    /// Whether to use adaptive learning rate
    pub adaptive_learning_rate: bool,
    /// Decay factor for learning rate
    pub learning_rate_decay: Float,
}

impl Default for IncrementalMultiOutputRegressionConfig {
    fn default() -> Self {
        Self {
            learning_rate: 0.01,
            alpha: 0.0001,
            fit_intercept: true,
            max_samples: 10000,
            adaptive_learning_rate: true,
            learning_rate_decay: 0.999,
        }
    }
}

/// Incremental Multi-Output Regressor
///
/// Online learning algorithm that can learn from data streams with multiple outputs.
/// Uses stochastic gradient descent with optional adaptive learning rates.
///
/// # Examples
///
/// ```rust
/// use sklears_multioutput::streaming::{IncrementalMultiOutputRegression, IncrementalMultiOutputRegressionConfig};
/// // Use SciRS2-Core for arrays and random number generation (SciRS2 Policy)
/// use scirs2_core::ndarray::array;
/// use sklears_core::traits::{Fit, Predict};
///
/// let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 4.0]];
/// let y = array![[1.0, 2.0], [2.0, 3.0], [3.0, 4.0]];
///
/// let mut model = IncrementalMultiOutputRegression::new();
/// let trained = model.fit(&X.view(), &y.view()).unwrap();
///
/// // Continue learning with new data
/// let X_new = array![[4.0, 5.0]];
/// let y_new = array![[4.0, 5.0]];
/// let updated = trained.partial_fit(&X_new.view(), &y_new.view()).unwrap();
///
/// let predictions = updated.predict(&X.view()).unwrap();
/// assert_eq!(predictions.dim(), (3, 2));
/// ```
#[derive(Debug, Clone)]
pub struct IncrementalMultiOutputRegression<S = Untrained> {
    state: S,
    config: IncrementalMultiOutputRegressionConfig,
}

/// Trained state for Incremental Multi-Output Regression
#[derive(Debug, Clone)]
pub struct IncrementalMultiOutputRegressionTrained {
    /// Coefficient matrix (n_features x n_outputs)
    pub coef: Array2<Float>,
    /// Intercept vector (n_outputs)
    pub intercept: Array1<Float>,
    /// Number of features
    pub n_features: usize,
    /// Number of outputs
    pub n_outputs: usize,
    /// Number of samples seen so far
    pub n_samples_seen: usize,
    /// Current learning rate
    pub current_learning_rate: Float,
    /// Running mean of features (for normalization)
    pub feature_mean: Array1<Float>,
    /// Running std of features (for normalization)
    pub feature_std: Array1<Float>,
    /// Configuration
    pub config: IncrementalMultiOutputRegressionConfig,
}

impl IncrementalMultiOutputRegression<Untrained> {
    /// Create a new incremental multi-output regressor
    pub fn new() -> Self {
        Self {
            state: Untrained,
            config: IncrementalMultiOutputRegressionConfig::default(),
        }
    }

    /// Set the configuration
    pub fn config(mut self, config: IncrementalMultiOutputRegressionConfig) -> Self {
        self.config = config;
        self
    }

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

    /// Set the regularization parameter
    pub fn alpha(mut self, alpha: Float) -> Self {
        self.config.alpha = alpha;
        self
    }

    /// Set whether to fit intercept
    pub fn fit_intercept(mut self, fit_intercept: bool) -> Self {
        self.config.fit_intercept = fit_intercept;
        self
    }
}

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

impl Fit<ArrayView2<'_, Float>, ArrayView2<'_, Float>>
    for IncrementalMultiOutputRegression<Untrained>
{
    type Fitted = IncrementalMultiOutputRegression<IncrementalMultiOutputRegressionTrained>;

    fn fit(self, X: &ArrayView2<Float>, y: &ArrayView2<Float>) -> SklResult<Self::Fitted> {
        if X.nrows() != y.nrows() {
            return Err(SklearsError::InvalidInput(
                "Number of samples in X and y must match".to_string(),
            ));
        }

        let n_samples = X.nrows();
        let n_features = X.ncols();
        let n_outputs = y.ncols();

        // Initialize coefficients
        let mut coef = Array2::zeros((n_features, n_outputs));
        let mut intercept = Array1::zeros(n_outputs);

        // Compute feature statistics
        let feature_mean = X
            .mean_axis(Axis(0))
            .expect("array should have elements for mean computation");
        let feature_std = X.std_axis(Axis(0), 0.0);

        let mut current_learning_rate = self.config.learning_rate;

        // Perform initial gradient descent over the batch
        for _ in 0..10 {
            // Mini-batch iterations
            for i in 0..n_samples {
                let x_i = X.row(i);
                let y_i = y.row(i);

                // Prediction
                let pred = coef.t().dot(&x_i) + &intercept;

                // Error
                let error = &y_i - &pred;

                // Update coefficients using gradient descent
                for j in 0..n_features {
                    for k in 0..n_outputs {
                        let gradient = -error[k] * x_i[j] + self.config.alpha * coef[[j, k]];
                        coef[[j, k]] -= current_learning_rate * gradient;
                    }
                }

                // Update intercept
                if self.config.fit_intercept {
                    for k in 0..n_outputs {
                        intercept[k] += current_learning_rate * error[k];
                    }
                }
            }

            // Decay learning rate
            if self.config.adaptive_learning_rate {
                current_learning_rate *= self.config.learning_rate_decay;
            }
        }

        Ok(IncrementalMultiOutputRegression {
            state: IncrementalMultiOutputRegressionTrained {
                coef,
                intercept,
                n_features,
                n_outputs,
                n_samples_seen: n_samples,
                current_learning_rate,
                feature_mean,
                feature_std,
                config: self.config,
            },
            config: IncrementalMultiOutputRegressionConfig::default(),
        })
    }
}

impl IncrementalMultiOutputRegression<IncrementalMultiOutputRegressionTrained> {
    /// Partial fit on new data (incremental learning)
    pub fn partial_fit(mut self, X: &ArrayView2<Float>, y: &ArrayView2<Float>) -> SklResult<Self> {
        if X.nrows() != y.nrows() {
            return Err(SklearsError::InvalidInput(
                "Number of samples in X and y must match".to_string(),
            ));
        }

        if X.ncols() != self.state.n_features {
            return Err(SklearsError::InvalidInput(format!(
                "Expected {} features, got {}",
                self.state.n_features,
                X.ncols()
            )));
        }

        if y.ncols() != self.state.n_outputs {
            return Err(SklearsError::InvalidInput(format!(
                "Expected {} outputs, got {}",
                self.state.n_outputs,
                y.ncols()
            )));
        }

        let n_samples = X.nrows();

        // Update feature statistics (running average)
        let n_old = self.state.n_samples_seen as Float;
        let n_new = n_samples as Float;
        let n_total = n_old + n_new;

        let new_mean = X
            .mean_axis(Axis(0))
            .expect("array should have elements for mean computation");
        self.state.feature_mean = (&self.state.feature_mean * n_old + &new_mean * n_new) / n_total;

        // Perform incremental updates
        for i in 0..n_samples {
            let x_i = X.row(i);
            let y_i = y.row(i);

            // Prediction
            let pred = self.state.coef.t().dot(&x_i) + &self.state.intercept;

            // Error
            let error = &y_i - &pred;

            // Update coefficients
            for j in 0..self.state.n_features {
                for k in 0..self.state.n_outputs {
                    let gradient =
                        -error[k] * x_i[j] + self.state.config.alpha * self.state.coef[[j, k]];
                    self.state.coef[[j, k]] -= self.state.current_learning_rate * gradient;
                }
            }

            // Update intercept
            if self.state.config.fit_intercept {
                for k in 0..self.state.n_outputs {
                    self.state.intercept[k] += self.state.current_learning_rate * error[k];
                }
            }
        }

        // Update statistics
        self.state.n_samples_seen += n_samples;

        // Decay learning rate
        if self.state.config.adaptive_learning_rate {
            self.state.current_learning_rate *= self.state.config.learning_rate_decay;
        }

        Ok(self)
    }

    /// Get the current coefficients
    pub fn coef(&self) -> &Array2<Float> {
        &self.state.coef
    }

    /// Get the current intercept
    pub fn intercept(&self) -> &Array1<Float> {
        &self.state.intercept
    }

    /// Get number of samples seen
    pub fn n_samples_seen(&self) -> usize {
        self.state.n_samples_seen
    }

    /// Get current learning rate
    pub fn current_learning_rate(&self) -> Float {
        self.state.current_learning_rate
    }
}

impl Predict<ArrayView2<'_, Float>, Array2<Float>>
    for IncrementalMultiOutputRegression<IncrementalMultiOutputRegressionTrained>
{
    fn predict(&self, X: &ArrayView2<Float>) -> SklResult<Array2<Float>> {
        if X.ncols() != self.state.n_features {
            return Err(SklearsError::InvalidInput(format!(
                "Expected {} features, got {}",
                self.state.n_features,
                X.ncols()
            )));
        }

        let n_samples = X.nrows();
        let mut predictions = Array2::zeros((n_samples, self.state.n_outputs));

        for i in 0..n_samples {
            let x_i = X.row(i);
            let pred = self.state.coef.t().dot(&x_i) + &self.state.intercept;
            predictions.row_mut(i).assign(&pred);
        }

        Ok(predictions)
    }
}

impl Estimator for IncrementalMultiOutputRegression<Untrained> {
    type Config = IncrementalMultiOutputRegressionConfig;
    type Error = SklearsError;
    type Float = Float;

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

impl Estimator for IncrementalMultiOutputRegression<IncrementalMultiOutputRegressionTrained> {
    type Config = IncrementalMultiOutputRegressionConfig;
    type Error = SklearsError;
    type Float = Float;

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

// ============================================================================
// Streaming Multi-Output with Mini-Batches
// ============================================================================

/// Configuration for streaming multi-output learning
#[derive(Debug, Clone)]
pub struct StreamingMultiOutputConfig {
    /// Mini-batch size for streaming updates
    pub batch_size: usize,
    /// Maximum buffer size before forced update
    pub max_buffer_size: usize,
    /// Learning rate
    pub learning_rate: Float,
    /// Whether to detect concept drift
    pub detect_drift: bool,
    /// Window size for drift detection
    pub drift_window_size: usize,
    /// Threshold for drift detection
    pub drift_threshold: Float,
}

impl Default for StreamingMultiOutputConfig {
    fn default() -> Self {
        Self {
            batch_size: 32,
            max_buffer_size: 1000,
            learning_rate: 0.01,
            detect_drift: true,
            drift_window_size: 100,
            drift_threshold: 0.1,
        }
    }
}

/// Streaming Multi-Output Learner
///
/// Handles streaming data with mini-batch processing and concept drift detection.
///
/// # Examples
///
/// ```rust
/// use sklears_multioutput::streaming::{StreamingMultiOutput, StreamingMultiOutputConfig};
/// // Use SciRS2-Core for arrays and random number generation (SciRS2 Policy)
/// use scirs2_core::ndarray::array;
/// use sklears_core::traits::{Fit, Predict};
///
/// let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 4.0]];
/// let y = array![[1.0, 2.0], [2.0, 3.0], [3.0, 4.0]];
///
/// let mut model = StreamingMultiOutput::new()
///     .batch_size(2)
///     .learning_rate(0.1);
///
/// let trained = model.fit(&X.view(), &y.view()).unwrap();
///
/// // Add streaming data
/// let X_stream = array![[4.0, 5.0]];
/// let y_stream = array![[4.0, 5.0]];
/// let updated = trained.update_stream(&X_stream.view(), &y_stream.view()).unwrap();
///
/// let predictions = updated.predict(&X.view()).unwrap();
/// assert_eq!(predictions.dim(), (3, 2));
/// ```
#[derive(Debug, Clone)]
pub struct StreamingMultiOutput<S = Untrained> {
    state: S,
    config: StreamingMultiOutputConfig,
}

/// Trained state for Streaming Multi-Output
#[derive(Debug, Clone)]
pub struct StreamingMultiOutputTrained {
    /// Base incremental model
    pub base_model: IncrementalMultiOutputRegressionTrained,
    /// Buffer for mini-batch processing
    pub buffer_X: VecDeque<Array1<Float>>,
    pub buffer_y: VecDeque<Array1<Float>>,
    /// Performance history for drift detection
    pub error_history: VecDeque<Float>,
    /// Whether drift was detected
    pub drift_detected: bool,
    /// Number of drift events detected
    pub n_drift_events: usize,
    /// Configuration
    pub config: StreamingMultiOutputConfig,
}

impl StreamingMultiOutput<Untrained> {
    /// Create a new streaming multi-output learner
    pub fn new() -> Self {
        Self {
            state: Untrained,
            config: StreamingMultiOutputConfig::default(),
        }
    }

    /// Set the configuration
    pub fn config(mut self, config: StreamingMultiOutputConfig) -> Self {
        self.config = config;
        self
    }

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

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

    /// Enable/disable drift detection
    pub fn detect_drift(mut self, detect: bool) -> Self {
        self.config.detect_drift = detect;
        self
    }
}

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

impl Fit<ArrayView2<'_, Float>, ArrayView2<'_, Float>> for StreamingMultiOutput<Untrained> {
    type Fitted = StreamingMultiOutput<StreamingMultiOutputTrained>;

    fn fit(self, X: &ArrayView2<Float>, y: &ArrayView2<Float>) -> SklResult<Self::Fitted> {
        // Initialize base model
        let base_config = IncrementalMultiOutputRegressionConfig {
            learning_rate: self.config.learning_rate,
            ..Default::default()
        };

        let base_model = IncrementalMultiOutputRegression::new()
            .config(base_config)
            .fit(X, y)?;

        Ok(StreamingMultiOutput {
            state: StreamingMultiOutputTrained {
                base_model: base_model.state,
                buffer_X: VecDeque::new(),
                buffer_y: VecDeque::new(),
                error_history: VecDeque::new(),
                drift_detected: false,
                n_drift_events: 0,
                config: self.config,
            },
            config: StreamingMultiOutputConfig::default(),
        })
    }
}

impl StreamingMultiOutput<StreamingMultiOutputTrained> {
    /// Update with streaming data
    pub fn update_stream(
        mut self,
        X: &ArrayView2<Float>,
        y: &ArrayView2<Float>,
    ) -> SklResult<Self> {
        // Add to buffer
        for i in 0..X.nrows() {
            self.state.buffer_X.push_back(X.row(i).to_owned());
            self.state.buffer_y.push_back(y.row(i).to_owned());
        }

        // Process if buffer is full
        if self.state.buffer_X.len() >= self.state.config.batch_size {
            self = self.process_buffer()?;
        }

        Ok(self)
    }

    /// Process the current buffer
    fn process_buffer(mut self) -> SklResult<Self> {
        let batch_size = self.state.config.batch_size.min(self.state.buffer_X.len());

        if batch_size == 0 {
            return Ok(self);
        }

        // Extract batch from buffer
        let mut X_batch = Array2::zeros((batch_size, self.state.base_model.n_features));
        let mut y_batch = Array2::zeros((batch_size, self.state.base_model.n_outputs));

        for i in 0..batch_size {
            let x = self
                .state
                .buffer_X
                .pop_front()
                .expect("operation should succeed");
            let y = self
                .state
                .buffer_y
                .pop_front()
                .expect("operation should succeed");
            X_batch.row_mut(i).assign(&x);
            y_batch.row_mut(i).assign(&y);
        }

        // Detect drift if enabled
        if self.state.config.detect_drift {
            let pred = self.predict(&X_batch.view())?;
            let error: Float = (&y_batch - &pred)
                .mapv(|x| x.powi(2))
                .mean()
                .expect("array should have elements for mean computation");

            self.state.error_history.push_back(error);
            if self.state.error_history.len() > self.state.config.drift_window_size {
                self.state.error_history.pop_front();
            }

            // Check for drift
            if self.state.error_history.len() >= self.state.config.drift_window_size {
                let recent_error: Float = self
                    .state
                    .error_history
                    .iter()
                    .rev()
                    .take(self.state.config.drift_window_size / 2)
                    .sum::<Float>()
                    / (self.state.config.drift_window_size / 2) as Float;

                let old_error: Float = self
                    .state
                    .error_history
                    .iter()
                    .take(self.state.config.drift_window_size / 2)
                    .sum::<Float>()
                    / (self.state.config.drift_window_size / 2) as Float;

                if recent_error > old_error * (1.0 + self.state.config.drift_threshold) {
                    self.state.drift_detected = true;
                    self.state.n_drift_events += 1;
                    // Could reset model here if needed
                }
            }
        }

        // Update base model
        let base_wrapper = IncrementalMultiOutputRegression {
            state: self.state.base_model.clone(),
            config: IncrementalMultiOutputRegressionConfig::default(),
        };

        let updated = base_wrapper.partial_fit(&X_batch.view(), &y_batch.view())?;
        self.state.base_model = updated.state;

        Ok(self)
    }

    /// Force processing of remaining buffer
    pub fn flush_buffer(mut self) -> SklResult<Self> {
        while !self.state.buffer_X.is_empty() {
            self = self.process_buffer()?;
        }
        Ok(self)
    }

    /// Check if drift was detected
    pub fn drift_detected(&self) -> bool {
        self.state.drift_detected
    }

    /// Get number of drift events
    pub fn n_drift_events(&self) -> usize {
        self.state.n_drift_events
    }

    /// Get buffer size
    pub fn buffer_size(&self) -> usize {
        self.state.buffer_X.len()
    }
}

impl Predict<ArrayView2<'_, Float>, Array2<Float>>
    for StreamingMultiOutput<StreamingMultiOutputTrained>
{
    fn predict(&self, X: &ArrayView2<Float>) -> SklResult<Array2<Float>> {
        let base_wrapper = IncrementalMultiOutputRegression {
            state: self.state.base_model.clone(),
            config: IncrementalMultiOutputRegressionConfig::default(),
        };
        base_wrapper.predict(X)
    }
}

impl Estimator for StreamingMultiOutput<Untrained> {
    type Config = StreamingMultiOutputConfig;
    type Error = SklearsError;
    type Float = Float;

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

impl Estimator for StreamingMultiOutput<StreamingMultiOutputTrained> {
    type Config = StreamingMultiOutputConfig;
    type Error = SklearsError;
    type Float = Float;

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

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_abs_diff_eq;
    // Use SciRS2-Core for arrays and random number generation (SciRS2 Policy)
    use scirs2_core::ndarray::array;

    #[test]
    #[allow(non_snake_case)]
    fn test_incremental_regression_basic() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 4.0]];
        let y = array![[1.0, 2.0], [2.0, 3.0], [3.0, 4.0]];

        let model = IncrementalMultiOutputRegression::new()
            .learning_rate(0.1)
            .alpha(0.0001);

        let trained = model
            .fit(&X.view(), &y.view())
            .expect("model fitting should succeed");
        let predictions = trained
            .predict(&X.view())
            .expect("prediction should succeed");

        assert_eq!(predictions.dim(), (3, 2));
        assert_eq!(trained.n_samples_seen(), 3);
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_incremental_regression_partial_fit() {
        let X1 = array![[1.0, 2.0], [2.0, 3.0]];
        let y1 = array![[1.0, 2.0], [2.0, 3.0]];

        let model = IncrementalMultiOutputRegression::new().learning_rate(0.1);
        let trained = model
            .fit(&X1.view(), &y1.view())
            .expect("model fitting should succeed");

        // Partial fit with new data
        let X2 = array![[3.0, 4.0], [4.0, 5.0]];
        let y2 = array![[3.0, 4.0], [4.0, 5.0]];
        let updated = trained
            .partial_fit(&X2.view(), &y2.view())
            .expect("operation should succeed");

        assert_eq!(updated.n_samples_seen(), 4);

        let predictions = updated
            .predict(&X2.view())
            .expect("prediction should succeed");
        assert_eq!(predictions.dim(), (2, 2));
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_incremental_regression_learning_rate_decay() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1.0, 2.0], [2.0, 3.0]];

        let model = IncrementalMultiOutputRegression::new().learning_rate(0.1);
        let trained = model
            .fit(&X.view(), &y.view())
            .expect("model fitting should succeed");

        let initial_lr = trained.current_learning_rate();

        // Partial fit should decay learning rate
        let X2 = array![[3.0, 4.0]];
        let y2 = array![[3.0, 4.0]];
        let updated = trained
            .partial_fit(&X2.view(), &y2.view())
            .expect("operation should succeed");

        assert!(updated.current_learning_rate() < initial_lr);
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_streaming_basic() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 4.0]];
        let y = array![[1.0, 2.0], [2.0, 3.0], [3.0, 4.0]];

        let model = StreamingMultiOutput::new().batch_size(2).learning_rate(0.1);

        let trained = model
            .fit(&X.view(), &y.view())
            .expect("model fitting should succeed");
        let predictions = trained
            .predict(&X.view())
            .expect("prediction should succeed");

        assert_eq!(predictions.dim(), (3, 2));
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_streaming_update() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1.0, 2.0], [2.0, 3.0]];

        let model = StreamingMultiOutput::new().batch_size(2);
        let trained = model
            .fit(&X.view(), &y.view())
            .expect("model fitting should succeed");

        // Stream new data
        let X_stream = array![[3.0, 4.0], [4.0, 5.0]];
        let y_stream = array![[3.0, 4.0], [4.0, 5.0]];
        let updated = trained
            .update_stream(&X_stream.view(), &y_stream.view())
            .expect("operation should succeed");

        let predictions = updated
            .predict(&X_stream.view())
            .expect("prediction should succeed");
        assert_eq!(predictions.dim(), (2, 2));
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_streaming_buffer() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1.0, 2.0], [2.0, 3.0]];

        let model = StreamingMultiOutput::new().batch_size(5); // Large batch size
        let trained = model
            .fit(&X.view(), &y.view())
            .expect("model fitting should succeed");

        // Add small amount of data (should buffer)
        let X_stream = array![[3.0, 4.0]];
        let y_stream = array![[3.0, 4.0]];
        let updated = trained
            .update_stream(&X_stream.view(), &y_stream.view())
            .expect("operation should succeed");

        assert_eq!(updated.buffer_size(), 1);

        // Flush buffer
        let flushed = updated.flush_buffer().expect("operation should succeed");
        assert_eq!(flushed.buffer_size(), 0);
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_streaming_drift_detection() {
        let X = array![[1.0, 2.0], [2.0, 3.0], [3.0, 4.0]];
        let y = array![[1.0, 2.0], [2.0, 3.0], [3.0, 4.0]];

        let model = StreamingMultiOutput::new()
            .batch_size(2)
            .detect_drift(true)
            .learning_rate(0.1);

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

        // The model should track drift events
        assert_eq!(trained.n_drift_events(), 0);
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_incremental_regression_error_handling() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1.0, 2.0], [2.0, 3.0], [3.0, 4.0]]; // Mismatched

        let model = IncrementalMultiOutputRegression::new();
        assert!(model.fit(&X.view(), &y.view()).is_err());
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_incremental_regression_prediction_error() {
        let X = array![[1.0, 2.0], [2.0, 3.0]];
        let y = array![[1.0, 2.0], [2.0, 3.0]];

        let model = IncrementalMultiOutputRegression::new();
        let trained = model
            .fit(&X.view(), &y.view())
            .expect("model fitting should succeed");

        // Wrong number of features
        let X_test = array![[1.0]];
        assert!(trained.predict(&X_test.view()).is_err());
    }
}