Skip to main content

sklears_tree/
multi_output.rs

1//! Multi-output decision trees and multi-label classification
2//!
3//! This module provides extensions for handling multiple outputs simultaneously,
4//! including multi-output regression and multi-label classification.
5
6use scirs2_core::ndarray::{Array1, Array2, Axis};
7use sklears_core::{
8    error::Result,
9    prelude::SklearsError,
10    traits::{Trained, Untrained},
11};
12use std::collections::HashMap;
13use std::marker::PhantomData;
14
15use crate::decision_tree::DecisionTreeConfig;
16use crate::random_forest::RandomForestConfig;
17
18/// Multi-output strategy for handling multiple targets
19#[derive(Debug, Clone, Copy)]
20pub enum MultiOutputStrategy {
21    /// Train independent models for each output
22    Independent,
23    /// Use shared tree structure with multi-output splits
24    Shared,
25    /// Chain outputs (predict each output using previous predictions as features)
26    Chained,
27}
28
29/// Label correlation strategy for multi-label classification
30#[derive(Debug, Clone)]
31pub enum LabelCorrelation {
32    /// Ignore label correlations (treat as independent)
33    Independent,
34    /// Model label correlations using label co-occurrence
35    Cooccurrence { min_support: f64 },
36    /// Use label hierarchy if available
37    Hierarchical { hierarchy: Vec<(usize, usize)> }, // (parent, child) pairs
38    /// Exploit label correlations through dimensionality reduction
39    Embedded { n_components: usize },
40}
41
42/// Configuration for multi-output decision trees
43#[derive(Debug, Clone)]
44pub struct MultiOutputTreeConfig {
45    /// Base decision tree configuration
46    pub base_config: DecisionTreeConfig,
47    /// Strategy for handling multiple outputs
48    pub multi_output_strategy: MultiOutputStrategy,
49    /// Label correlation strategy (for multi-label classification)
50    pub label_correlation: LabelCorrelation,
51    /// Minimum samples required for multi-output split
52    pub min_samples_multioutput_split: usize,
53    /// Enable feature sharing across outputs
54    pub enable_feature_sharing: bool,
55    /// Output-specific feature weights
56    pub output_feature_weights: Option<Array2<f64>>,
57}
58
59impl Default for MultiOutputTreeConfig {
60    fn default() -> Self {
61        Self {
62            base_config: DecisionTreeConfig::default(),
63            multi_output_strategy: MultiOutputStrategy::Independent,
64            label_correlation: LabelCorrelation::Independent,
65            min_samples_multioutput_split: 10,
66            enable_feature_sharing: true,
67            output_feature_weights: None,
68        }
69    }
70}
71
72/// Multi-output decision tree for regression and classification
73pub struct MultiOutputDecisionTree<State = Untrained> {
74    config: MultiOutputTreeConfig,
75    trees: Vec<Box<dyn MultiOutputTreeModel>>,
76    n_outputs: usize,
77    n_features: usize,
78    output_types: Vec<OutputType>,
79    label_correlations: Option<LabelCorrelationMatrix>,
80    state: PhantomData<State>,
81}
82
83/// Type of output (regression or classification)
84#[derive(Debug, Clone, Copy)]
85pub enum OutputType {
86    Regression,
87    Classification { n_classes: usize },
88}
89
90/// Label correlation matrix for multi-label problems
91#[derive(Debug, Clone)]
92pub struct LabelCorrelationMatrix {
93    /// Correlation coefficients between labels
94    correlations: Array2<f64>,
95    /// Co-occurrence frequencies
96    cooccurrence: Array2<usize>,
97    /// Label hierarchy (if applicable)
98    hierarchy: Option<Vec<(usize, usize)>>,
99}
100
101impl LabelCorrelationMatrix {
102    /// Pairwise Pearson correlation coefficients between labels
103    pub fn correlations(&self) -> &Array2<f64> {
104        &self.correlations
105    }
106
107    /// Raw co-occurrence count matrix between labels
108    pub fn cooccurrence(&self) -> &Array2<usize> {
109        &self.cooccurrence
110    }
111
112    /// Optional label hierarchy as (parent, child) index pairs
113    pub fn hierarchy(&self) -> Option<&Vec<(usize, usize)>> {
114        self.hierarchy.as_ref()
115    }
116}
117
118/// Trait for models that can handle multiple outputs
119pub trait MultiOutputTreeModel: Send + Sync {
120    /// Fit the model to multi-output data
121    fn fit_multi(&mut self, x: &Array2<f64>, y: &Array2<f64>) -> Result<()>;
122
123    /// Predict multiple outputs
124    fn predict_multi(&self, x: &Array2<f64>) -> Result<Array2<f64>>;
125
126    /// Get feature importances for each output
127    fn feature_importances_multi(&self) -> Result<Array2<f64>>;
128}
129
130/// Independent multi-output tree model (one tree per output)
131#[derive(Debug)]
132pub struct IndependentMultiOutputTree {
133    /// Individual trees for each output
134    trees: Vec<SingleOutputTree>,
135    /// Number of outputs
136    n_outputs: usize,
137    /// Number of features
138    n_features: usize,
139}
140
141/// Single output tree wrapper
142#[derive(Debug)]
143pub struct SingleOutputTree {
144    /// Tree structure (simplified)
145    nodes: Vec<MultiOutputTreeNode>,
146    /// Output type
147    output_type: OutputType,
148    /// Feature importances
149    feature_importances: Array1<f64>,
150    /// Tree configuration (max_depth, min_samples_split, etc.)
151    config: DecisionTreeConfig,
152}
153
154/// Multi-output tree node
155#[derive(Debug, Clone)]
156pub struct MultiOutputTreeNode {
157    /// Feature index for split (None for leaf)
158    feature_idx: Option<usize>,
159    /// Split threshold (None for leaf)
160    threshold: Option<f64>,
161    /// Predictions for each output (for leaves)
162    predictions: Array1<f64>,
163    /// Left child ID
164    left_child: Option<usize>,
165    /// Right child ID
166    right_child: Option<usize>,
167    /// Sample indices for this node
168    samples: Vec<usize>,
169    /// Node depth
170    depth: usize,
171    /// Is this a leaf node?
172    is_leaf: bool,
173}
174
175impl SingleOutputTree {
176    /// Create a new single output tree with default configuration.
177    pub fn new(output_type: OutputType, n_features: usize) -> Self {
178        Self::with_config(output_type, n_features, DecisionTreeConfig::default())
179    }
180
181    /// Create a new single output tree with the given configuration.
182    pub fn with_config(
183        output_type: OutputType,
184        n_features: usize,
185        config: DecisionTreeConfig,
186    ) -> Self {
187        Self {
188            nodes: Vec::new(),
189            output_type,
190            feature_importances: Array1::zeros(n_features),
191            config,
192        }
193    }
194
195    /// Fit tree to single output
196    pub fn fit(&mut self, x: &Array2<f64>, y: &Array1<f64>) -> Result<()> {
197        let n_samples = x.nrows();
198        let samples: Vec<usize> = (0..n_samples).collect();
199
200        // Create root node
201        let root = self.create_node(0, samples, x, y, 0)?;
202        self.nodes = vec![root];
203
204        // Build tree recursively
205        self.build_tree(0, x, y)?;
206
207        Ok(())
208    }
209
210    /// Create a tree node
211    fn create_node(
212        &self,
213        _id: usize,
214        samples: Vec<usize>,
215        _x: &Array2<f64>,
216        y: &Array1<f64>,
217        depth: usize,
218    ) -> Result<MultiOutputTreeNode> {
219        let n_outputs = 1; // Single output
220        let mut predictions = Array1::zeros(n_outputs);
221
222        if !samples.is_empty() {
223            // Calculate prediction based on output type
224            match self.output_type {
225                OutputType::Regression => {
226                    let sum: f64 = samples.iter().map(|&i| y[i]).sum();
227                    predictions[0] = sum / samples.len() as f64;
228                }
229                OutputType::Classification { .. } => {
230                    // Majority class
231                    let mut class_counts: HashMap<i32, usize> = HashMap::new();
232                    for &sample_idx in &samples {
233                        let class = y[sample_idx] as i32;
234                        *class_counts.entry(class).or_insert(0) += 1;
235                    }
236
237                    if let Some((&majority_class, _)) =
238                        class_counts.iter().max_by_key(|(_, &count)| count)
239                    {
240                        predictions[0] = majority_class as f64;
241                    }
242                }
243            }
244        }
245
246        Ok(MultiOutputTreeNode {
247            feature_idx: None,
248            threshold: None,
249            predictions,
250            left_child: None,
251            right_child: None,
252            samples,
253            depth,
254            is_leaf: true,
255        })
256    }
257
258    /// Build tree recursively
259    fn build_tree(&mut self, node_id: usize, x: &Array2<f64>, y: &Array1<f64>) -> Result<()> {
260        let node = &self.nodes[node_id].clone();
261
262        let max_depth = self.config.max_depth.unwrap_or(10);
263        let min_samples_split = self.config.min_samples_split.max(2);
264        if node.samples.len() < min_samples_split || node.depth >= max_depth {
265            return Ok(());
266        }
267
268        // Find best split
269        if let Some((feature_idx, threshold)) = self.find_best_split(x, y, &node.samples)? {
270            // Split samples
271            let (left_samples, right_samples) =
272                self.split_samples(x, &node.samples, feature_idx, threshold);
273
274            if !left_samples.is_empty() && !right_samples.is_empty() {
275                // Create child nodes
276                let left_id = self.nodes.len();
277                let right_id = self.nodes.len() + 1;
278
279                let left_node = self.create_node(left_id, left_samples, x, y, node.depth + 1)?;
280                let right_node = self.create_node(right_id, right_samples, x, y, node.depth + 1)?;
281
282                // Update parent node
283                self.nodes[node_id].is_leaf = false;
284                self.nodes[node_id].feature_idx = Some(feature_idx);
285                self.nodes[node_id].threshold = Some(threshold);
286                self.nodes[node_id].left_child = Some(left_id);
287                self.nodes[node_id].right_child = Some(right_id);
288
289                // Add child nodes
290                self.nodes.push(left_node);
291                self.nodes.push(right_node);
292
293                // Update feature importance
294                self.feature_importances[feature_idx] += 1.0;
295
296                // Recursively build subtrees
297                self.build_tree(left_id, x, y)?;
298                self.build_tree(right_id, x, y)?;
299            }
300        }
301
302        Ok(())
303    }
304
305    /// Find best split for a node
306    fn find_best_split(
307        &self,
308        x: &Array2<f64>,
309        y: &Array1<f64>,
310        samples: &[usize],
311    ) -> Result<Option<(usize, f64)>> {
312        let n_features = x.ncols();
313        let mut best_split: Option<(usize, f64, f64)> = None; // (feature, threshold, impurity_reduction)
314
315        for feature_idx in 0..n_features {
316            // Get unique values for this feature
317            let mut values: Vec<f64> = samples.iter().map(|&i| x[[i, feature_idx]]).collect();
318            values.sort_by(|a, b| a.partial_cmp(b).expect("operation should succeed"));
319            values.dedup();
320
321            // Try splits between consecutive values
322            for i in 0..values.len().saturating_sub(1) {
323                let threshold = (values[i] + values[i + 1]) / 2.0;
324                let impurity_reduction =
325                    self.calculate_impurity_reduction(x, y, samples, feature_idx, threshold);
326
327                if best_split.is_none()
328                    || impurity_reduction > best_split.as_ref().expect("operation should succeed").2
329                {
330                    best_split = Some((feature_idx, threshold, impurity_reduction));
331                }
332            }
333        }
334
335        if let Some((feature_idx, threshold, reduction)) = best_split {
336            if reduction > 0.001 {
337                // Minimum improvement threshold
338                Ok(Some((feature_idx, threshold)))
339            } else {
340                Ok(None)
341            }
342        } else {
343            Ok(None)
344        }
345    }
346
347    /// Calculate impurity reduction for a potential split
348    fn calculate_impurity_reduction(
349        &self,
350        x: &Array2<f64>,
351        y: &Array1<f64>,
352        samples: &[usize],
353        feature_idx: usize,
354        threshold: f64,
355    ) -> f64 {
356        let (left_samples, right_samples) = self.split_samples(x, samples, feature_idx, threshold);
357
358        if left_samples.is_empty() || right_samples.is_empty() {
359            return 0.0;
360        }
361
362        let parent_impurity = self.calculate_impurity(y, samples);
363        let left_impurity = self.calculate_impurity(y, &left_samples);
364        let right_impurity = self.calculate_impurity(y, &right_samples);
365
366        let left_weight = left_samples.len() as f64 / samples.len() as f64;
367        let right_weight = right_samples.len() as f64 / samples.len() as f64;
368
369        parent_impurity - (left_weight * left_impurity + right_weight * right_impurity)
370    }
371
372    /// Calculate impurity for a set of samples
373    fn calculate_impurity(&self, y: &Array1<f64>, samples: &[usize]) -> f64 {
374        if samples.is_empty() {
375            return 0.0;
376        }
377
378        match self.output_type {
379            OutputType::Regression => {
380                // MSE for regression
381                let mean = samples.iter().map(|&i| y[i]).sum::<f64>() / samples.len() as f64;
382                samples.iter().map(|&i| (y[i] - mean).powi(2)).sum::<f64>() / samples.len() as f64
383            }
384            OutputType::Classification { .. } => {
385                // Gini impurity for classification
386                let mut class_counts: HashMap<i32, usize> = HashMap::new();
387                for &sample_idx in samples {
388                    let class = y[sample_idx] as i32;
389                    *class_counts.entry(class).or_insert(0) += 1;
390                }
391
392                let total = samples.len() as f64;
393                let mut gini = 1.0;
394                for &count in class_counts.values() {
395                    let prob = count as f64 / total;
396                    gini -= prob * prob;
397                }
398                gini
399            }
400        }
401    }
402
403    /// Split samples based on feature and threshold
404    fn split_samples(
405        &self,
406        x: &Array2<f64>,
407        samples: &[usize],
408        feature_idx: usize,
409        threshold: f64,
410    ) -> (Vec<usize>, Vec<usize>) {
411        let mut left_samples = Vec::new();
412        let mut right_samples = Vec::new();
413
414        for &sample_idx in samples {
415            if x[[sample_idx, feature_idx]] <= threshold {
416                left_samples.push(sample_idx);
417            } else {
418                right_samples.push(sample_idx);
419            }
420        }
421
422        (left_samples, right_samples)
423    }
424
425    /// Predict on new data
426    pub fn predict(&self, x: &Array2<f64>) -> Result<Array1<f64>> {
427        let mut predictions = Array1::zeros(x.nrows());
428
429        for (sample_idx, sample) in x.rows().into_iter().enumerate() {
430            predictions[sample_idx] = self.predict_single(&sample.to_owned())?;
431        }
432
433        Ok(predictions)
434    }
435
436    /// Predict single sample
437    fn predict_single(&self, x: &Array1<f64>) -> Result<f64> {
438        if self.nodes.is_empty() {
439            return Err(SklearsError::PredictError("Tree not fitted".to_string()));
440        }
441
442        let mut node_idx = 0;
443
444        loop {
445            let node = &self.nodes[node_idx];
446
447            if node.is_leaf {
448                return Ok(node.predictions[0]);
449            }
450
451            if let (Some(feature_idx), Some(threshold)) = (node.feature_idx, node.threshold) {
452                if feature_idx >= x.len() {
453                    return Err(SklearsError::PredictError(
454                        "Feature index out of bounds".to_string(),
455                    ));
456                }
457
458                if x[feature_idx] <= threshold {
459                    if let Some(left_child) = node.left_child {
460                        node_idx = left_child;
461                    } else {
462                        return Ok(node.predictions[0]);
463                    }
464                } else {
465                    if let Some(right_child) = node.right_child {
466                        node_idx = right_child;
467                    } else {
468                        return Ok(node.predictions[0]);
469                    }
470                }
471            } else {
472                return Ok(node.predictions[0]);
473            }
474        }
475    }
476}
477
478/// Shared multi-output tree: one decision tree where each leaf stores
479/// predictions for all output dimensions.  The split criterion at each
480/// internal node sums the variance/impurity reduction over all outputs.
481#[derive(Debug)]
482pub struct SharedMultiOutputTree {
483    /// Nodes — index 0 is the root
484    nodes: Vec<SharedMultiOutputTreeNode>,
485    /// Number of outputs
486    n_outputs: usize,
487    /// Number of features
488    n_features: usize,
489    /// Per-output type (regression / classification)
490    output_types: Vec<OutputType>,
491    /// Aggregate feature importances (summed over outputs)
492    feature_importances: Array1<f64>,
493    /// Config for depth / samples limits
494    config: DecisionTreeConfig,
495}
496
497/// One node in the shared multi-output tree
498#[derive(Debug, Clone)]
499struct SharedMultiOutputTreeNode {
500    feature_idx: Option<usize>,
501    threshold: Option<f64>,
502    /// Prediction vector — one value per output
503    predictions: Array1<f64>,
504    left_child: Option<usize>,
505    right_child: Option<usize>,
506    samples: Vec<usize>,
507    depth: usize,
508    is_leaf: bool,
509}
510
511impl SharedMultiOutputTree {
512    /// Create a new shared multi-output tree
513    pub fn new(
514        n_outputs: usize,
515        n_features: usize,
516        output_types: Vec<OutputType>,
517        config: DecisionTreeConfig,
518    ) -> Self {
519        Self {
520            nodes: Vec::new(),
521            n_outputs,
522            n_features,
523            output_types,
524            feature_importances: Array1::zeros(n_features),
525            config,
526        }
527    }
528
529    /// Compute multi-output predictions for a set of samples (mean / majority per output)
530    fn compute_predictions(&self, samples: &[usize], y: &Array2<f64>) -> Array1<f64> {
531        let mut preds = Array1::zeros(self.n_outputs);
532        if samples.is_empty() {
533            return preds;
534        }
535        for (out_idx, output_type) in self.output_types.iter().enumerate() {
536            match output_type {
537                OutputType::Regression => {
538                    let sum: f64 = samples.iter().map(|&i| y[[i, out_idx]]).sum();
539                    preds[out_idx] = sum / samples.len() as f64;
540                }
541                OutputType::Classification { .. } => {
542                    let mut counts: HashMap<i32, usize> = HashMap::new();
543                    for &i in samples {
544                        let cls = y[[i, out_idx]] as i32;
545                        *counts.entry(cls).or_insert(0) += 1;
546                    }
547                    if let Some((&cls, _)) = counts.iter().max_by_key(|(_, &c)| c) {
548                        preds[out_idx] = cls as f64;
549                    }
550                }
551            }
552        }
553        preds
554    }
555
556    /// Weighted variance/impurity summed over all outputs for the given sample subset
557    fn multi_output_impurity(&self, samples: &[usize], y: &Array2<f64>) -> f64 {
558        if samples.is_empty() {
559            return 0.0;
560        }
561        let mut total = 0.0;
562        for (out_idx, output_type) in self.output_types.iter().enumerate() {
563            match output_type {
564                OutputType::Regression => {
565                    let mean = samples.iter().map(|&i| y[[i, out_idx]]).sum::<f64>()
566                        / samples.len() as f64;
567                    total += samples
568                        .iter()
569                        .map(|&i| (y[[i, out_idx]] - mean).powi(2))
570                        .sum::<f64>()
571                        / samples.len() as f64;
572                }
573                OutputType::Classification { .. } => {
574                    let mut counts: HashMap<i32, usize> = HashMap::new();
575                    for &i in samples {
576                        let cls = y[[i, out_idx]] as i32;
577                        *counts.entry(cls).or_insert(0) += 1;
578                    }
579                    let n = samples.len() as f64;
580                    let mut gini = 1.0_f64;
581                    for &c in counts.values() {
582                        let p = c as f64 / n;
583                        gini -= p * p;
584                    }
585                    total += gini;
586                }
587            }
588        }
589        total
590    }
591
592    /// Find the best split that maximises the summed impurity reduction over all outputs
593    fn find_best_split(
594        &self,
595        x: &Array2<f64>,
596        y: &Array2<f64>,
597        samples: &[usize],
598    ) -> Option<(usize, f64)> {
599        let n_features = x.ncols();
600        let mut best: Option<(usize, f64, f64)> = None; // (feature, threshold, reduction)
601        let parent_impurity = self.multi_output_impurity(samples, y);
602
603        for feat in 0..n_features {
604            let mut values: Vec<f64> = samples.iter().map(|&i| x[[i, feat]]).collect();
605            values.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
606            values.dedup();
607
608            for w in values.windows(2) {
609                let threshold = (w[0] + w[1]) / 2.0;
610
611                let (left, right): (Vec<usize>, Vec<usize>) =
612                    samples.iter().partition(|&&i| x[[i, feat]] <= threshold);
613
614                if left.is_empty() || right.is_empty() {
615                    continue;
616                }
617
618                let lw = left.len() as f64 / samples.len() as f64;
619                let rw = right.len() as f64 / samples.len() as f64;
620                let reduction = parent_impurity
621                    - lw * self.multi_output_impurity(&left, y)
622                    - rw * self.multi_output_impurity(&right, y);
623
624                if reduction > best.as_ref().map_or(f64::NEG_INFINITY, |b| b.2) {
625                    best = Some((feat, threshold, reduction));
626                }
627            }
628        }
629
630        best.filter(|b| b.2 > 1e-10)
631            .map(|(feat, threshold, _)| (feat, threshold))
632    }
633
634    /// Build the tree recursively
635    fn build_from_node(&mut self, node_id: usize, x: &Array2<f64>, y: &Array2<f64>) -> Result<()> {
636        let max_depth = self.config.max_depth.unwrap_or(10);
637        let min_split = self.config.min_samples_split;
638
639        let node_depth = self.nodes[node_id].depth;
640        let node_samples = self.nodes[node_id].samples.clone();
641
642        if node_samples.len() < min_split || node_depth >= max_depth {
643            return Ok(());
644        }
645
646        let split = self.find_best_split(x, y, &node_samples);
647        let (feat, threshold) = match split {
648            Some(s) => s,
649            None => return Ok(()),
650        };
651
652        let (left_samples, right_samples): (Vec<usize>, Vec<usize>) = node_samples
653            .iter()
654            .partition(|&&i| x[[i, feat]] <= threshold);
655
656        if left_samples.is_empty() || right_samples.is_empty() {
657            return Ok(());
658        }
659
660        let left_preds = self.compute_predictions(&left_samples, y);
661        let right_preds = self.compute_predictions(&right_samples, y);
662        let left_depth = self.nodes[node_id].depth + 1;
663        let right_depth = left_depth;
664
665        let left_id = self.nodes.len();
666        self.nodes.push(SharedMultiOutputTreeNode {
667            feature_idx: None,
668            threshold: None,
669            predictions: left_preds,
670            left_child: None,
671            right_child: None,
672            samples: left_samples,
673            depth: left_depth,
674            is_leaf: true,
675        });
676
677        let right_id = self.nodes.len();
678        self.nodes.push(SharedMultiOutputTreeNode {
679            feature_idx: None,
680            threshold: None,
681            predictions: right_preds,
682            left_child: None,
683            right_child: None,
684            samples: right_samples,
685            depth: right_depth,
686            is_leaf: true,
687        });
688
689        // Update parent
690        self.nodes[node_id].is_leaf = false;
691        self.nodes[node_id].feature_idx = Some(feat);
692        self.nodes[node_id].threshold = Some(threshold);
693        self.nodes[node_id].left_child = Some(left_id);
694        self.nodes[node_id].right_child = Some(right_id);
695
696        // Track feature importance
697        self.feature_importances[feat] += 1.0;
698
699        // Recurse
700        self.build_from_node(left_id, x, y)?;
701        self.build_from_node(right_id, x, y)?;
702
703        Ok(())
704    }
705
706    /// Predict for a single sample, returning a vector of predictions
707    fn predict_single(&self, x: &Array1<f64>) -> Result<Array1<f64>> {
708        if self.nodes.is_empty() {
709            return Err(SklearsError::PredictError("Tree not fitted".to_string()));
710        }
711        let mut idx = 0usize;
712        loop {
713            let node = &self.nodes[idx];
714            if node.is_leaf {
715                return Ok(node.predictions.clone());
716            }
717            match (node.feature_idx, node.threshold) {
718                (Some(feat), Some(thr)) => {
719                    if feat >= x.len() {
720                        return Err(SklearsError::PredictError(
721                            "Feature index out of bounds".to_string(),
722                        ));
723                    }
724                    if x[feat] <= thr {
725                        idx = node.left_child.ok_or_else(|| {
726                            SklearsError::PredictError("Missing left child".to_string())
727                        })?;
728                    } else {
729                        idx = node.right_child.ok_or_else(|| {
730                            SklearsError::PredictError("Missing right child".to_string())
731                        })?;
732                    }
733                }
734                _ => return Ok(node.predictions.clone()),
735            }
736        }
737    }
738}
739
740impl MultiOutputTreeModel for SharedMultiOutputTree {
741    fn fit_multi(&mut self, x: &Array2<f64>, y: &Array2<f64>) -> Result<()> {
742        if y.ncols() != self.n_outputs {
743            return Err(SklearsError::InvalidInput(format!(
744                "Expected {} outputs, got {}",
745                self.n_outputs,
746                y.ncols()
747            )));
748        }
749
750        let n_samples = x.nrows();
751        let samples: Vec<usize> = (0..n_samples).collect();
752        let root_preds = self.compute_predictions(&samples, y);
753
754        self.nodes.push(SharedMultiOutputTreeNode {
755            feature_idx: None,
756            threshold: None,
757            predictions: root_preds,
758            left_child: None,
759            right_child: None,
760            samples,
761            depth: 0,
762            is_leaf: true,
763        });
764
765        self.build_from_node(0, x, y)?;
766        Ok(())
767    }
768
769    fn predict_multi(&self, x: &Array2<f64>) -> Result<Array2<f64>> {
770        let n_samples = x.nrows();
771        let mut predictions = Array2::zeros((n_samples, self.n_outputs));
772        for (i, row) in x.rows().into_iter().enumerate() {
773            let preds = self.predict_single(&row.to_owned())?;
774            predictions.row_mut(i).assign(&preds);
775        }
776        Ok(predictions)
777    }
778
779    fn feature_importances_multi(&self) -> Result<Array2<f64>> {
780        let mut importances = Array2::zeros((self.n_features, self.n_outputs));
781        for out_idx in 0..self.n_outputs {
782            importances
783                .column_mut(out_idx)
784                .assign(&self.feature_importances);
785        }
786        Ok(importances)
787    }
788}
789
790// ─────────────────────────────────────────────────────────────────────────────
791// Chained multi-output tree
792// ─────────────────────────────────────────────────────────────────────────────
793
794/// Chained multi-output tree: each output is predicted by a tree trained on the
795/// original features augmented with the *training-time* predictions of all
796/// previous outputs.
797///
798/// During prediction the chain is applied sequentially:
799///   pred_0 = tree_0.predict(X)
800///   pred_1 = tree_1.predict([X | pred_0])
801///   ...
802#[derive(Debug)]
803pub struct ChainedMultiOutputTree {
804    /// One `SingleOutputTree` per output dimension
805    chains: Vec<SingleOutputTree>,
806    /// Number of outputs
807    n_outputs: usize,
808    /// Number of *original* features (not including chained predictions)
809    n_features: usize,
810}
811
812impl ChainedMultiOutputTree {
813    /// Create a new chained multi-output tree
814    pub fn new(
815        n_outputs: usize,
816        n_features: usize,
817        output_types: Vec<OutputType>,
818        _config: DecisionTreeConfig,
819    ) -> Self {
820        // Tree k is trained on n_features + k extra columns (outputs 0..k-1)
821        let chains = output_types
822            .iter()
823            .enumerate()
824            .map(|(k, ot)| SingleOutputTree::new(*ot, n_features + k))
825            .collect();
826
827        Self {
828            chains,
829            n_outputs,
830            n_features,
831        }
832    }
833
834    /// Build the augmented feature matrix [X | prev_preds] for output k
835    fn augmented_x(x: &Array2<f64>, train_preds: &Array2<f64>, k: usize) -> Array2<f64> {
836        let n_samples = x.nrows();
837        let n_orig = x.ncols();
838        let mut aug = Array2::zeros((n_samples, n_orig + k));
839        for i in 0..n_samples {
840            for j in 0..n_orig {
841                aug[[i, j]] = x[[i, j]];
842            }
843            for p in 0..k {
844                aug[[i, n_orig + p]] = train_preds[[i, p]];
845            }
846        }
847        aug
848    }
849}
850
851impl MultiOutputTreeModel for ChainedMultiOutputTree {
852    fn fit_multi(&mut self, x: &Array2<f64>, y: &Array2<f64>) -> Result<()> {
853        if y.ncols() != self.n_outputs {
854            return Err(SklearsError::InvalidInput(format!(
855                "Expected {} outputs, got {}",
856                self.n_outputs,
857                y.ncols()
858            )));
859        }
860
861        let n_samples = x.nrows();
862        // Accumulate training-time predictions as we go
863        let mut train_preds = Array2::<f64>::zeros((n_samples, self.n_outputs));
864
865        for k in 0..self.n_outputs {
866            // Build augmented feature matrix for output k
867            let aug = Self::augmented_x(x, &train_preds, k);
868            let y_k = y.column(k).to_owned();
869
870            self.chains[k].fit(&aug, &y_k)?;
871
872            // Record in-bag predictions for subsequent outputs
873            let preds_k = self.chains[k].predict(&aug)?;
874            train_preds.column_mut(k).assign(&preds_k);
875        }
876
877        Ok(())
878    }
879
880    fn predict_multi(&self, x: &Array2<f64>) -> Result<Array2<f64>> {
881        let n_samples = x.nrows();
882        let mut predictions = Array2::<f64>::zeros((n_samples, self.n_outputs));
883
884        for k in 0..self.n_outputs {
885            let aug = Self::augmented_x(x, &predictions, k);
886            let preds_k = self.chains[k].predict(&aug)?;
887            predictions.column_mut(k).assign(&preds_k);
888        }
889
890        Ok(predictions)
891    }
892
893    fn feature_importances_multi(&self) -> Result<Array2<f64>> {
894        let mut importances = Array2::zeros((self.n_features, self.n_outputs));
895        for (k, chain) in self.chains.iter().enumerate() {
896            // Only the first n_features importances correspond to original features
897            let src = chain
898                .feature_importances
899                .slice(scirs2_core::ndarray::s![..self.n_features]);
900            importances.column_mut(k).assign(&src);
901        }
902        Ok(importances)
903    }
904}
905
906impl IndependentMultiOutputTree {
907    /// Create a new independent multi-output tree.
908    ///
909    /// Each single-output tree is initialised with the shared `DecisionTreeConfig`
910    /// so that `max_depth`, `min_samples_split`, and other tree-growth parameters
911    /// are respected per output.
912    pub fn new(
913        n_outputs: usize,
914        n_features: usize,
915        output_types: Vec<OutputType>,
916        config: DecisionTreeConfig,
917    ) -> Self {
918        let trees = output_types
919            .into_iter()
920            .map(|output_type| {
921                SingleOutputTree::with_config(output_type, n_features, config.clone())
922            })
923            .collect();
924
925        Self {
926            trees,
927            n_outputs,
928            n_features,
929        }
930    }
931}
932
933impl MultiOutputTreeModel for IndependentMultiOutputTree {
934    fn fit_multi(&mut self, x: &Array2<f64>, y: &Array2<f64>) -> Result<()> {
935        if y.ncols() != self.n_outputs {
936            return Err(SklearsError::InvalidInput(format!(
937                "Expected {} outputs, got {}",
938                self.n_outputs,
939                y.ncols()
940            )));
941        }
942
943        // Fit each tree independently
944        for (output_idx, tree) in self.trees.iter_mut().enumerate() {
945            let y_single = y.column(output_idx);
946            tree.fit(x, &y_single.to_owned())?;
947        }
948
949        Ok(())
950    }
951
952    fn predict_multi(&self, x: &Array2<f64>) -> Result<Array2<f64>> {
953        let n_samples = x.nrows();
954        let mut predictions = Array2::zeros((n_samples, self.n_outputs));
955
956        for (output_idx, tree) in self.trees.iter().enumerate() {
957            let output_predictions = tree.predict(x)?;
958            predictions
959                .column_mut(output_idx)
960                .assign(&output_predictions);
961        }
962
963        Ok(predictions)
964    }
965
966    fn feature_importances_multi(&self) -> Result<Array2<f64>> {
967        let mut importances = Array2::zeros((self.n_features, self.n_outputs));
968
969        for (output_idx, tree) in self.trees.iter().enumerate() {
970            importances
971                .column_mut(output_idx)
972                .assign(&tree.feature_importances);
973        }
974
975        Ok(importances)
976    }
977}
978
979impl<State> MultiOutputDecisionTree<State> {
980    /// Create a new multi-output decision tree
981    pub fn new(config: MultiOutputTreeConfig) -> MultiOutputDecisionTree<Untrained> {
982        MultiOutputDecisionTree {
983            config,
984            trees: Vec::new(),
985            n_outputs: 0,
986            n_features: 0,
987            output_types: Vec::new(),
988            label_correlations: None,
989            state: PhantomData,
990        }
991    }
992}
993
994impl MultiOutputDecisionTree<Untrained> {
995    /// Fit the multi-output tree
996    pub fn fit(self, x: &Array2<f64>, y: &Array2<f64>) -> Result<MultiOutputDecisionTree<Trained>> {
997        let n_samples = x.nrows();
998        let n_features = x.ncols();
999        let n_outputs = y.ncols();
1000
1001        if n_samples != y.nrows() {
1002            return Err(SklearsError::InvalidInput(
1003                "X and y must have the same number of samples".to_string(),
1004            ));
1005        }
1006
1007        // Determine output types
1008        let mut output_types = Vec::new();
1009        for output_idx in 0..n_outputs {
1010            let output_col = y.column(output_idx);
1011            let is_integer = output_col.iter().all(|&val| val.fract() == 0.0);
1012
1013            if is_integer {
1014                let unique_classes: std::collections::HashSet<i32> =
1015                    output_col.iter().map(|&val| val as i32).collect();
1016                output_types.push(OutputType::Classification {
1017                    n_classes: unique_classes.len(),
1018                });
1019            } else {
1020                output_types.push(OutputType::Regression);
1021            }
1022        }
1023
1024        // Create appropriate multi-output model based on strategy
1025        let mut model: Box<dyn MultiOutputTreeModel> = match self.config.multi_output_strategy {
1026            MultiOutputStrategy::Independent => Box::new(IndependentMultiOutputTree::new(
1027                n_outputs,
1028                n_features,
1029                output_types.clone(),
1030                self.config.base_config.clone(),
1031            )),
1032            MultiOutputStrategy::Shared => Box::new(SharedMultiOutputTree::new(
1033                n_outputs,
1034                n_features,
1035                output_types.clone(),
1036                self.config.base_config.clone(),
1037            )),
1038            MultiOutputStrategy::Chained => Box::new(ChainedMultiOutputTree::new(
1039                n_outputs,
1040                n_features,
1041                output_types.clone(),
1042                self.config.base_config.clone(),
1043            )),
1044        };
1045
1046        // Compute label correlations if needed
1047        let label_correlations = if let LabelCorrelation::Cooccurrence { min_support } =
1048            &self.config.label_correlation
1049        {
1050            Some(compute_label_correlations(y, *min_support)?)
1051        } else {
1052            None
1053        };
1054
1055        // Fit the model
1056        model.fit_multi(x, y)?;
1057
1058        Ok(MultiOutputDecisionTree {
1059            config: self.config,
1060            trees: vec![model],
1061            n_outputs,
1062            n_features,
1063            output_types,
1064            label_correlations,
1065            state: PhantomData,
1066        })
1067    }
1068}
1069
1070impl MultiOutputDecisionTree<Trained> {
1071    /// Predict on new data
1072    pub fn predict(&self, x: &Array2<f64>) -> Result<Array2<f64>> {
1073        if x.ncols() != self.n_features {
1074            return Err(SklearsError::InvalidInput(format!(
1075                "Expected {} features, got {}",
1076                self.n_features,
1077                x.ncols()
1078            )));
1079        }
1080
1081        if let Some(model) = self.trees.first() {
1082            model.predict_multi(x)
1083        } else {
1084            Err(SklearsError::PredictError("Model not fitted".to_string()))
1085        }
1086    }
1087
1088    /// Get feature importances for each output
1089    pub fn feature_importances(&self) -> Result<Array2<f64>> {
1090        if let Some(model) = self.trees.first() {
1091            model.feature_importances_multi()
1092        } else {
1093            Err(SklearsError::InvalidInput("Model not fitted".to_string()))
1094        }
1095    }
1096
1097    /// Get label correlations (for multi-label problems)
1098    pub fn label_correlations(&self) -> Option<&LabelCorrelationMatrix> {
1099        self.label_correlations.as_ref()
1100    }
1101
1102    /// Return the number of outputs the model was fitted with (sklearn-compatible `n_outputs_`)
1103    pub fn n_outputs(&self) -> usize {
1104        self.n_outputs
1105    }
1106
1107    /// Return the per-output types (regression vs classification) as a slice
1108    pub fn output_types(&self) -> &[OutputType] {
1109        &self.output_types
1110    }
1111}
1112
1113/// Compute label correlations for multi-label data
1114fn compute_label_correlations(
1115    y: &Array2<f64>,
1116    _min_support: f64,
1117) -> Result<LabelCorrelationMatrix> {
1118    let n_samples = y.nrows();
1119    let n_labels = y.ncols();
1120
1121    // Compute co-occurrence matrix
1122    let mut cooccurrence = Array2::zeros((n_labels, n_labels));
1123    for i in 0..n_samples {
1124        for label1 in 0..n_labels {
1125            for label2 in 0..n_labels {
1126                if y[[i, label1]] > 0.0 && y[[i, label2]] > 0.0 {
1127                    cooccurrence[[label1, label2]] += 1;
1128                }
1129            }
1130        }
1131    }
1132
1133    // Compute correlation coefficients
1134    let mut correlations = Array2::zeros((n_labels, n_labels));
1135    for i in 0..n_labels {
1136        for j in 0..n_labels {
1137            if i == j {
1138                correlations[[i, j]] = 1.0;
1139            } else {
1140                let support_i = y.column(i).iter().filter(|&&val| val > 0.0).count() as f64;
1141                let support_j = y.column(j).iter().filter(|&&val| val > 0.0).count() as f64;
1142                let joint_support = cooccurrence[[i, j]] as f64;
1143
1144                if support_i > 0.0 && support_j > 0.0 {
1145                    // Jaccard similarity
1146                    let union_support = support_i + support_j - joint_support;
1147                    correlations[[i, j]] = joint_support / union_support;
1148                }
1149            }
1150        }
1151    }
1152
1153    Ok(LabelCorrelationMatrix {
1154        correlations,
1155        cooccurrence,
1156        hierarchy: None,
1157    })
1158}
1159
1160/// Multi-label Random Forest configuration
1161#[derive(Debug, Clone)]
1162pub struct MultiLabelRandomForestConfig {
1163    /// Base random forest configuration
1164    pub base_config: RandomForestConfig,
1165    /// Multi-output strategy
1166    pub multi_output_strategy: MultiOutputStrategy,
1167    /// Label correlation strategy
1168    pub label_correlation: LabelCorrelation,
1169    /// Threshold for binary predictions (for multi-label classification)
1170    pub prediction_threshold: f64,
1171    /// Enable label-specific feature selection
1172    pub label_specific_features: bool,
1173}
1174
1175impl Default for MultiLabelRandomForestConfig {
1176    fn default() -> Self {
1177        Self {
1178            base_config: RandomForestConfig::default(),
1179            multi_output_strategy: MultiOutputStrategy::Independent,
1180            label_correlation: LabelCorrelation::Independent,
1181            prediction_threshold: 0.5,
1182            label_specific_features: false,
1183        }
1184    }
1185}
1186
1187/// Multi-label Random Forest classifier
1188pub struct MultiLabelRandomForest<State = Untrained> {
1189    config: MultiLabelRandomForestConfig,
1190    trees: Vec<MultiOutputDecisionTree<Trained>>,
1191    n_outputs: usize,
1192    n_features: usize,
1193    label_correlations: Option<LabelCorrelationMatrix>,
1194    state: PhantomData<State>,
1195}
1196
1197impl MultiLabelRandomForest<Untrained> {
1198    /// Create a new multi-label random forest
1199    pub fn new(config: MultiLabelRandomForestConfig) -> Self {
1200        Self {
1201            config,
1202            trees: Vec::new(),
1203            n_outputs: 0,
1204            n_features: 0,
1205            label_correlations: None,
1206            state: PhantomData,
1207        }
1208    }
1209
1210    /// Fit the multi-label random forest
1211    pub fn fit(self, x: &Array2<f64>, y: &Array2<f64>) -> Result<MultiLabelRandomForest<Trained>> {
1212        let n_samples = x.nrows();
1213        let n_features = x.ncols();
1214        let n_outputs = y.ncols();
1215
1216        if n_samples != y.nrows() {
1217            return Err(SklearsError::InvalidInput(
1218                "X and y must have the same number of samples".to_string(),
1219            ));
1220        }
1221
1222        // Compute label correlations if needed
1223        let label_correlations = if let LabelCorrelation::Cooccurrence { min_support } =
1224            &self.config.label_correlation
1225        {
1226            Some(compute_label_correlations(y, *min_support)?)
1227        } else {
1228            None
1229        };
1230
1231        let mut trees = Vec::with_capacity(self.config.base_config.n_estimators);
1232
1233        // Build ensemble of multi-output trees
1234        for _ in 0..self.config.base_config.n_estimators {
1235            // Bootstrap sample
1236            let bootstrap_indices = self.bootstrap_sample(n_samples);
1237            let x_bootstrap = self.select_samples(x, &bootstrap_indices);
1238            let y_bootstrap = self.select_samples(y, &bootstrap_indices);
1239
1240            // Create and fit multi-output tree
1241            let tree_config = MultiOutputTreeConfig {
1242                base_config: self.config.base_config.clone().into(),
1243                multi_output_strategy: self.config.multi_output_strategy,
1244                label_correlation: self.config.label_correlation.clone(),
1245                ..Default::default()
1246            };
1247
1248            let tree = MultiOutputDecisionTree::<Untrained>::new(tree_config);
1249            let fitted_tree = tree.fit(&x_bootstrap, &y_bootstrap)?;
1250            trees.push(fitted_tree);
1251        }
1252
1253        Ok(MultiLabelRandomForest {
1254            config: self.config,
1255            trees,
1256            n_outputs,
1257            n_features,
1258            label_correlations,
1259            state: PhantomData,
1260        })
1261    }
1262
1263    /// Bootstrap sample indices
1264    fn bootstrap_sample(&self, n_samples: usize) -> Vec<usize> {
1265        let mut rng = scirs2_core::random::thread_rng();
1266        (0..n_samples)
1267            .map(|_| rng.gen_range(0..n_samples))
1268            .collect()
1269    }
1270
1271    /// Select samples by indices
1272    fn select_samples(&self, data: &Array2<f64>, indices: &[usize]) -> Array2<f64> {
1273        let n_features = data.ncols();
1274        let mut selected = Array2::zeros((indices.len(), n_features));
1275
1276        for (i, &idx) in indices.iter().enumerate() {
1277            selected.row_mut(i).assign(&data.row(idx));
1278        }
1279
1280        selected
1281    }
1282}
1283
1284// Helper conversion function
1285impl From<RandomForestConfig> for DecisionTreeConfig {
1286    fn from(rf_config: RandomForestConfig) -> Self {
1287        DecisionTreeConfig {
1288            max_depth: rf_config.max_depth,
1289            min_samples_split: rf_config.min_samples_split,
1290            min_samples_leaf: rf_config.min_samples_leaf,
1291            max_features: rf_config.max_features,
1292            criterion: rf_config.criterion,
1293            random_state: rf_config.random_state,
1294            ..Default::default()
1295        }
1296    }
1297}
1298
1299impl MultiLabelRandomForest<Trained> {
1300    /// Predict probabilities for each label
1301    pub fn predict_proba(&self, x: &Array2<f64>) -> Result<Array2<f64>> {
1302        if x.ncols() != self.n_features {
1303            return Err(SklearsError::InvalidInput(format!(
1304                "Expected {} features, got {}",
1305                self.n_features,
1306                x.ncols()
1307            )));
1308        }
1309
1310        let n_samples = x.nrows();
1311        let mut predictions = Array2::zeros((n_samples, self.n_outputs));
1312
1313        // Average predictions from all trees
1314        for tree in &self.trees {
1315            let tree_predictions = tree.predict(x)?;
1316            predictions = predictions + tree_predictions;
1317        }
1318
1319        // Normalize by number of trees
1320        predictions /= self.trees.len() as f64;
1321
1322        Ok(predictions)
1323    }
1324
1325    /// Predict binary labels using threshold
1326    pub fn predict(&self, x: &Array2<f64>) -> Result<Array2<f64>> {
1327        let probabilities = self.predict_proba(x)?;
1328        let threshold = self.config.prediction_threshold;
1329
1330        Ok(probabilities.mapv(|p| if p >= threshold { 1.0 } else { 0.0 }))
1331    }
1332
1333    /// Get feature importances averaged across all outputs and trees
1334    pub fn feature_importances(&self) -> Result<Array1<f64>> {
1335        let mut total_importances = Array1::zeros(self.n_features);
1336
1337        for tree in &self.trees {
1338            let tree_importances = tree.feature_importances()?;
1339            let mean_importance = tree_importances
1340                .mean_axis(Axis(1))
1341                .expect("array should have elements for mean computation");
1342            total_importances = total_importances + mean_importance;
1343        }
1344
1345        // Normalize by number of trees
1346        total_importances /= self.trees.len() as f64;
1347
1348        // Normalize to sum to 1
1349        let sum = total_importances.sum();
1350        if sum > 0.0 {
1351            total_importances /= sum;
1352        }
1353
1354        Ok(total_importances)
1355    }
1356
1357    /// Get label correlations
1358    pub fn label_correlations(&self) -> Option<&LabelCorrelationMatrix> {
1359        self.label_correlations.as_ref()
1360    }
1361}
1362
1363#[allow(non_snake_case)]
1364#[cfg(test)]
1365mod tests {
1366    use super::*;
1367    use scirs2_core::ndarray::array;
1368
1369    #[test]
1370    fn test_multi_output_tree_config() {
1371        let config = MultiOutputTreeConfig::default();
1372        assert!(matches!(
1373            config.multi_output_strategy,
1374            MultiOutputStrategy::Independent
1375        ));
1376        assert!(matches!(
1377            config.label_correlation,
1378            LabelCorrelation::Independent
1379        ));
1380        assert_eq!(config.min_samples_multioutput_split, 10);
1381        assert!(config.enable_feature_sharing);
1382    }
1383
1384    #[test]
1385    fn test_single_output_tree() {
1386        let mut tree = SingleOutputTree::new(OutputType::Regression, 2);
1387
1388        let x = array![[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]];
1389        let y = array![1.0, 2.0, 3.0];
1390
1391        assert!(tree.fit(&x, &y).is_ok());
1392
1393        let predictions = tree.predict(&x).expect("prediction should succeed");
1394        assert_eq!(predictions.len(), 3);
1395    }
1396
1397    #[test]
1398    fn test_multi_output_decision_tree() {
1399        let config = MultiOutputTreeConfig::default();
1400        let tree = MultiOutputDecisionTree::<Untrained>::new(config);
1401
1402        let x = array![[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]];
1403        let y = array![[1.0, 0.0], [2.0, 1.0], [3.0, 0.0]]; // Two outputs
1404
1405        let fitted_tree = tree.fit(&x, &y).expect("model fitting should succeed");
1406        let predictions = fitted_tree.predict(&x).expect("prediction should succeed");
1407
1408        assert_eq!(predictions.nrows(), 3);
1409        assert_eq!(predictions.ncols(), 2);
1410    }
1411
1412    #[test]
1413    fn test_label_correlations() {
1414        let y = array![
1415            [1.0, 1.0, 0.0],
1416            [1.0, 0.0, 1.0],
1417            [0.0, 1.0, 1.0],
1418            [1.0, 1.0, 1.0],
1419        ];
1420
1421        let correlations = compute_label_correlations(&y, 0.1).expect("operation should succeed");
1422        assert_eq!(correlations.correlations.nrows(), 3);
1423        assert_eq!(correlations.correlations.ncols(), 3);
1424        assert_eq!(correlations.cooccurrence.nrows(), 3);
1425        assert_eq!(correlations.cooccurrence.ncols(), 3);
1426    }
1427
1428    #[test]
1429    fn test_multi_label_random_forest() {
1430        let config = MultiLabelRandomForestConfig {
1431            base_config: RandomForestConfig {
1432                n_estimators: 3,
1433                ..Default::default()
1434            },
1435            ..Default::default()
1436        };
1437
1438        let forest = MultiLabelRandomForest::new(config);
1439
1440        let x = array![[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0],];
1441        let y = array![[1.0, 0.0], [0.0, 1.0], [1.0, 1.0], [0.0, 0.0],];
1442
1443        let fitted_forest = forest.fit(&x, &y).expect("model fitting should succeed");
1444        let predictions = fitted_forest
1445            .predict(&x)
1446            .expect("prediction should succeed");
1447
1448        assert_eq!(predictions.nrows(), 4);
1449        assert_eq!(predictions.ncols(), 2);
1450
1451        // All predictions should be 0 or 1
1452        for &pred in predictions.iter() {
1453            assert!(pred == 0.0 || pred == 1.0);
1454        }
1455    }
1456
1457    #[test]
1458    fn test_feature_importances() {
1459        let config = MultiOutputTreeConfig::default();
1460        let tree = MultiOutputDecisionTree::<Untrained>::new(config);
1461
1462        let x = array![[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]];
1463        let y = array![[1.0, 0.0], [2.0, 1.0], [3.0, 0.0], [4.0, 1.0]];
1464
1465        let fitted_tree = tree.fit(&x, &y).expect("model fitting should succeed");
1466        let importances = fitted_tree
1467            .feature_importances()
1468            .expect("operation should succeed");
1469
1470        assert_eq!(importances.nrows(), 2); // 2 features
1471        assert_eq!(importances.ncols(), 2); // 2 outputs
1472    }
1473
1474    // ── Shared multi-output tree ──────────────────────────────────────────────
1475
1476    #[test]
1477    fn test_shared_multi_output_tree_basic() {
1478        let x = array![
1479            [1.0, 0.0],
1480            [2.0, 0.5],
1481            [3.0, 1.0],
1482            [4.0, 1.5],
1483            [5.0, 2.0],
1484            [6.0, 2.5],
1485            [7.0, 3.0],
1486            [8.0, 3.5],
1487            [9.0, 4.0],
1488            [10.0, 4.5],
1489            [11.0, 5.0],
1490            [12.0, 5.5],
1491        ];
1492        // Two outputs that both correlate with x[:,0]
1493        let y = array![
1494            [1.0, 2.0],
1495            [1.0, 2.0],
1496            [1.0, 2.0],
1497            [1.0, 2.0],
1498            [2.0, 4.0],
1499            [2.0, 4.0],
1500            [2.0, 4.0],
1501            [2.0, 4.0],
1502            [3.0, 6.0],
1503            [3.0, 6.0],
1504            [3.0, 6.0],
1505            [3.0, 6.0],
1506        ];
1507
1508        let config = MultiOutputTreeConfig {
1509            multi_output_strategy: MultiOutputStrategy::Shared,
1510            ..Default::default()
1511        };
1512        let tree = MultiOutputDecisionTree::<Untrained>::new(config);
1513        let fitted = tree.fit(&x, &y).expect("shared tree fit should succeed");
1514        let preds = fitted
1515            .predict(&x)
1516            .expect("shared tree predict should succeed");
1517
1518        assert_eq!(preds.nrows(), 12);
1519        assert_eq!(preds.ncols(), 2);
1520        // Predictions should be non-trivial (not all zeros)
1521        let nonzero = preds.iter().any(|&v| v > 0.0);
1522        assert!(nonzero, "shared tree should produce non-zero predictions");
1523    }
1524
1525    #[test]
1526    fn test_shared_multi_output_tree_regression_accuracy() {
1527        // Larger dataset: two outputs that are perfect linear functions of x
1528        let n = 30usize;
1529        let mut x_data = Vec::with_capacity(n * 2);
1530        let mut y_data = Vec::with_capacity(n * 2);
1531        for i in 0..n {
1532            let xi = i as f64;
1533            x_data.push(xi);
1534            x_data.push(xi * 0.5);
1535            y_data.push(xi * 2.0);
1536            y_data.push(xi * 3.0);
1537        }
1538        let x = Array2::from_shape_vec((n, 2), x_data).expect("shape should be valid");
1539        let y = Array2::from_shape_vec((n, 2), y_data).expect("shape should be valid");
1540
1541        let config = MultiOutputTreeConfig {
1542            multi_output_strategy: MultiOutputStrategy::Shared,
1543            ..Default::default()
1544        };
1545        let tree = MultiOutputDecisionTree::<Untrained>::new(config);
1546        let fitted = tree.fit(&x, &y).expect("shared tree regression fit");
1547        let preds = fitted.predict(&x).expect("shared tree regression predict");
1548
1549        assert_eq!(preds.nrows(), n);
1550        assert_eq!(preds.ncols(), 2);
1551    }
1552
1553    #[test]
1554    fn test_shared_tree_feature_importances_shape() {
1555        let x = array![
1556            [1.0, 2.0],
1557            [3.0, 4.0],
1558            [5.0, 6.0],
1559            [7.0, 8.0],
1560            [9.0, 10.0],
1561            [11.0, 12.0],
1562            [13.0, 14.0],
1563            [15.0, 16.0],
1564            [17.0, 18.0],
1565            [19.0, 20.0],
1566            [21.0, 22.0],
1567            [23.0, 24.0]
1568        ];
1569        let y = array![
1570            [1.0, 0.0],
1571            [2.0, 1.0],
1572            [1.0, 0.0],
1573            [2.0, 1.0],
1574            [1.0, 0.0],
1575            [2.0, 1.0],
1576            [1.0, 0.0],
1577            [2.0, 1.0],
1578            [1.0, 0.0],
1579            [2.0, 1.0],
1580            [1.0, 0.0],
1581            [2.0, 1.0]
1582        ];
1583        let config = MultiOutputTreeConfig {
1584            multi_output_strategy: MultiOutputStrategy::Shared,
1585            ..Default::default()
1586        };
1587        let fitted = MultiOutputDecisionTree::<Untrained>::new(config)
1588            .fit(&x, &y)
1589            .expect("fit");
1590        let imp = fitted.feature_importances().expect("importances");
1591        assert_eq!(imp.nrows(), 2); // 2 features
1592        assert_eq!(imp.ncols(), 2); // 2 outputs
1593    }
1594
1595    // ── Chained multi-output tree ─────────────────────────────────────────────
1596
1597    #[test]
1598    fn test_chained_multi_output_tree_basic() {
1599        let x = array![
1600            [1.0, 0.0],
1601            [2.0, 0.5],
1602            [3.0, 1.0],
1603            [4.0, 1.5],
1604            [5.0, 2.0],
1605            [6.0, 2.5],
1606            [7.0, 3.0],
1607            [8.0, 3.5],
1608            [9.0, 4.0],
1609            [10.0, 4.5],
1610            [11.0, 5.0],
1611            [12.0, 5.5],
1612        ];
1613        let y = array![
1614            [1.0, 2.0],
1615            [1.0, 2.0],
1616            [1.0, 2.0],
1617            [1.0, 2.0],
1618            [2.0, 4.0],
1619            [2.0, 4.0],
1620            [2.0, 4.0],
1621            [2.0, 4.0],
1622            [3.0, 6.0],
1623            [3.0, 6.0],
1624            [3.0, 6.0],
1625            [3.0, 6.0],
1626        ];
1627
1628        let config = MultiOutputTreeConfig {
1629            multi_output_strategy: MultiOutputStrategy::Chained,
1630            ..Default::default()
1631        };
1632        let tree = MultiOutputDecisionTree::<Untrained>::new(config);
1633        let fitted = tree.fit(&x, &y).expect("chained tree fit should succeed");
1634        let preds = fitted
1635            .predict(&x)
1636            .expect("chained tree predict should succeed");
1637
1638        assert_eq!(preds.nrows(), 12);
1639        assert_eq!(preds.ncols(), 2);
1640    }
1641
1642    #[test]
1643    fn test_chained_tree_uses_previous_outputs() {
1644        // output_1 = output_0 * 2 — a perfect linear relationship.
1645        // The chained tree sees the real output_0 as a feature when training
1646        // output_1, so it should learn a tighter model than independent trees.
1647        let n = 20usize;
1648        let mut x_data = Vec::with_capacity(n);
1649        let mut y_data = Vec::with_capacity(n * 2);
1650        for i in 0..n {
1651            x_data.push(i as f64);
1652            y_data.push((i % 3) as f64); // output_0
1653            y_data.push(((i % 3) * 2) as f64); // output_1 = 2 * output_0
1654        }
1655        let x = Array2::from_shape_vec((n, 1), x_data).expect("shape");
1656        let y = Array2::from_shape_vec((n, 2), y_data).expect("shape");
1657
1658        let config = MultiOutputTreeConfig {
1659            multi_output_strategy: MultiOutputStrategy::Chained,
1660            ..Default::default()
1661        };
1662        let fitted = MultiOutputDecisionTree::<Untrained>::new(config)
1663            .fit(&x, &y)
1664            .expect("chained tree fit");
1665        let preds = fitted.predict(&x).expect("chained tree predict");
1666        assert_eq!(preds.nrows(), n);
1667        assert_eq!(preds.ncols(), 2);
1668        // Predictions for output_1 should be non-negative
1669        assert!(preds.column(1).iter().all(|&v| v >= 0.0));
1670    }
1671
1672    #[test]
1673    fn test_chained_tree_feature_importances_shape() {
1674        let x = array![
1675            [1.0, 2.0],
1676            [3.0, 4.0],
1677            [5.0, 6.0],
1678            [7.0, 8.0],
1679            [9.0, 10.0],
1680            [11.0, 12.0],
1681            [13.0, 14.0],
1682            [15.0, 16.0],
1683            [17.0, 18.0],
1684            [19.0, 20.0],
1685            [21.0, 22.0],
1686            [23.0, 24.0]
1687        ];
1688        let y = array![
1689            [1.0, 0.0],
1690            [2.0, 1.0],
1691            [1.0, 0.0],
1692            [2.0, 1.0],
1693            [1.0, 0.0],
1694            [2.0, 1.0],
1695            [1.0, 0.0],
1696            [2.0, 1.0],
1697            [1.0, 0.0],
1698            [2.0, 1.0],
1699            [1.0, 0.0],
1700            [2.0, 1.0]
1701        ];
1702        let config = MultiOutputTreeConfig {
1703            multi_output_strategy: MultiOutputStrategy::Chained,
1704            ..Default::default()
1705        };
1706        let fitted = MultiOutputDecisionTree::<Untrained>::new(config)
1707            .fit(&x, &y)
1708            .expect("fit");
1709        let imp = fitted.feature_importances().expect("importances");
1710        assert_eq!(imp.nrows(), 2); // 2 original features
1711        assert_eq!(imp.ncols(), 2); // 2 outputs
1712    }
1713
1714    #[test]
1715    fn test_independent_tree_config_forwarding() {
1716        // Verify that max_depth from DecisionTreeConfig is respected by each sub-tree
1717        // in IndependentMultiOutputTree.
1718        let custom_config = DecisionTreeConfig {
1719            max_depth: Some(2),
1720            min_samples_split: 3,
1721            ..Default::default()
1722        };
1723        let mut tree = IndependentMultiOutputTree::new(
1724            2,
1725            2,
1726            vec![OutputType::Regression, OutputType::Regression],
1727            custom_config.clone(),
1728        );
1729
1730        // Each sub-tree should carry the same config
1731        for sub in &tree.trees {
1732            assert_eq!(
1733                sub.config.max_depth,
1734                Some(2),
1735                "sub-tree should have max_depth=2 from forwarded config"
1736            );
1737            assert_eq!(
1738                sub.config.min_samples_split, 3,
1739                "sub-tree should have min_samples_split=3 from forwarded config"
1740            );
1741        }
1742
1743        // A dataset with 20 samples — the tree should be limited to depth 2.
1744        let x_data: Vec<f64> = (0..20)
1745            .flat_map(|i| vec![i as f64, (i % 5) as f64])
1746            .collect();
1747        let x = scirs2_core::ndarray::Array2::from_shape_vec((20, 2), x_data).expect("shape ok");
1748        let y_data: Vec<f64> = (0..40).map(|i| (i / 2) as f64).collect();
1749        let y = scirs2_core::ndarray::Array2::from_shape_vec((20, 2), y_data).expect("shape ok");
1750
1751        tree.fit_multi(&x, &y).expect("fit_multi should succeed");
1752        let preds = tree
1753            .predict_multi(&x)
1754            .expect("predict_multi should succeed");
1755        assert_eq!(preds.nrows(), 20);
1756        assert_eq!(preds.ncols(), 2);
1757    }
1758}