1use 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
13pub use crate::criteria::SplitCriterion;
16
17#[derive(Debug, Clone, Copy, PartialEq)]
19pub enum MonotonicConstraint {
20 None,
22 Increasing,
24 Decreasing,
26}
27
28#[derive(Debug, Clone)]
30pub enum InteractionConstraint {
31 None,
33 Groups(Vec<Vec<usize>>),
35 Forbidden(Vec<(usize, usize)>),
37 Allowed(Vec<(usize, usize)>),
39}
40
41#[derive(Debug, Clone)]
43pub enum FeatureGrouping {
44 None,
46 AutoCorrelation {
48 threshold: Float,
50 selection_method: GroupSelectionMethod,
52 },
53 Manual {
55 groups: Vec<Vec<usize>>,
57 selection_method: GroupSelectionMethod,
59 },
60 Hierarchical {
62 n_clusters: usize,
64 linkage: LinkageMethod,
66 selection_method: GroupSelectionMethod,
68 },
69}
70
71#[derive(Debug, Clone, Copy, PartialEq)]
73pub enum GroupSelectionMethod {
74 MaxVariance,
76 MaxTargetCorrelation,
78 First,
80 Random,
82 WeightedAll,
84}
85
86#[derive(Debug, Clone, Copy, PartialEq)]
88pub enum LinkageMethod {
89 Single,
91 Complete,
93 Average,
95 Ward,
97}
98
99#[derive(Debug, Clone)]
101pub struct FeatureGroupInfo {
102 pub groups: Vec<Vec<usize>>,
104 pub representatives: Vec<usize>,
106 pub correlation_matrix: Option<Array2<Float>>,
108 pub group_correlations: Vec<Float>,
110}
111
112#[derive(Debug, Clone)]
114pub enum MaxFeatures {
115 All,
117 Sqrt,
119 Log2,
121 Number(usize),
123 Fraction(f64),
125}
126
127#[derive(Debug, Clone, Copy)]
129pub enum PruningStrategy {
130 None,
132 CostComplexity { alpha: f64 },
134 ReducedError,
136}
137
138#[derive(Debug, Clone, Copy)]
140pub enum MissingValueStrategy {
141 Skip,
143 Majority,
145 Surrogate,
147}
148
149#[derive(Debug, Clone)]
151pub enum FeatureType {
152 Continuous,
154 Categorical(Vec<String>),
156}
157
158#[derive(Debug, Clone)]
160pub struct MultiwaySplit {
161 pub feature_idx: usize,
163 pub category_branches: Vec<Vec<String>>,
165 pub impurity_decrease: f64,
167}
168
169#[derive(Debug, Clone, Copy)]
171pub enum TreeGrowingStrategy {
172 DepthFirst,
174 BestFirst { max_leaves: Option<usize> },
176}
177
178#[derive(Debug, Clone, Copy)]
180pub enum SplitType {
181 AxisAligned,
183 Oblique {
185 n_hyperplanes: usize,
187 use_ridge: bool,
189 },
190}
191
192#[derive(Debug, Clone)]
194pub struct HyperplaneSplit {
195 pub coefficients: Array1<f64>,
197 pub threshold: f64,
199 pub bias: f64,
201 pub impurity_decrease: f64,
203}
204
205impl HyperplaneSplit {
206 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 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 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 #[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 let mut x_bias = Array2::ones((x.nrows(), n_features + 1));
249 x_bias.slice_mut(s![.., ..n_features]).assign(x);
250
251 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 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, bias,
268 impurity_decrease: 0.0,
269 })
270 }
271 Err(_) => {
272 let mut rng = scirs2_core::random::thread_rng();
274 Ok(Self::random(n_features, &mut rng))
275 }
276 }
277 }
278}
279
280#[derive(Debug, Clone)]
282pub struct DecisionTreeConfig {
283 pub criterion: SplitCriterion,
285 pub max_depth: Option<usize>,
287 pub min_samples_split: usize,
289 pub min_samples_leaf: usize,
291 pub max_features: MaxFeatures,
293 pub random_state: Option<u64>,
295 pub min_weight_fraction_leaf: f64,
297 pub min_impurity_decrease: f64,
299 pub pruning: PruningStrategy,
301 pub missing_values: MissingValueStrategy,
303 pub feature_types: Option<Vec<FeatureType>>,
305 pub growing_strategy: TreeGrowingStrategy,
307 pub split_type: SplitType,
309 pub monotonic_constraints: Option<Vec<MonotonicConstraint>>,
311 pub interaction_constraints: InteractionConstraint,
313 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
340pub 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#[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 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 for i in 0..n {
372 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 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 if augmented[[i, i]].abs() < 1e-10 {
391 return Err("Matrix is singular");
392 }
393
394 let pivot = augmented[[i, i]];
396 for j in 0..2 * n {
397 augmented[[i, j]] /= pivot;
398 }
399
400 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 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}