Skip to main content

sklears_tree/
config.rs

1//! Configuration types and enums for decision trees
2//!
3//! This module contains all the configuration enums, structs, and parameters
4//! used by decision tree classifiers and regressors.
5
6use scirs2_core::ndarray::{Array1, Array2};
7use sklears_core::types::Float;
8use smartcore::linalg::basic::matrix::DenseMatrix;
9
10#[cfg(feature = "oblique")]
11use sklears_core::error::Result;
12
13// Re-export SplitCriterion so downstream modules (classifier, regressor) can
14// import it via `crate::config` in addition to `crate::criteria`.
15pub use crate::criteria::SplitCriterion;
16
17/// Monotonic constraint for a feature
18#[derive(Debug, Clone, Copy, PartialEq)]
19pub enum MonotonicConstraint {
20    /// No constraint on the relationship
21    None,
22    /// Feature must have increasing relationship with target (positive monotonicity)
23    Increasing,
24    /// Feature must have decreasing relationship with target (negative monotonicity)
25    Decreasing,
26}
27
28/// Interaction constraint between features
29#[derive(Debug, Clone)]
30pub enum InteractionConstraint {
31    /// No constraints on feature interactions
32    None,
33    /// Allow interactions only within specified groups
34    Groups(Vec<Vec<usize>>),
35    /// Forbid specific feature pairs from interacting
36    Forbidden(Vec<(usize, usize)>),
37    /// Allow only specific feature pairs to interact
38    Allowed(Vec<(usize, usize)>),
39}
40
41/// Feature grouping strategy for handling correlated features
42#[derive(Debug, Clone)]
43pub enum FeatureGrouping {
44    /// No feature grouping (default)
45    None,
46    /// Automatic grouping based on correlation threshold
47    AutoCorrelation {
48        /// Correlation threshold above which features are grouped together
49        threshold: Float,
50        /// Method to select representative feature from each group
51        selection_method: GroupSelectionMethod,
52    },
53    /// Manual feature groups specified by user
54    Manual {
55        /// List of feature groups, each group contains feature indices
56        groups: Vec<Vec<usize>>,
57        /// Method to select representative feature from each group
58        selection_method: GroupSelectionMethod,
59    },
60    /// Hierarchical clustering-based grouping
61    Hierarchical {
62        /// Number of clusters to create
63        n_clusters: usize,
64        /// Linkage method for hierarchical clustering
65        linkage: LinkageMethod,
66        /// Method to select representative feature from each group
67        selection_method: GroupSelectionMethod,
68    },
69}
70
71/// Method for selecting representative feature from a group
72#[derive(Debug, Clone, Copy, PartialEq)]
73pub enum GroupSelectionMethod {
74    /// Select feature with highest variance within the group
75    MaxVariance,
76    /// Select feature with highest correlation to target
77    MaxTargetCorrelation,
78    /// Select first feature in the group (index order)
79    First,
80    /// Select random feature from the group
81    Random,
82    /// Use all features from the group but with reduced weight
83    WeightedAll,
84}
85
86/// Linkage method for hierarchical clustering
87#[derive(Debug, Clone, Copy, PartialEq)]
88pub enum LinkageMethod {
89    /// Single linkage (minimum distance)
90    Single,
91    /// Complete linkage (maximum distance)
92    Complete,
93    /// Average linkage
94    Average,
95    /// Ward linkage (minimize within-cluster variance)
96    Ward,
97}
98
99/// Information about feature groups discovered or specified
100#[derive(Debug, Clone)]
101pub struct FeatureGroupInfo {
102    /// Groups of correlated features
103    pub groups: Vec<Vec<usize>>,
104    /// Representative feature index for each group
105    pub representatives: Vec<usize>,
106    /// Correlation matrix used for grouping (if applicable)
107    pub correlation_matrix: Option<Array2<Float>>,
108    /// Within-group correlations for each group
109    pub group_correlations: Vec<Float>,
110}
111
112/// Strategy for selecting max features
113#[derive(Debug, Clone)]
114pub enum MaxFeatures {
115    /// Use all features
116    All,
117    /// Use sqrt(n_features)
118    Sqrt,
119    /// Use log2(n_features)
120    Log2,
121    /// Use a specific number of features
122    Number(usize),
123    /// Use a fraction of features
124    Fraction(f64),
125}
126
127/// Pruning strategy for decision trees
128#[derive(Debug, Clone, Copy)]
129pub enum PruningStrategy {
130    /// No pruning
131    None,
132    /// Cost-complexity pruning (post-pruning)
133    CostComplexity { alpha: f64 },
134    /// Reduced error pruning
135    ReducedError,
136}
137
138/// Missing value handling strategy
139#[derive(Debug, Clone, Copy)]
140pub enum MissingValueStrategy {
141    /// Skip samples with missing values
142    Skip,
143    /// Use majority class/mean for splits
144    Majority,
145    /// Use surrogate splits
146    Surrogate,
147}
148
149/// Feature type specification for multiway splits
150#[derive(Debug, Clone)]
151pub enum FeatureType {
152    /// Continuous numerical feature (binary splits)
153    Continuous,
154    /// Categorical feature with specified categories (multiway splits)
155    Categorical(Vec<String>),
156}
157
158/// Information about a multiway split
159#[derive(Debug, Clone)]
160pub struct MultiwaySplit {
161    /// Feature index
162    pub feature_idx: usize,
163    /// Category assignments for each branch
164    pub category_branches: Vec<Vec<String>>,
165    /// Impurity decrease achieved by this split
166    pub impurity_decrease: f64,
167}
168
169/// Tree growing strategy
170#[derive(Debug, Clone, Copy)]
171pub enum TreeGrowingStrategy {
172    /// Depth-first growing (traditional CART)
173    DepthFirst,
174    /// Best-first growing (expand node with highest impurity decrease)
175    BestFirst { max_leaves: Option<usize> },
176}
177
178/// Split type for decision trees
179#[derive(Debug, Clone, Copy)]
180pub enum SplitType {
181    /// Traditional axis-aligned splits (threshold on single feature)
182    AxisAligned,
183    /// Linear hyperplane splits (linear combination of features)
184    Oblique {
185        /// Number of random hyperplanes to evaluate per split
186        n_hyperplanes: usize,
187        /// Use ridge regression to find optimal hyperplane
188        use_ridge: bool,
189    },
190}
191
192/// Hyperplane split information for oblique trees
193#[derive(Debug, Clone)]
194pub struct HyperplaneSplit {
195    /// Feature coefficients for the hyperplane (w^T x >= threshold)
196    pub coefficients: Array1<f64>,
197    /// Threshold for the hyperplane split
198    pub threshold: f64,
199    /// Bias term for the hyperplane
200    pub bias: f64,
201    /// Impurity decrease achieved by this split
202    pub impurity_decrease: f64,
203}
204
205impl HyperplaneSplit {
206    /// Evaluate the hyperplane split for a sample
207    pub fn evaluate(&self, sample: &Array1<f64>) -> bool {
208        let dot_product = self.coefficients.dot(sample) + self.bias;
209        dot_product >= self.threshold
210    }
211
212    /// Create a random hyperplane with normalized coefficients
213    pub fn random(n_features: usize, rng: &mut scirs2_core::CoreRandom) -> Self {
214        let mut coefficients = Array1::zeros(n_features);
215        for i in 0..n_features {
216            coefficients[i] = rng.gen_range(-1.0..1.0);
217        }
218
219        // Normalize coefficients
220        let dot_product: f64 = coefficients.dot(&coefficients);
221        let norm = dot_product.sqrt();
222        if norm > 1e-10_f64 {
223            coefficients /= norm;
224        }
225
226        Self {
227            coefficients,
228            threshold: rng.gen_range(-1.0..1.0),
229            bias: rng.gen_range(-0.1..0.1),
230            impurity_decrease: 0.0,
231        }
232    }
233
234    /// Find optimal hyperplane using ridge regression
235    #[cfg(feature = "oblique")]
236    pub fn from_ridge_regression(x: &Array2<f64>, y: &Array1<f64>, alpha: f64) -> Result<Self> {
237        use scirs2_core::ndarray::s;
238        use sklears_core::error::SklearsError;
239
240        let n_features = x.ncols();
241        if x.nrows() < 2 {
242            return Err(SklearsError::InvalidInput(
243                "Need at least 2 samples for ridge regression".to_string(),
244            ));
245        }
246
247        // Add bias column to X
248        let mut x_bias = Array2::ones((x.nrows(), n_features + 1));
249        x_bias.slice_mut(s![.., ..n_features]).assign(x);
250
251        // Ridge regression: w = (X^T X + α I)^(-1) X^T y
252        let xtx = x_bias.t().dot(&x_bias);
253        let ridge_matrix = xtx + Array2::<f64>::eye(n_features + 1) * alpha;
254        let xty = x_bias.t().dot(y);
255
256        // Simple matrix inverse using Gauss-Jordan elimination
257        match gauss_jordan_inverse(&ridge_matrix) {
258            Ok(inv_matrix) => {
259                let coefficients_full = inv_matrix.dot(&xty);
260
261                let coefficients = coefficients_full.slice(s![..n_features]).to_owned();
262                let bias = coefficients_full[n_features];
263
264                Ok(Self {
265                    coefficients,
266                    threshold: 0.0, // Will be set during split evaluation
267                    bias,
268                    impurity_decrease: 0.0,
269                })
270            }
271            Err(_) => {
272                // Fallback to random hyperplane if matrix is singular
273                let mut rng = scirs2_core::random::thread_rng();
274                Ok(Self::random(n_features, &mut rng))
275            }
276        }
277    }
278}
279
280/// Configuration for Decision Trees
281#[derive(Debug, Clone)]
282pub struct DecisionTreeConfig {
283    /// Split criterion
284    pub criterion: SplitCriterion,
285    /// Maximum depth of the tree
286    pub max_depth: Option<usize>,
287    /// Minimum samples required to split an internal node
288    pub min_samples_split: usize,
289    /// Minimum samples required to be at a leaf node
290    pub min_samples_leaf: usize,
291    /// Maximum number of features to consider for splits
292    pub max_features: MaxFeatures,
293    /// Random seed for reproducibility
294    pub random_state: Option<u64>,
295    /// Minimum weighted fraction of samples required to be at a leaf
296    pub min_weight_fraction_leaf: f64,
297    /// Minimum impurity decrease required for a split
298    pub min_impurity_decrease: f64,
299    /// Pruning strategy to apply
300    pub pruning: PruningStrategy,
301    /// Strategy for handling missing values
302    pub missing_values: MissingValueStrategy,
303    /// Feature types for each feature (enables multiway splits for categorical features)
304    pub feature_types: Option<Vec<FeatureType>>,
305    /// Tree growing strategy
306    pub growing_strategy: TreeGrowingStrategy,
307    /// Split type (axis-aligned or oblique)
308    pub split_type: SplitType,
309    /// Monotonic constraints for each feature
310    pub monotonic_constraints: Option<Vec<MonotonicConstraint>>,
311    /// Interaction constraints between features
312    pub interaction_constraints: InteractionConstraint,
313    /// Feature grouping strategy for handling correlated features
314    pub feature_grouping: FeatureGrouping,
315}
316
317impl Default for DecisionTreeConfig {
318    fn default() -> Self {
319        Self {
320            criterion: SplitCriterion::Gini,
321            max_depth: None,
322            min_samples_split: 2,
323            min_samples_leaf: 1,
324            max_features: MaxFeatures::All,
325            random_state: None,
326            min_weight_fraction_leaf: 0.0,
327            min_impurity_decrease: 0.0,
328            pruning: PruningStrategy::None,
329            missing_values: MissingValueStrategy::Skip,
330            feature_types: None,
331            growing_strategy: TreeGrowingStrategy::DepthFirst,
332            split_type: SplitType::AxisAligned,
333            monotonic_constraints: None,
334            interaction_constraints: InteractionConstraint::None,
335            feature_grouping: FeatureGrouping::None,
336        }
337    }
338}
339
340/// Helper function to convert ndarray to DenseMatrix
341pub fn ndarray_to_dense_matrix(arr: &Array2<f64>) -> DenseMatrix<f64> {
342    let _rows = arr.nrows();
343    let _cols = arr.ncols();
344    let mut data = Vec::new();
345    for row in arr.outer_iter() {
346        data.push(row.to_vec());
347    }
348    DenseMatrix::from_2d_vec(&data).expect("Failed to convert ndarray to DenseMatrix")
349}
350
351/// Simple Gauss-Jordan elimination for matrix inversion
352#[cfg(feature = "oblique")]
353fn gauss_jordan_inverse(matrix: &Array2<f64>) -> std::result::Result<Array2<f64>, &'static str> {
354    let n = matrix.nrows();
355    if n != matrix.ncols() {
356        return Err("Matrix must be square");
357    }
358
359    // Create augmented matrix [A | I]
360    let mut augmented = Array2::zeros((n, 2 * n));
361    for i in 0..n {
362        for j in 0..n {
363            augmented[[i, j]] = matrix[[i, j]];
364            if i == j {
365                augmented[[i, j + n]] = 1.0;
366            }
367        }
368    }
369
370    // Forward elimination
371    for i in 0..n {
372        // Find pivot
373        let mut max_row = i;
374        for k in i + 1..n {
375            if augmented[[k, i]].abs() > augmented[[max_row, i]].abs() {
376                max_row = k;
377            }
378        }
379
380        // Swap rows if needed
381        if max_row != i {
382            for j in 0..2 * n {
383                let temp = augmented[[i, j]];
384                augmented[[i, j]] = augmented[[max_row, j]];
385                augmented[[max_row, j]] = temp;
386            }
387        }
388
389        // Check for singular matrix
390        if augmented[[i, i]].abs() < 1e-10 {
391            return Err("Matrix is singular");
392        }
393
394        // Make diagonal element 1
395        let pivot = augmented[[i, i]];
396        for j in 0..2 * n {
397            augmented[[i, j]] /= pivot;
398        }
399
400        // Eliminate column
401        for k in 0..n {
402            if k != i {
403                let factor = augmented[[k, i]];
404                for j in 0..2 * n {
405                    augmented[[k, j]] -= factor * augmented[[i, j]];
406                }
407            }
408        }
409    }
410
411    // Extract inverse matrix
412    let mut inverse = Array2::zeros((n, n));
413    for i in 0..n {
414        for j in 0..n {
415            inverse[[i, j]] = augmented[[i, j + n]];
416        }
417    }
418
419    Ok(inverse)
420}