1use 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#[derive(Debug, Clone, Copy)]
20pub enum MultiOutputStrategy {
21 Independent,
23 Shared,
25 Chained,
27}
28
29#[derive(Debug, Clone)]
31pub enum LabelCorrelation {
32 Independent,
34 Cooccurrence { min_support: f64 },
36 Hierarchical { hierarchy: Vec<(usize, usize)> }, Embedded { n_components: usize },
40}
41
42#[derive(Debug, Clone)]
44pub struct MultiOutputTreeConfig {
45 pub base_config: DecisionTreeConfig,
47 pub multi_output_strategy: MultiOutputStrategy,
49 pub label_correlation: LabelCorrelation,
51 pub min_samples_multioutput_split: usize,
53 pub enable_feature_sharing: bool,
55 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
72pub 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#[derive(Debug, Clone, Copy)]
85pub enum OutputType {
86 Regression,
87 Classification { n_classes: usize },
88}
89
90#[derive(Debug, Clone)]
92pub struct LabelCorrelationMatrix {
93 correlations: Array2<f64>,
95 cooccurrence: Array2<usize>,
97 hierarchy: Option<Vec<(usize, usize)>>,
99}
100
101impl LabelCorrelationMatrix {
102 pub fn correlations(&self) -> &Array2<f64> {
104 &self.correlations
105 }
106
107 pub fn cooccurrence(&self) -> &Array2<usize> {
109 &self.cooccurrence
110 }
111
112 pub fn hierarchy(&self) -> Option<&Vec<(usize, usize)>> {
114 self.hierarchy.as_ref()
115 }
116}
117
118pub trait MultiOutputTreeModel: Send + Sync {
120 fn fit_multi(&mut self, x: &Array2<f64>, y: &Array2<f64>) -> Result<()>;
122
123 fn predict_multi(&self, x: &Array2<f64>) -> Result<Array2<f64>>;
125
126 fn feature_importances_multi(&self) -> Result<Array2<f64>>;
128}
129
130#[derive(Debug)]
132pub struct IndependentMultiOutputTree {
133 trees: Vec<SingleOutputTree>,
135 n_outputs: usize,
137 n_features: usize,
139}
140
141#[derive(Debug)]
143pub struct SingleOutputTree {
144 nodes: Vec<MultiOutputTreeNode>,
146 output_type: OutputType,
148 feature_importances: Array1<f64>,
150 config: DecisionTreeConfig,
152}
153
154#[derive(Debug, Clone)]
156pub struct MultiOutputTreeNode {
157 feature_idx: Option<usize>,
159 threshold: Option<f64>,
161 predictions: Array1<f64>,
163 left_child: Option<usize>,
165 right_child: Option<usize>,
167 samples: Vec<usize>,
169 depth: usize,
171 is_leaf: bool,
173}
174
175impl SingleOutputTree {
176 pub fn new(output_type: OutputType, n_features: usize) -> Self {
178 Self::with_config(output_type, n_features, DecisionTreeConfig::default())
179 }
180
181 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 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 let root = self.create_node(0, samples, x, y, 0)?;
202 self.nodes = vec![root];
203
204 self.build_tree(0, x, y)?;
206
207 Ok(())
208 }
209
210 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; let mut predictions = Array1::zeros(n_outputs);
221
222 if !samples.is_empty() {
223 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 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 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 if let Some((feature_idx, threshold)) = self.find_best_split(x, y, &node.samples)? {
270 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 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 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 self.nodes.push(left_node);
291 self.nodes.push(right_node);
292
293 self.feature_importances[feature_idx] += 1.0;
295
296 self.build_tree(left_id, x, y)?;
298 self.build_tree(right_id, x, y)?;
299 }
300 }
301
302 Ok(())
303 }
304
305 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; for feature_idx in 0..n_features {
316 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 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 Ok(Some((feature_idx, threshold)))
339 } else {
340 Ok(None)
341 }
342 } else {
343 Ok(None)
344 }
345 }
346
347 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 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 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 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 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 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 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#[derive(Debug)]
482pub struct SharedMultiOutputTree {
483 nodes: Vec<SharedMultiOutputTreeNode>,
485 n_outputs: usize,
487 n_features: usize,
489 output_types: Vec<OutputType>,
491 feature_importances: Array1<f64>,
493 config: DecisionTreeConfig,
495}
496
497#[derive(Debug, Clone)]
499struct SharedMultiOutputTreeNode {
500 feature_idx: Option<usize>,
501 threshold: Option<f64>,
502 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 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 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 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 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; 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 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 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 self.feature_importances[feat] += 1.0;
698
699 self.build_from_node(left_id, x, y)?;
701 self.build_from_node(right_id, x, y)?;
702
703 Ok(())
704 }
705
706 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#[derive(Debug)]
803pub struct ChainedMultiOutputTree {
804 chains: Vec<SingleOutputTree>,
806 n_outputs: usize,
808 n_features: usize,
810}
811
812impl ChainedMultiOutputTree {
813 pub fn new(
815 n_outputs: usize,
816 n_features: usize,
817 output_types: Vec<OutputType>,
818 _config: DecisionTreeConfig,
819 ) -> Self {
820 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 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 let mut train_preds = Array2::<f64>::zeros((n_samples, self.n_outputs));
864
865 for k in 0..self.n_outputs {
866 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn label_correlations(&self) -> Option<&LabelCorrelationMatrix> {
1099 self.label_correlations.as_ref()
1100 }
1101
1102 pub fn n_outputs(&self) -> usize {
1104 self.n_outputs
1105 }
1106
1107 pub fn output_types(&self) -> &[OutputType] {
1109 &self.output_types
1110 }
1111}
1112
1113fn 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 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 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 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#[derive(Debug, Clone)]
1162pub struct MultiLabelRandomForestConfig {
1163 pub base_config: RandomForestConfig,
1165 pub multi_output_strategy: MultiOutputStrategy,
1167 pub label_correlation: LabelCorrelation,
1169 pub prediction_threshold: f64,
1171 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
1187pub 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 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 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 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 for _ in 0..self.config.base_config.n_estimators {
1235 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 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 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 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
1284impl 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 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 for tree in &self.trees {
1315 let tree_predictions = tree.predict(x)?;
1316 predictions = predictions + tree_predictions;
1317 }
1318
1319 predictions /= self.trees.len() as f64;
1321
1322 Ok(predictions)
1323 }
1324
1325 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 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 total_importances /= self.trees.len() as f64;
1347
1348 let sum = total_importances.sum();
1350 if sum > 0.0 {
1351 total_importances /= sum;
1352 }
1353
1354 Ok(total_importances)
1355 }
1356
1357 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]]; 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 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); assert_eq!(importances.ncols(), 2); }
1473
1474 #[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 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 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 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); assert_eq!(imp.ncols(), 2); }
1594
1595 #[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 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); y_data.push(((i % 3) * 2) as f64); }
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 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); assert_eq!(imp.ncols(), 2); }
1713
1714 #[test]
1715 fn test_independent_tree_config_forwarding() {
1716 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 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 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}