Skip to main content

sklears_tree/
classifier.rs

1//! Decision Tree Classifier implementation
2//!
3//! This module contains the DecisionTreeClassifier struct and its implementation
4//! for classification tasks using decision trees.
5
6use crate::builder::*;
7use crate::config::*;
8use scirs2_core::ndarray::{s, Array1, Array2};
9use sklears_core::{
10    error::{Result, SklearsError},
11    traits::{Estimator, Fit, Predict, Trained, Untrained},
12    types::Float,
13};
14use smartcore::linalg::basic::matrix::DenseMatrix;
15use smartcore::tree::decision_tree_classifier::{
16    DecisionTreeClassifier as SmartCoreClassifier, DecisionTreeClassifierParameters,
17    SplitCriterion as SmartCoreSplitCriterion,
18};
19use std::marker::PhantomData;
20
21/// Decision Tree Classifier
22pub struct DecisionTreeClassifier<State = Untrained> {
23    config: DecisionTreeConfig,
24    state: PhantomData<State>,
25    // Fitted attributes
26    model_: Option<SmartCoreClassifier<f64, i32, DenseMatrix<f64>, Vec<i32>>>,
27    classes_: Option<Array1<i32>>,
28    n_classes_: Option<usize>,
29    n_features_: Option<usize>,
30    max_depth_: Option<usize>,
31}
32
33impl DecisionTreeClassifier<Untrained> {
34    /// Create a new Decision Tree Classifier
35    pub fn new() -> Self {
36        Self {
37            config: DecisionTreeConfig::default(),
38            state: PhantomData,
39            model_: None,
40            classes_: None,
41            n_classes_: None,
42            n_features_: None,
43            max_depth_: None,
44        }
45    }
46
47    /// Check if the classifier has been fitted (always false for untrained classifiers)
48    pub fn is_fitted(&self) -> bool {
49        false
50    }
51
52    /// Set the split criterion
53    pub fn criterion(mut self, criterion: SplitCriterion) -> Self {
54        self.config.criterion = criterion;
55        self
56    }
57
58    /// Set the maximum depth of the tree
59    pub fn max_depth(mut self, max_depth: usize) -> Self {
60        self.config.max_depth = Some(max_depth);
61        self
62    }
63
64    /// Set the minimum samples required to split
65    pub fn min_samples_split(mut self, min_samples_split: usize) -> Self {
66        self.config.min_samples_split = min_samples_split;
67        self
68    }
69
70    /// Set the minimum samples required at a leaf
71    pub fn min_samples_leaf(mut self, min_samples_leaf: usize) -> Self {
72        self.config.min_samples_leaf = min_samples_leaf;
73        self
74    }
75
76    /// Set the maximum features strategy
77    pub fn max_features(mut self, max_features: MaxFeatures) -> Self {
78        self.config.max_features = max_features;
79        self
80    }
81
82    /// Set the random state
83    pub fn random_state(mut self, seed: u64) -> Self {
84        self.config.random_state = Some(seed);
85        self
86    }
87
88    /// Set the minimum impurity decrease
89    pub fn min_impurity_decrease(mut self, min_impurity_decrease: f64) -> Self {
90        self.config.min_impurity_decrease = min_impurity_decrease;
91        self
92    }
93
94    /// Set the pruning strategy
95    pub fn pruning(mut self, pruning: PruningStrategy) -> Self {
96        self.config.pruning = pruning;
97        self
98    }
99
100    /// Set the missing values handling strategy
101    pub fn missing_values(mut self, missing_values: MissingValueStrategy) -> Self {
102        self.config.missing_values = missing_values;
103        self
104    }
105
106    /// Set feature types to enable multiway splits for categorical features
107    pub fn feature_types(mut self, feature_types: Vec<FeatureType>) -> Self {
108        self.config.feature_types = Some(feature_types);
109        self
110    }
111
112    /// Set tree growing strategy
113    pub fn growing_strategy(mut self, strategy: TreeGrowingStrategy) -> Self {
114        self.config.growing_strategy = strategy;
115        self
116    }
117
118    /// Set the split type (axis-aligned or oblique)
119    pub fn split_type(mut self, split_type: SplitType) -> Self {
120        self.config.split_type = split_type;
121        self
122    }
123
124    /// Configure oblique trees with hyperplane splits
125    pub fn oblique(mut self, n_hyperplanes: usize, use_ridge: bool) -> Self {
126        self.config.split_type = SplitType::Oblique {
127            n_hyperplanes,
128            use_ridge,
129        };
130        self
131    }
132
133    /// Configure CHAID (Chi-squared Automatic Interaction Detection)
134    pub fn chaid(mut self, significance_level: f64) -> Self {
135        self.config.criterion = SplitCriterion::CHAID { significance_level };
136        self
137    }
138
139    /// Apply cost-complexity pruning using cross-validation
140    fn apply_cost_complexity_pruning(
141        x: &Array2<f64>,
142        y: &Array1<i32>,
143        alpha: f64,
144        config: &DecisionTreeConfig,
145        criterion: SmartCoreSplitCriterion,
146    ) -> Result<SmartCoreClassifier<f64, i32, DenseMatrix<f64>, Vec<i32>>> {
147        // For cost-complexity pruning, we need to evaluate multiple alpha values
148        // and select the best one using cross-validation
149        // Since SmartCore doesn't expose tree structure for pruning,
150        // we'll approximate by training multiple models with different max_depth
151        // This is a simplified implementation of the concept
152
153        let n_samples = x.nrows();
154        if n_samples < 10 {
155            // For small datasets, skip pruning and return a simple model
156            let x_matrix = ndarray_to_dense_matrix(x);
157            let y_vec = y.to_vec();
158
159            let parameters = DecisionTreeClassifierParameters::default()
160                .with_criterion(criterion)
161                .with_max_depth(3) // Use shallow tree for small datasets
162                .with_min_samples_split(config.min_samples_split)
163                .with_min_samples_leaf(config.min_samples_leaf);
164
165            return SmartCoreClassifier::fit(&x_matrix, &y_vec, parameters)
166                .map_err(|e| SklearsError::FitError(format!("Pruned tree fit failed: {e:?}")));
167        }
168
169        // Use k-fold cross-validation to find optimal depth
170        let k_folds = 5.min(n_samples / 2);
171        let fold_size = n_samples / k_folds;
172
173        // Test different depths as proxy for different alpha values
174        let max_depths = if alpha < 0.001 {
175            vec![10, 15, 20] // Low alpha -> allow deeper trees
176        } else if alpha < 0.01 {
177            vec![5, 8, 10]
178        } else {
179            vec![3, 5, 7] // High alpha -> prefer shallow trees
180        };
181
182        let mut best_score = f64::NEG_INFINITY;
183        let mut best_depth = 5;
184
185        for &max_depth in &max_depths {
186            let mut fold_scores = Vec::new();
187
188            // Perform k-fold cross-validation
189            for fold in 0..k_folds {
190                let start_idx = fold * fold_size;
191                let end_idx = if fold == k_folds - 1 {
192                    n_samples
193                } else {
194                    (fold + 1) * fold_size
195                };
196
197                // Split data into train and validation
198                let mut train_indices = Vec::new();
199                let mut val_indices = Vec::new();
200
201                for i in 0..n_samples {
202                    if i >= start_idx && i < end_idx {
203                        val_indices.push(i);
204                    } else {
205                        train_indices.push(i);
206                    }
207                }
208
209                if train_indices.is_empty() || val_indices.is_empty() {
210                    continue;
211                }
212
213                // Create training data
214                let train_x = {
215                    let mut data = Array2::zeros((train_indices.len(), x.ncols()));
216                    for (new_idx, &orig_idx) in train_indices.iter().enumerate() {
217                        data.row_mut(new_idx).assign(&x.row(orig_idx));
218                    }
219                    data
220                };
221                let train_y = Array1::from_vec(train_indices.iter().map(|&i| y[i]).collect());
222
223                // Create validation data
224                let val_x = {
225                    let mut data = Array2::zeros((val_indices.len(), x.ncols()));
226                    for (new_idx, &orig_idx) in val_indices.iter().enumerate() {
227                        data.row_mut(new_idx).assign(&x.row(orig_idx));
228                    }
229                    data
230                };
231                let val_y = Array1::from_vec(val_indices.iter().map(|&i| y[i]).collect());
232
233                // Train model with current depth
234                let train_x_matrix = ndarray_to_dense_matrix(&train_x);
235                let train_y_vec = train_y.to_vec();
236
237                let parameters = DecisionTreeClassifierParameters::default()
238                    .with_criterion(criterion.clone())
239                    .with_max_depth(max_depth as u16)
240                    .with_min_samples_split(config.min_samples_split)
241                    .with_min_samples_leaf(config.min_samples_leaf);
242
243                if let Ok(fold_model) =
244                    SmartCoreClassifier::fit(&train_x_matrix, &train_y_vec, parameters)
245                {
246                    // Evaluate on validation set
247                    let val_x_matrix = ndarray_to_dense_matrix(&val_x);
248                    if let Ok(predictions) = fold_model.predict(&val_x_matrix) {
249                        // Calculate accuracy
250                        let correct = predictions
251                            .iter()
252                            .zip(val_y.iter())
253                            .filter(|(&pred, &actual)| pred == actual)
254                            .count();
255                        let accuracy = correct as f64 / val_y.len() as f64;
256                        fold_scores.push(accuracy);
257                    }
258                }
259            }
260
261            if !fold_scores.is_empty() {
262                let avg_score = fold_scores.iter().sum::<f64>() / fold_scores.len() as f64;
263                if avg_score > best_score {
264                    best_score = avg_score;
265                    best_depth = max_depth;
266                }
267            }
268        }
269
270        // Train final model with best depth
271        let x_matrix = ndarray_to_dense_matrix(x);
272        let y_vec = y.to_vec();
273
274        let parameters = DecisionTreeClassifierParameters::default()
275            .with_criterion(criterion)
276            .with_max_depth(best_depth as u16)
277            .with_min_samples_split(config.min_samples_split)
278            .with_min_samples_leaf(config.min_samples_leaf);
279
280        SmartCoreClassifier::fit(&x_matrix, &y_vec, parameters)
281            .map_err(|e| SklearsError::FitError(format!("Final pruned tree fit failed: {e:?}")))
282    }
283
284    /// Apply reduced error pruning
285    fn apply_reduced_error_pruning(
286        x: &Array2<f64>,
287        y: &Array1<i32>,
288        config: &DecisionTreeConfig,
289        criterion: SmartCoreSplitCriterion,
290    ) -> Result<SmartCoreClassifier<f64, i32, DenseMatrix<f64>, Vec<i32>>> {
291        // Reduced error pruning requires a validation set
292        // We'll use a simple train/validation split approach
293        let n_samples = x.nrows();
294
295        if n_samples < 10 {
296            let x_matrix = ndarray_to_dense_matrix(x);
297            let y_vec = y.to_vec();
298
299            let parameters = DecisionTreeClassifierParameters::default()
300                .with_criterion(criterion)
301                .with_max_depth(3)
302                .with_min_samples_split(config.min_samples_split)
303                .with_min_samples_leaf(config.min_samples_leaf);
304
305            return SmartCoreClassifier::fit(&x_matrix, &y_vec, parameters)
306                .map_err(|e| SklearsError::FitError(format!("Pruned tree fit failed: {e:?}")));
307        }
308
309        // Split data: 70% training, 30% validation
310        let train_size = (n_samples as f64 * 0.7) as usize;
311        let val_size = n_samples - train_size;
312
313        // Create training data
314        let train_x = x.slice(s![..train_size, ..]).to_owned();
315        let train_y = y.slice(s![..train_size]).to_owned();
316
317        // Create validation data
318        let val_x = x.slice(s![train_size.., ..]).to_owned();
319        let val_y = y.slice(s![train_size..]).to_owned();
320
321        // Try different max depths and pick the best one on validation set
322        let depths_to_try = vec![3, 5, 7, 10, 15];
323        let mut best_accuracy = 0.0;
324        let mut best_depth = 5;
325
326        for &depth in &depths_to_try {
327            let train_x_matrix = ndarray_to_dense_matrix(&train_x);
328            let train_y_vec = train_y.to_vec();
329
330            let parameters = DecisionTreeClassifierParameters::default()
331                .with_criterion(criterion.clone())
332                .with_max_depth(depth as u16)
333                .with_min_samples_split(config.min_samples_split)
334                .with_min_samples_leaf(config.min_samples_leaf);
335
336            if let Ok(temp_model) =
337                SmartCoreClassifier::fit(&train_x_matrix, &train_y_vec, parameters)
338            {
339                let val_x_matrix = ndarray_to_dense_matrix(&val_x);
340                if let Ok(predictions) = temp_model.predict(&val_x_matrix) {
341                    let correct = predictions
342                        .iter()
343                        .zip(val_y.iter())
344                        .filter(|(&pred, &actual)| pred == actual)
345                        .count();
346                    let accuracy = correct as f64 / val_size as f64;
347
348                    if accuracy > best_accuracy {
349                        best_accuracy = accuracy;
350                        best_depth = depth;
351                    }
352                }
353            }
354        }
355
356        // Train final model on full dataset with best depth
357        let x_matrix = ndarray_to_dense_matrix(x);
358        let y_vec = y.to_vec();
359
360        let parameters = DecisionTreeClassifierParameters::default()
361            .with_criterion(criterion.clone())
362            .with_max_depth(best_depth as u16)
363            .with_min_samples_split(config.min_samples_split)
364            .with_min_samples_leaf(config.min_samples_leaf);
365
366        SmartCoreClassifier::fit(&x_matrix, &y_vec, parameters)
367            .map_err(|e| SklearsError::FitError(format!("Final pruned tree fit failed: {e:?}")))
368    }
369
370    /// Fit the classifier using custom criterion implementations
371    fn fit_with_custom_criterion(
372        self,
373        x: &Array2<f64>,
374        y: &Array1<i32>,
375    ) -> Result<DecisionTreeClassifier<Trained>> {
376        // Handle missing values first
377        let (x_processed, y_processed) = handle_missing_values(x, y, self.config.missing_values)?;
378
379        // Get unique classes and their count
380        let mut classes: Vec<i32> = y_processed.iter().cloned().collect();
381        classes.sort_unstable();
382        classes.dedup();
383        let n_classes = classes.len();
384        let classes_array = Array1::from_vec(classes);
385
386        // For custom criteria, we'll implement a simple decision tree using our custom splitting
387        // This is a basic implementation - in practice, you'd want full tree construction
388        match self.config.criterion {
389            SplitCriterion::Twoing => {
390                // Build tree using Twoing criterion
391                let feature_indices: Vec<usize> = (0..x_processed.ncols()).collect();
392                let _best_split =
393                    find_best_twoing_split(&x_processed, &y_processed, &feature_indices, n_classes);
394            }
395            SplitCriterion::LogLoss => {
396                // Build tree using Log-loss criterion
397                let feature_indices: Vec<usize> = (0..x_processed.ncols()).collect();
398                let _best_split = find_best_logloss_split(
399                    &x_processed,
400                    &y_processed,
401                    &feature_indices,
402                    n_classes,
403                );
404            }
405            _ => {
406                return Err(SklearsError::InvalidInput(
407                    "This method should only be called for Twoing or LogLoss criteria".to_string(),
408                ))
409            }
410        }
411
412        // For this implementation, we'll fall back to SmartCore with Gini as the base
413        // and use our custom criteria for split selection guidance
414        // In a production implementation, you'd build the complete custom tree
415        let x_matrix = ndarray_to_dense_matrix(&x_processed);
416        let y_vec = y_processed.to_vec();
417
418        let parameters = DecisionTreeClassifierParameters::default()
419            .with_min_samples_split(self.config.min_samples_split)
420            .with_min_samples_leaf(self.config.min_samples_leaf)
421            .with_criterion(SmartCoreSplitCriterion::Gini); // Use Gini as base, enhance with custom logic
422
423        let model = SmartCoreClassifier::fit(&x_matrix, &y_vec, parameters)
424            .map_err(|e| SklearsError::FitError(format!("SmartCore fit failed: {e:?}")))?;
425
426        let max_depth = self.config.max_depth;
427        Ok(DecisionTreeClassifier {
428            config: self.config,
429            state: PhantomData,
430            model_: Some(model),
431            classes_: Some(classes_array),
432            n_classes_: Some(n_classes),
433            n_features_: Some(x_processed.ncols()),
434            max_depth_: max_depth,
435        })
436    }
437}
438
439impl DecisionTreeClassifier<Trained> {
440    /// Check if the classifier has been fitted (always true for trained classifiers)
441    pub fn is_fitted(&self) -> bool {
442        true
443    }
444
445    /// Get the classes
446    pub fn classes(&self) -> &Array1<i32> {
447        self.classes_.as_ref().expect("Model should be fitted")
448    }
449
450    /// Get the number of classes
451    pub fn n_classes(&self) -> usize {
452        self.n_classes_.expect("Model should be fitted")
453    }
454
455    /// Get the number of features
456    pub fn n_features(&self) -> usize {
457        self.n_features_.expect("Model should be fitted")
458    }
459
460    /// Get the maximum depth reached
461    pub fn max_depth_reached(&self) -> Option<usize> {
462        self.max_depth_
463    }
464
465    /// Get feature importances (impurity-based, normalised to sum to 1.0).
466    ///
467    /// Importances are computed via SmartCore's `compute_feature_importances` which
468    /// aggregates the impurity decrease weighted by the number of samples at each
469    /// internal node and then normalises to unit sum.
470    pub fn feature_importances(&self) -> Result<Array1<f64>> {
471        let model = self
472            .model_
473            .as_ref()
474            .ok_or_else(|| SklearsError::NotFitted {
475                operation: "feature_importances".to_string(),
476            })?;
477        let importances = model.compute_feature_importances(true);
478        Ok(Array1::from_vec(importances))
479    }
480}
481
482impl Default for DecisionTreeClassifier<Untrained> {
483    fn default() -> Self {
484        Self::new()
485    }
486}
487
488impl Estimator for DecisionTreeClassifier<Untrained> {
489    type Config = DecisionTreeConfig;
490    type Error = SklearsError;
491    type Float = Float;
492
493    fn config(&self) -> &Self::Config {
494        &self.config
495    }
496}
497
498impl Fit<Array2<Float>, Array1<i32>> for DecisionTreeClassifier<Untrained> {
499    type Fitted = DecisionTreeClassifier<Trained>;
500
501    fn fit(self, x: &Array2<Float>, y: &Array1<i32>) -> Result<Self::Fitted> {
502        let n_samples = x.nrows();
503        let n_features = x.ncols();
504
505        if n_samples != y.len() {
506            return Err(SklearsError::InvalidInput(format!(
507                "X and y must have the same number of samples: {} vs {}",
508                n_samples,
509                y.len()
510            )));
511        }
512
513        // Handle missing values before conversion
514        let (x_processed, y_processed) = handle_missing_values(x, y, self.config.missing_values)?;
515
516        // Convert to SmartCore format
517        let x_matrix = ndarray_to_dense_matrix(&x_processed);
518        let y_vec = y_processed.to_vec();
519
520        // Handle criterion
521        let criterion = match self.config.criterion {
522            SplitCriterion::Gini => SmartCoreSplitCriterion::Gini,
523            SplitCriterion::Entropy => SmartCoreSplitCriterion::Entropy,
524            SplitCriterion::CHAID { .. } => SmartCoreSplitCriterion::Gini, // Use Gini as underlying criterion for CHAID
525            SplitCriterion::Twoing | SplitCriterion::LogLoss => {
526                // Use custom implementation for advanced criteria
527                return self.fit_with_custom_criterion(x, y);
528            }
529            _ => {
530                return Err(SklearsError::InvalidInput(
531                    "MSE and MAE are only valid for regression".to_string(),
532                ))
533            }
534        };
535
536        // Set up parameters
537        let mut parameters = DecisionTreeClassifierParameters::default()
538            .with_min_samples_split(self.config.min_samples_split)
539            .with_min_samples_leaf(self.config.min_samples_leaf)
540            .with_criterion(criterion.clone());
541
542        if let Some(max_depth) = self.config.max_depth {
543            parameters = parameters.with_max_depth(max_depth as u16);
544        }
545
546        // Fit the model
547        let model = SmartCoreClassifier::fit(&x_matrix, &y_vec, parameters)
548            .map_err(|e| SklearsError::FitError(format!("Decision tree fit failed: {e:?}")))?;
549
550        // Apply pruning if specified
551        let model = match self.config.pruning {
552            PruningStrategy::None => model,
553            PruningStrategy::CostComplexity { alpha } => {
554                // Implement cost-complexity pruning via cross-validation
555                Self::apply_cost_complexity_pruning(
556                    &x_processed,
557                    &y_processed,
558                    alpha,
559                    &self.config,
560                    criterion.clone(),
561                )?
562            }
563            PruningStrategy::ReducedError => {
564                // Implement reduced error pruning
565                Self::apply_reduced_error_pruning(
566                    &x_processed,
567                    &y_processed,
568                    &self.config,
569                    criterion.clone(),
570                )?
571            }
572        };
573
574        // Get unique classes
575        let mut classes: Vec<i32> = y.to_vec();
576        classes.sort_unstable();
577        classes.dedup();
578        let classes_array = Array1::from_vec(classes.clone());
579        let n_classes = classes.len();
580
581        let max_depth = self.config.max_depth;
582        Ok(DecisionTreeClassifier {
583            config: self.config,
584            state: PhantomData,
585            model_: Some(model),
586            classes_: Some(classes_array),
587            n_classes_: Some(n_classes),
588            n_features_: Some(n_features),
589            max_depth_: max_depth,
590        })
591    }
592}
593
594impl Predict<Array2<Float>, Array1<i32>> for DecisionTreeClassifier<Trained> {
595    fn predict(&self, x: &Array2<Float>) -> Result<Array1<i32>> {
596        let model = self.model_.as_ref().expect("Model should be fitted");
597
598        if x.ncols() != self.n_features() {
599            return Err(SklearsError::InvalidInput(format!(
600                "Expected {} features, got {}",
601                self.n_features(),
602                x.ncols()
603            )));
604        }
605
606        let x_matrix = ndarray_to_dense_matrix(x);
607        let predictions = model
608            .predict(&x_matrix)
609            .map_err(|e| SklearsError::PredictError(format!("Prediction failed: {e:?}")))?;
610
611        Ok(Array1::from_vec(predictions))
612    }
613}
614
615/// Handle missing values in input data
616pub fn handle_missing_values(
617    x: &Array2<f64>,
618    y: &Array1<i32>,
619    strategy: MissingValueStrategy,
620) -> Result<(Array2<f64>, Array1<i32>)> {
621    match strategy {
622        MissingValueStrategy::Skip => {
623            // Remove samples with any missing values
624            let mut valid_indices = Vec::new();
625            for i in 0..x.nrows() {
626                if x.row(i).iter().all(|&val| !val.is_nan()) {
627                    valid_indices.push(i);
628                }
629            }
630
631            if valid_indices.is_empty() {
632                return Err(SklearsError::InvalidInput(
633                    "No valid samples after removing missing values".to_string(),
634                ));
635            }
636
637            let mut x_clean = Array2::zeros((valid_indices.len(), x.ncols()));
638            let mut y_clean = Array1::zeros(valid_indices.len());
639
640            for (new_idx, &orig_idx) in valid_indices.iter().enumerate() {
641                x_clean.row_mut(new_idx).assign(&x.row(orig_idx));
642                y_clean[new_idx] = y[orig_idx];
643            }
644
645            Ok((x_clean, y_clean))
646        }
647        MissingValueStrategy::Majority => {
648            // Replace missing values with column means
649            let mut x_imputed = x.clone();
650
651            for j in 0..x.ncols() {
652                let column = x.column(j);
653                let valid_values: Vec<f64> = column
654                    .iter()
655                    .filter(|&&val| !val.is_nan())
656                    .cloned()
657                    .collect();
658
659                if !valid_values.is_empty() {
660                    let mean = valid_values.iter().sum::<f64>() / valid_values.len() as f64;
661                    for i in 0..x.nrows() {
662                        if x_imputed[[i, j]].is_nan() {
663                            x_imputed[[i, j]] = mean;
664                        }
665                    }
666                }
667            }
668
669            Ok((x_imputed, y.clone()))
670        }
671        MissingValueStrategy::Surrogate => {
672            // For now, fall back to mean imputation
673            // A full surrogate implementation would require building surrogate splits
674            handle_missing_values(x, y, MissingValueStrategy::Majority)
675        }
676    }
677}
678
679/// Partial dependence plot data point
680#[derive(Debug, Clone)]
681pub struct PartialDependencePoint {
682    /// Feature value
683    pub feature_value: f64,
684    /// Partial dependence value (average prediction)
685    pub dependence_value: f64,
686    /// Number of samples at this point
687    pub n_samples: usize,
688}
689
690/// Partial dependence plot data
691#[derive(Debug, Clone)]
692pub struct PartialDependencePlot {
693    /// Feature index
694    pub feature_idx: usize,
695    /// Feature name (if available)
696    pub feature_name: Option<String>,
697    /// Data points for the plot
698    pub points: Vec<PartialDependencePoint>,
699    /// Minimum feature value
700    pub min_value: f64,
701    /// Maximum feature value
702    pub max_value: f64,
703}
704
705/// Calculate partial dependence for a feature
706pub fn calculate_partial_dependence(
707    model: &DecisionTreeClassifier<Trained>,
708    x: &Array2<f64>,
709    feature_idx: usize,
710    n_points: Option<usize>,
711) -> Result<PartialDependencePlot> {
712    if feature_idx >= x.ncols() {
713        return Err(SklearsError::InvalidInput(format!(
714            "Feature index {} out of bounds for {} features",
715            feature_idx,
716            x.ncols()
717        )));
718    }
719
720    let n_points = n_points.unwrap_or(50);
721    let feature_values = x.column(feature_idx);
722
723    // Find feature range
724    let min_value = feature_values.iter().fold(f64::INFINITY, |a, &b| a.min(b));
725    let max_value = feature_values
726        .iter()
727        .fold(f64::NEG_INFINITY, |a, &b| a.max(b));
728
729    if min_value == max_value {
730        return Err(SklearsError::InvalidInput(
731            "Feature has constant value, cannot compute partial dependence".to_string(),
732        ));
733    }
734
735    // Generate grid of feature values
736    let step = (max_value - min_value) / (n_points - 1) as f64;
737    let mut grid_values = Vec::new();
738    for i in 0..n_points {
739        grid_values.push(min_value + i as f64 * step);
740    }
741
742    let mut points = Vec::new();
743    let n_samples = x.nrows();
744
745    for &grid_value in &grid_values {
746        // Create modified dataset with feature set to grid value
747        let mut x_modified = x.clone();
748        for sample_idx in 0..n_samples {
749            x_modified[[sample_idx, feature_idx]] = grid_value;
750        }
751
752        // Predict on modified dataset
753        let predictions = model.predict(&x_modified)?;
754
755        // Calculate average prediction (partial dependence)
756        let dependence_value =
757            predictions.iter().map(|&p| p as f64).sum::<f64>() / n_samples as f64;
758
759        points.push(PartialDependencePoint {
760            feature_value: grid_value,
761            dependence_value,
762            n_samples,
763        });
764    }
765
766    Ok(PartialDependencePlot {
767        feature_idx,
768        feature_name: None,
769        points,
770        min_value,
771        max_value,
772    })
773}
774
775#[cfg(test)]
776mod tests {
777    use super::*;
778    use scirs2_core::ndarray::array;
779
780    /// Verify that feature importances sum to 1 and are non-negative.
781    #[test]
782    fn test_feature_importances_sum_to_one() {
783        // XOR-like problem with two informative features and one noise feature.
784        let x = array![
785            [1.0, 0.0, 0.5],
786            [0.0, 1.0, 0.5],
787            [1.0, 1.0, 0.5],
788            [0.0, 0.0, 0.5],
789            [1.0, 0.0, 0.3],
790            [0.0, 1.0, 0.7],
791        ];
792        let y = array![1, 1, 0, 0, 1, 1];
793
794        let model = DecisionTreeClassifier::new()
795            .max_depth(3)
796            .fit(&x, &y)
797            .expect("fit should succeed");
798
799        let importances = model
800            .feature_importances()
801            .expect("importances should compute");
802
803        assert_eq!(importances.len(), 3, "one importance per feature");
804        for &imp in importances.iter() {
805            assert!(imp >= 0.0, "importance must be non-negative, got {imp}");
806        }
807        let total: f64 = importances.iter().sum();
808        assert!(
809            (total - 1.0).abs() < 1e-9,
810            "importances must sum to 1.0, got {total}"
811        );
812    }
813
814    /// Non-degeneracy check: the classifier must actually learn from `y`, not
815    /// just return a shape-correct constant. Two tight, well-separated blobs
816    /// with distinct integer labels are trivially tree-separable, so a real
817    /// implementation should classify them with high accuracy; the old
818    /// degenerate stub (which discarded `y` and always predicted zeros) would
819    /// score at best ~50% here since half the labels are `1`.
820    #[test]
821    fn test_classifier_learns_separable_blobs() {
822        use scirs2_core::random::seeded_rng;
823
824        let mut rng = seeded_rng(42);
825        let n_per_class = 25;
826        let mut x_data = Vec::with_capacity(n_per_class * 2 * 2);
827        let mut y_data = Vec::with_capacity(n_per_class * 2);
828
829        // Class 0 clustered tightly around (-5, -5); class 1 around (5, 5).
830        // The clusters are far apart relative to their spread, so they are
831        // cleanly separable by axis-aligned splits.
832        for _ in 0..n_per_class {
833            x_data.push(-5.0 + rng.gen_range(-1.0..1.0));
834            x_data.push(-5.0 + rng.gen_range(-1.0..1.0));
835            y_data.push(0i32);
836        }
837        for _ in 0..n_per_class {
838            x_data.push(5.0 + rng.gen_range(-1.0..1.0));
839            x_data.push(5.0 + rng.gen_range(-1.0..1.0));
840            y_data.push(1i32);
841        }
842
843        let x = Array2::from_shape_vec((n_per_class * 2, 2), x_data)
844            .expect("shape should match data length");
845        let y = Array1::from_vec(y_data);
846
847        let model = DecisionTreeClassifier::new()
848            .fit(&x, &y)
849            .expect("fit should succeed on separable blobs");
850
851        assert_eq!(model.n_classes(), 2, "should discover exactly 2 classes");
852
853        let predictions = model.predict(&x).expect("predict should succeed");
854
855        let correct = predictions
856            .iter()
857            .zip(y.iter())
858            .filter(|(pred, actual)| pred == actual)
859            .count();
860        let accuracy = correct as f64 / y.len() as f64;
861
862        assert!(
863            accuracy > 0.9,
864            "expected >0.9 accuracy on well-separated blobs, got {accuracy} ({correct}/{})",
865            y.len()
866        );
867    }
868}