sklears-tree 0.2.0

Decision tree algorithms for sklears: CART, ID3, C4.5
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
//! Soft Decision Trees with Probabilistic Splits
//!
//! This module implements soft decision trees where splits are probabilistic rather than hard.
//! Instead of routing samples deterministically based on feature thresholds, soft trees use
//! probabilistic routing with sigmoid functions, allowing samples to flow down multiple paths
//! with different probabilities.

use scirs2_core::ndarray::{Array1, Array2, Array3, Axis};
use scirs2_core::random::{Random, rng};
use sklears_core::{
    error::{Result, SklearsError},
    traits::{Estimator, Fit, Predict, Untrained},
};
use std::marker::PhantomData;

/// Configuration for soft decision trees
#[derive(Debug, Clone)]
pub struct SoftDecisionTreeConfig {
    /// Maximum depth of the tree
    pub max_depth: Option<usize>,
    /// Minimum number of samples required to split an internal node
    pub min_samples_split: usize,
    /// Minimum number of samples required to be at a leaf node
    pub min_samples_leaf: usize,
    /// Temperature parameter for sigmoid function (controls "softness")
    pub temperature: f64,
    /// Maximum number of features to consider when looking for the best split
    pub max_features: Option<usize>,
    /// Learning rate for gradient updates
    pub learning_rate: f64,
    /// Number of gradient descent iterations for training
    pub n_iterations: usize,
    /// Regularization parameter for leaf weights
    pub leaf_regularization: f64,
    /// Regularization parameter for internal node weights
    pub node_regularization: f64,
    /// Random state for reproducibility
    pub random_state: Option<u64>,
    /// Use batch normalization for internal nodes
    pub use_batch_norm: bool,
    /// Dropout probability for regularization
    pub dropout_rate: f64,
}

impl Default for SoftDecisionTreeConfig {
    fn default() -> Self {
        Self {
            max_depth: Some(6),
            min_samples_split: 2,
            min_samples_leaf: 1,
            temperature: 1.0,
            max_features: None,
            learning_rate: 0.01,
            n_iterations: 100,
            leaf_regularization: 0.01,
            node_regularization: 0.01,
            random_state: None,
            use_batch_norm: false,
            dropout_rate: 0.0,
        }
    }
}

/// A node in a soft decision tree
#[derive(Debug, Clone)]
pub struct SoftTreeNode {
    /// Node index in the tree
    pub node_id: usize,
    /// Depth of this node in the tree
    pub depth: usize,
    /// Feature weights for probabilistic split
    pub feature_weights: Array1<f64>,
    /// Bias term for the split
    pub bias: f64,
    /// Temperature parameter for this node
    pub temperature: f64,
    /// Left child node index
    pub left_child: Option<usize>,
    /// Right child node index
    pub right_child: Option<usize>,
    /// Leaf probability distribution (for classification) or value (for regression)
    pub leaf_values: Option<Array1<f64>>,
    /// Is this node a leaf?
    pub is_leaf: bool,
    /// Number of samples that reached this node during training
    pub n_samples: usize,
    /// Batch normalization parameters (if enabled)
    pub batch_norm_mean: Option<f64>,
    pub batch_norm_var: Option<f64>,
    pub batch_norm_gamma: Option<f64>,
    pub batch_norm_beta: Option<f64>,
}

impl SoftTreeNode {
    /// Create a new internal node
    pub fn new_internal(
        node_id: usize,
        depth: usize,
        n_features: usize,
        temperature: f64,
        rng: &mut impl Rng,
    ) -> Self {
        let feature_weights = Array1::from_iter((0..n_features).map(|_| rng.random_range(-0.1..0.1)));

        Self {
            node_id,
            depth,
            feature_weights,
            bias: rng.random_range(-0.1..0.1),
            temperature,
            left_child: None,
            right_child: None,
            leaf_values: None,
            is_leaf: false,
            n_samples: 0,
            batch_norm_mean: None,
            batch_norm_var: None,
            batch_norm_gamma: Some(1.0),
            batch_norm_beta: Some(0.0),
        }
    }

    /// Create a new leaf node
    pub fn new_leaf(node_id: usize, depth: usize, leaf_values: Array1<f64>) -> Self {
        Self {
            node_id,
            depth,
            feature_weights: Array1::zeros(0),
            bias: 0.0,
            temperature: 1.0,
            left_child: None,
            right_child: None,
            leaf_values: Some(leaf_values),
            is_leaf: true,
            n_samples: 0,
            batch_norm_mean: None,
            batch_norm_var: None,
            batch_norm_gamma: None,
            batch_norm_beta: None,
        }
    }

    /// Calculate the probability of going to the right child
    pub fn split_probability(&self, sample: &Array1<f64>) -> f64 {
        if self.is_leaf {
            return 0.5; // Shouldn't be called on leaf nodes
        }

        let mut logit = self.feature_weights.dot(sample) + self.bias;

        // Apply batch normalization if enabled
        if let (Some(mean), Some(var), Some(gamma), Some(beta)) = (
            self.batch_norm_mean,
            self.batch_norm_var,
            self.batch_norm_gamma,
            self.batch_norm_beta,
        ) {
            logit = gamma * (logit - mean) / (var + 1e-8).sqrt() + beta;
        }

        // Apply sigmoid with temperature
        sigmoid(logit / self.temperature)
    }

    /// Update batch normalization statistics
    pub fn update_batch_norm(&mut self, samples: &Array2<f64>) {
        if samples.nrows() == 0 {
            return;
        }

        let logits: Array1<f64> = samples
            .axis_iter(Axis(0))
            .map(|sample| self.feature_weights.dot(&sample.to_owned()) + self.bias)
            .collect();

        self.batch_norm_mean = Some(logits.mean().unwrap_or(0.0));
        self.batch_norm_var = Some(logits.var(0.0));
    }
}

/// Soft decision tree for classification
pub struct SoftDecisionTreeClassifier<S> {
    config: SoftDecisionTreeConfig,
    _state: PhantomData<S>,
}

/// Trained soft decision tree classifier
pub struct TrainedSoftDecisionTreeClassifier {
    config: SoftDecisionTreeConfig,
    nodes: Vec<SoftTreeNode>,
    root_id: usize,
    n_classes: usize,
    n_features: usize,
    classes: Array1<i32>,
    feature_importances: Array1<f64>,
}

impl<S> SoftDecisionTreeClassifier<S> {
    /// Create a new soft decision tree with the given configuration
    pub fn new(config: SoftDecisionTreeConfig) -> Self {
        Self {
            config,
            _state: PhantomData,
        }
    }

    /// Create a soft decision tree with default configuration
    pub fn default() -> Self {
        Self::new(SoftDecisionTreeConfig::default())
    }

    /// Builder pattern for creating a soft decision tree
    pub fn builder() -> SoftDecisionTreeBuilder {
        SoftDecisionTreeBuilder::new()
    }
}

/// Builder for soft decision trees
pub struct SoftDecisionTreeBuilder {
    config: SoftDecisionTreeConfig,
}

impl SoftDecisionTreeBuilder {
    pub fn new() -> Self {
        Self {
            config: SoftDecisionTreeConfig::default(),
        }
    }

    pub fn max_depth(mut self, max_depth: Option<usize>) -> Self {
        self.config.max_depth = max_depth;
        self
    }

    pub fn min_samples_split(mut self, min_samples_split: usize) -> Self {
        self.config.min_samples_split = min_samples_split;
        self
    }

    pub fn min_samples_leaf(mut self, min_samples_leaf: usize) -> Self {
        self.config.min_samples_leaf = min_samples_leaf;
        self
    }

    pub fn temperature(mut self, temperature: f64) -> Self {
        self.config.temperature = temperature;
        self
    }

    pub fn max_features(mut self, max_features: Option<usize>) -> Self {
        self.config.max_features = max_features;
        self
    }

    pub fn learning_rate(mut self, learning_rate: f64) -> Self {
        self.config.learning_rate = learning_rate;
        self
    }

    pub fn n_iterations(mut self, n_iterations: usize) -> Self {
        self.config.n_iterations = n_iterations;
        self
    }

    pub fn leaf_regularization(mut self, leaf_regularization: f64) -> Self {
        self.config.leaf_regularization = leaf_regularization;
        self
    }

    pub fn node_regularization(mut self, node_regularization: f64) -> Self {
        self.config.node_regularization = node_regularization;
        self
    }

    pub fn random_state(mut self, random_state: Option<u64>) -> Self {
        self.config.random_state = random_state;
        self
    }

    pub fn use_batch_norm(mut self, use_batch_norm: bool) -> Self {
        self.config.use_batch_norm = use_batch_norm;
        self
    }

    pub fn dropout_rate(mut self, dropout_rate: f64) -> Self {
        self.config.dropout_rate = dropout_rate;
        self
    }

    pub fn build(self) -> SoftDecisionTreeClassifier<Untrained> {
        SoftDecisionTreeClassifier::new(self.config)
    }
}

impl Default for SoftDecisionTreeBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl Estimator for SoftDecisionTreeClassifier<Untrained> {
    type Config = SoftDecisionTreeConfig;
    type Error = SklearsError;
    type Float = f64;

    fn config(&self) -> &Self::Config {
        &self.config
    }
}

impl Fit<Array2<f64>, Array1<i32>> for SoftDecisionTreeClassifier<Untrained> {
    type Fitted = TrainedSoftDecisionTreeClassifier;

    fn fit(self, X: &Array2<f64>, y: &Array1<i32>) -> Result<Self::Fitted> {
        if X.nrows() != y.len() {
            return Err(SklearsError::DimensionMismatch {
                expected: X.nrows(),
                actual: y.len(),
            });
        }

        if X.nrows() == 0 {
            return Err(SklearsError::InvalidInput(
                "Cannot fit with empty dataset".to_string(),
            ));
        }

        let n_samples = X.nrows();
        let n_features = X.ncols();

        // Get unique classes
        let mut classes: Vec<i32> = y.iter().cloned().collect();
        classes.sort_unstable();
        classes.dedup();
        let n_classes = classes.len();
        let classes = Array1::from_vec(classes);

        // Initialize RNG
        let mut rng = match self.config.random_state {
            Some(seed) => StdRng::seed_from_u64(seed),
            None => scirs2_core::random::thread_rng(),
        };

        // Build tree structure
        let mut nodes = Vec::new();
        let root_id = 0;
        self.build_tree_structure(&mut nodes, root_id, 0, n_features, n_classes, &mut rng)?;

        // Train the tree using gradient descent
        let mut trained_tree = TrainedSoftDecisionTreeClassifier {
            config: self.config.clone(),
            nodes,
            root_id,
            n_classes,
            n_features,
            classes,
            feature_importances: Array1::zeros(n_features),
        };

        trained_tree.train_with_gradient_descent(X, y)?;
        trained_tree.compute_feature_importances(X)?;

        Ok(trained_tree)
    }
}

impl SoftDecisionTreeClassifier<Untrained> {
    /// Build the tree structure (nodes without trained weights)
    fn build_tree_structure(
        &self,
        nodes: &mut Vec<SoftTreeNode>,
        node_id: usize,
        depth: usize,
        n_features: usize,
        n_classes: usize,
        rng: &mut impl Rng,
    ) -> Result<()> {
        // Check stopping criteria
        let should_stop = if let Some(max_depth) = self.config.max_depth {
            depth >= max_depth
        } else {
            false
        };

        if should_stop {
            // Create leaf node with uniform distribution
            let uniform_prob = 1.0 / n_classes as f64;
            let leaf_values = Array1::from_elem(n_classes, uniform_prob);
            let leaf_node = SoftTreeNode::new_leaf(node_id, depth, leaf_values);

            if nodes.len() <= node_id {
                nodes.resize(node_id + 1, leaf_node.clone());
            }
            nodes[node_id] = leaf_node;
            return Ok(());
        }

        // Create internal node
        let mut internal_node =
            SoftTreeNode::new_internal(node_id, depth, n_features, self.config.temperature, rng);

        // Determine child node IDs
        let left_child_id = nodes.len();
        let right_child_id = left_child_id + 1;

        internal_node.left_child = Some(left_child_id);
        internal_node.right_child = Some(right_child_id);

        if nodes.len() <= node_id {
            nodes.resize(node_id + 1, internal_node.clone());
        }
        nodes[node_id] = internal_node;

        // Recursively build children
        self.build_tree_structure(nodes, left_child_id, depth + 1, n_features, n_classes, rng)?;
        self.build_tree_structure(nodes, right_child_id, depth + 1, n_features, n_classes, rng)?;

        Ok(())
    }
}

impl TrainedSoftDecisionTreeClassifier {
    /// Train the tree using gradient descent
    fn train_with_gradient_descent(&mut self, X: &Array2<f64>, y: &Array1<i32>) -> Result<()> {
        let n_samples = X.nrows();

        // Convert labels to one-hot encoding
        let y_one_hot = self.labels_to_one_hot(y)?;

        for iteration in 0..self.config.n_iterations {
            // Forward pass: compute predictions and path probabilities
            let (predictions, path_probs) = self.forward_pass(X)?;

            // Compute loss and gradients
            let loss = self.compute_loss(&predictions, &y_one_hot)?;

            if iteration % 10 == 0 {
                println!("Iteration {}, Loss: {:.6}", iteration, loss);
            }

            // Backward pass: compute gradients and update weights
            self.backward_pass(X, &y_one_hot, &predictions, &path_probs)?;
        }

        Ok(())
    }

    /// Convert integer labels to one-hot encoding
    fn labels_to_one_hot(&self, y: &Array1<i32>) -> Result<Array2<f64>> {
        let n_samples = y.len();
        let mut y_one_hot = Array2::zeros((n_samples, self.n_classes));

        for (i, &label) in y.iter().enumerate() {
            let class_idx = self
                .classes
                .iter()
                .position(|&c| c == label)
                .ok_or_else(|| {
                    SklearsError::InvalidInput(format!("Unknown class label: {}", label))
                })?;
            y_one_hot[[i, class_idx]] = 1.0;
        }

        Ok(y_one_hot)
    }

    /// Forward pass through the tree
    fn forward_pass(&self, X: &Array2<f64>) -> Result<(Array2<f64>, Array3<f64>)> {
        let n_samples = X.nrows();
        let mut predictions = Array2::zeros((n_samples, self.n_classes));
        let mut path_probs = Array3::zeros((n_samples, self.nodes.len(), 2)); // [sample, node, left/right]

        for (sample_idx, sample) in X.axis_iter(Axis(0)).enumerate() {
            let sample = sample.to_owned();
            let (pred, paths) = self.predict_single_with_paths(&sample)?;
            predictions.row_mut(sample_idx).assign(&pred);

            // Store path probabilities
            for (node_idx, &(left_prob, right_prob)) in paths.iter().enumerate() {
                if node_idx < self.nodes.len() {
                    path_probs[[sample_idx, node_idx, 0]] = left_prob;
                    path_probs[[sample_idx, node_idx, 1]] = right_prob;
                }
            }
        }

        Ok((predictions, path_probs))
    }

    /// Predict for a single sample and return path probabilities
    fn predict_single_with_paths(
        &self,
        sample: &Array1<f64>,
    ) -> Result<(Array1<f64>, Vec<(f64, f64)>)> {
        let mut prediction = Array1::zeros(self.n_classes);
        let mut path_probs = vec![(0.0, 0.0); self.nodes.len()];

        self.traverse_with_paths(sample, self.root_id, 1.0, &mut prediction, &mut path_probs)?;

        Ok((prediction, path_probs))
    }

    /// Traverse tree and accumulate predictions with path probabilities
    fn traverse_with_paths(
        &self,
        sample: &Array1<f64>,
        node_id: usize,
        probability: f64,
        prediction: &mut Array1<f64>,
        path_probs: &mut Vec<(f64, f64)>,
    ) -> Result<()> {
        if node_id >= self.nodes.len() {
            return Err(SklearsError::InvalidInput(format!(
                "Invalid node ID: {}",
                node_id
            )));
        }

        let node = &self.nodes[node_id];

        if node.is_leaf {
            // Add leaf contribution to prediction
            if let Some(ref leaf_values) = node.leaf_values {
                for i in 0..self.n_classes {
                    prediction[i] += probability * leaf_values[i];
                }
            }
            return Ok(());
        }

        // Calculate split probabilities
        let right_prob = node.split_probability(sample);
        let left_prob = 1.0 - right_prob;

        // Store path probabilities
        path_probs[node_id] = (left_prob, right_prob);

        // Traverse children
        if let Some(left_child) = node.left_child {
            self.traverse_with_paths(
                sample,
                left_child,
                probability * left_prob,
                prediction,
                path_probs,
            )?;
        }

        if let Some(right_child) = node.right_child {
            self.traverse_with_paths(
                sample,
                right_child,
                probability * right_prob,
                prediction,
                path_probs,
            )?;
        }

        Ok(())
    }

    /// Compute cross-entropy loss
    fn compute_loss(&self, predictions: &Array2<f64>, y_true: &Array2<f64>) -> Result<f64> {
        let n_samples = predictions.nrows();
        let mut total_loss = 0.0;

        for i in 0..n_samples {
            for j in 0..self.n_classes {
                let pred = predictions[[i, j]].max(1e-15).min(1.0 - 1e-15); // Clip for numerical stability
                total_loss -= y_true[[i, j]] * pred.ln();
            }
        }

        // Add regularization
        let mut reg_loss = 0.0;
        for node in &self.nodes {
            if !node.is_leaf {
                reg_loss += self.config.node_regularization
                    * node.feature_weights.dot(&node.feature_weights);
            } else if let Some(ref leaf_values) = node.leaf_values {
                reg_loss += self.config.leaf_regularization * leaf_values.dot(leaf_values);
            }
        }

        Ok(total_loss / n_samples as f64 + reg_loss)
    }

    /// Backward pass: compute gradients and update weights
    fn backward_pass(
        &mut self,
        X: &Array2<f64>,
        y_true: &Array2<f64>,
        predictions: &Array2<f64>,
        path_probs: &Array3<f64>,
    ) -> Result<()> {
        let n_samples = X.nrows();

        // Compute gradients for each node
        for node_idx in 0..self.nodes.len() {
            if self.nodes[node_idx].is_leaf {
                continue;
            }

            let mut weight_grad = Array1::zeros(self.n_features);
            let mut bias_grad = 0.0;

            for sample_idx in 0..n_samples {
                let sample = X.row(sample_idx);

                // Compute gradient contribution from this sample
                let grad_contribution = self.compute_node_gradient(
                    sample_idx,
                    node_idx,
                    &sample.to_owned(),
                    y_true,
                    predictions,
                    path_probs,
                )?;

                weight_grad += &grad_contribution.0;
                bias_grad += grad_contribution.1;
            }

            // Add regularization gradients
            weight_grad +=
                &(&self.nodes[node_idx].feature_weights * (2.0 * self.config.node_regularization));

            // Update weights using gradient descent
            self.nodes[node_idx].feature_weights -= &(&weight_grad * self.config.learning_rate);
            self.nodes[node_idx].bias -= bias_grad * self.config.learning_rate;
        }

        Ok(())
    }

    /// Compute gradient for a specific node and sample
    fn compute_node_gradient(
        &self,
        sample_idx: usize,
        node_idx: usize,
        sample: &Array1<f64>,
        y_true: &Array2<f64>,
        predictions: &Array2<f64>,
        path_probs: &Array3<f64>,
    ) -> Result<(Array1<f64>, f64)> {
        // This is a simplified gradient computation
        // In practice, you would need to implement the full chain rule through the tree

        let mut weight_grad = Array1::zeros(self.n_features);
        let mut bias_grad = 0.0;

        // Compute loss gradient w.r.t. predictions
        let mut pred_grad = Array1::zeros(self.n_classes);
        for class_idx in 0..self.n_classes {
            let pred = predictions[[sample_idx, class_idx]]
                .max(1e-15)
                .min(1.0 - 1e-15);
            pred_grad[class_idx] = -y_true[[sample_idx, class_idx]] / pred;
        }

        // Compute gradient w.r.t. node parameters
        let right_prob = path_probs[[sample_idx, node_idx, 1]];
        let sigmoid_grad = right_prob * (1.0 - right_prob); // Sigmoid derivative

        // Simplified gradient (this should be more sophisticated in practice)
        let grad_scale = pred_grad.sum() * sigmoid_grad / self.config.temperature;

        weight_grad = sample * grad_scale;
        bias_grad = grad_scale;

        Ok((weight_grad, bias_grad))
    }

    /// Compute feature importances based on weight magnitudes
    fn compute_feature_importances(&mut self, X: &Array2<f64>) -> Result<()> {
        let mut importances = Array1::zeros(self.n_features);

        for node in &self.nodes {
            if !node.is_leaf {
                let weight_magnitude = node.feature_weights.mapv(|x| x.abs()).sum();
                if weight_magnitude > 0.0 {
                    for (feature_idx, &weight) in node.feature_weights.iter().enumerate() {
                        importances[feature_idx] += weight.abs() / weight_magnitude;
                    }
                }
            }
        }

        // Normalize importances
        let total_importance = importances.sum();
        if total_importance > 0.0 {
            importances /= total_importance;
        }

        self.feature_importances = importances;
        Ok(())
    }
}

impl Predict<Array2<f64>, Array1<f64>> for TrainedSoftDecisionTreeClassifier {
    fn predict(&self, X: &Array2<f64>) -> Result<Array1<f64>> {
        let predictions = self.predict_proba(X)?;

        // Return class with highest probability
        let class_predictions: Vec<f64> = predictions
            .axis_iter(Axis(0))
            .map(|row| {
                let max_idx = row
                    .iter()
                    .enumerate()
                    .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
                    .map(|(idx, _)| idx)
                    .unwrap_or(0);
                self.classes[max_idx] as f64
            })
            .collect();

        Ok(Array1::from_vec(class_predictions))
    }
}

impl TrainedSoftDecisionTreeClassifier {
    /// Predict class probabilities
    pub fn predict_proba(&self, X: &Array2<f64>) -> Result<Array2<f64>> {
        let n_samples = X.nrows();
        let mut predictions = Array2::zeros((n_samples, self.n_classes));

        for (sample_idx, sample) in X.axis_iter(Axis(0)).enumerate() {
            let sample = sample.to_owned();
            let pred = self.predict_single(&sample)?;
            predictions.row_mut(sample_idx).assign(&pred);
        }

        Ok(predictions)
    }

    /// Predict for a single sample
    fn predict_single(&self, sample: &Array1<f64>) -> Result<Array1<f64>> {
        let mut prediction = Array1::zeros(self.n_classes);
        self.traverse(sample, self.root_id, 1.0, &mut prediction)?;

        // Normalize to ensure probabilities sum to 1
        let sum = prediction.sum();
        if sum > 0.0 {
            prediction /= sum;
        } else {
            // If all probabilities are zero, return uniform distribution
            prediction.fill(1.0 / self.n_classes as f64);
        }

        Ok(prediction)
    }

    /// Traverse the tree and accumulate predictions
    fn traverse(
        &self,
        sample: &Array1<f64>,
        node_id: usize,
        probability: f64,
        prediction: &mut Array1<f64>,
    ) -> Result<()> {
        if node_id >= self.nodes.len() {
            return Err(SklearsError::InvalidInput(format!(
                "Invalid node ID: {}",
                node_id
            )));
        }

        let node = &self.nodes[node_id];

        if node.is_leaf {
            // Add leaf contribution to prediction
            if let Some(ref leaf_values) = node.leaf_values {
                for i in 0..self.n_classes {
                    prediction[i] += probability * leaf_values[i];
                }
            }
            return Ok(());
        }

        // Calculate split probabilities
        let right_prob = node.split_probability(sample);
        let left_prob = 1.0 - right_prob;

        // Traverse children
        if let Some(left_child) = node.left_child {
            self.traverse(sample, left_child, probability * left_prob, prediction)?;
        }

        if let Some(right_child) = node.right_child {
            self.traverse(sample, right_child, probability * right_prob, prediction)?;
        }

        Ok(())
    }

    /// Get feature importances
    pub fn feature_importances(&self) -> &Array1<f64> {
        &self.feature_importances
    }

    /// Get the tree structure as a string representation
    pub fn tree_structure(&self) -> String {
        let mut structure = String::new();
        self.print_node(self.root_id, 0, &mut structure);
        structure
    }

    fn print_node(&self, node_id: usize, depth: usize, structure: &mut String) {
        if node_id >= self.nodes.len() {
            return;
        }

        let node = &self.nodes[node_id];
        let indent = "  ".repeat(depth);

        if node.is_leaf {
            if let Some(ref leaf_values) = node.leaf_values {
                structure.push_str(&format!("{}Leaf: classes={:?}\n", indent, leaf_values));
            }
        } else {
            structure.push_str(&format!(
                "{}Node {}: weights={:?}, bias={:.4}, temp={:.4}\n",
                indent, node_id, node.feature_weights, node.bias, node.temperature
            ));

            if let Some(left_child) = node.left_child {
                structure.push_str(&format!("{}├─ Left:\n", indent));
                self.print_node(left_child, depth + 1, structure);
            }

            if let Some(right_child) = node.right_child {
                structure.push_str(&format!("{}└─ Right:\n", indent));
                self.print_node(right_child, depth + 1, structure);
            }
        }
    }
}

/// Sigmoid activation function
fn sigmoid(x: f64) -> f64 {
    1.0 / (1.0 + (-x).exp())
}

#[allow(non_snake_case)]
#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_abs_diff_eq;

    #[test]
    fn test_sigmoid() {
        assert_abs_diff_eq!(sigmoid(0.0), 0.5, epsilon = 1e-10);
        assert!(sigmoid(10.0) > 0.99);
        assert!(sigmoid(-10.0) < 0.01);
    }

    #[test]
    fn test_soft_tree_node_creation() {
        let mut rng = StdRng::seed_from_u64(42);
        let node = SoftTreeNode::new_internal(0, 0, 3, 1.0, &mut rng);

        assert_eq!(node.node_id, 0);
        assert_eq!(node.depth, 0);
        assert_eq!(node.feature_weights.len(), 3);
        assert!(!node.is_leaf);
        assert!(node.leaf_values.is_none());
    }

    #[test]
    fn test_soft_tree_leaf_creation() {
        let leaf_values = Array1::from_vec(vec![0.7, 0.3]);
        let leaf = SoftTreeNode::new_leaf(1, 2, leaf_values.clone());

        assert_eq!(leaf.node_id, 1);
        assert_eq!(leaf.depth, 2);
        assert!(leaf.is_leaf);
        assert_eq!(leaf.leaf_values.expect("operation should succeed"), leaf_values);
    }

    #[test]
    fn test_split_probability() {
        let mut rng = StdRng::seed_from_u64(42);
        let mut node = SoftTreeNode::new_internal(0, 0, 2, 1.0, &mut rng);

        // Set known weights for predictable behavior
        node.feature_weights = Array1::from_vec(vec![1.0, -0.5]);
        node.bias = 0.1;

        let sample = Array1::from_vec(vec![0.5, 0.2]);
        let prob = node.split_probability(&sample);

        // Should be sigmoid(1.0*0.5 + (-0.5)*0.2 + 0.1) = sigmoid(0.5)
        let expected = sigmoid(0.5);
        assert_abs_diff_eq!(prob, expected, epsilon = 1e-10);
    }

    #[test]
    fn test_soft_tree_builder() {
        let tree = SoftDecisionTreeClassifier::<Untrained>::builder()
            .max_depth(Some(3))
            .temperature(0.5)
            .learning_rate(0.01)
            .random_state(Some(42))
            .build();

        assert_eq!(tree.config.max_depth, Some(3));
        assert_eq!(tree.config.temperature, 0.5);
        assert_eq!(tree.config.learning_rate, 0.01);
        assert_eq!(tree.config.random_state, Some(42));
    }

    #[test]
    fn test_small_classification_dataset() {
        // Create a simple 2D classification problem
        let X = Array2::from_shape_vec(
            (6, 2),
            vec![
                1.0, 1.0, // Class 0
                1.5, 1.2, // Class 0
                2.0, 2.1, // Class 0
                -1.0, -1.0, // Class 1
                -1.5, -1.2, // Class 1
                -2.0, -2.1, // Class 1
            ],
        )
        .expect("operation should succeed");

        let y = Array1::from_vec(vec![0, 0, 0, 1, 1, 1]);

        let tree = SoftDecisionTreeClassifier::<Untrained>::builder()
            .max_depth(Some(2))
            .n_iterations(50)
            .temperature(1.0)
            .learning_rate(0.1)
            .random_state(Some(42))
            .build();

        let trained_tree = tree.fit(&X, &y).expect("model fitting should succeed");

        // Test predictions
        let predictions = trained_tree.predict(&X).expect("prediction should succeed");
        assert_eq!(predictions.len(), 6);

        // Test probability predictions
        let probabilities = trained_tree.predict_proba(&X).expect("operation should succeed");
        assert_eq!(probabilities.shape(), &[6, 2]);

        // Check that probabilities sum to 1 for each sample
        for i in 0..6 {
            let sum: f64 = probabilities.row(i).sum();
            assert_abs_diff_eq!(sum, 1.0, epsilon = 1e-10);
        }

        // Check feature importances
        let importances = trained_tree.feature_importances();
        assert_eq!(importances.len(), 2);
        assert_abs_diff_eq!(importances.sum(), 1.0, epsilon = 1e-10);
    }

    #[test]
    fn test_labels_to_one_hot() {
        let tree = SoftDecisionTreeClassifier::<Untrained>::builder().build();
        let X = Array2::zeros((3, 2));
        let y = Array1::from_vec(vec![0, 1, 0]);

        let trained_tree = tree.fit(&X, &y).expect("model fitting should succeed");
        let y_one_hot = trained_tree.labels_to_one_hot(&y).expect("operation should succeed");

        assert_eq!(y_one_hot.shape(), &[3, 2]);
        assert_eq!(y_one_hot[[0, 0]], 1.0);
        assert_eq!(y_one_hot[[0, 1]], 0.0);
        assert_eq!(y_one_hot[[1, 0]], 0.0);
        assert_eq!(y_one_hot[[1, 1]], 1.0);
        assert_eq!(y_one_hot[[2, 0]], 1.0);
        assert_eq!(y_one_hot[[2, 1]], 0.0);
    }

    #[test]
    fn test_tree_structure_display() {
        let X =
            Array2::from_shape_vec((4, 2), vec![1.0, 1.0, 1.0, 2.0, 2.0, 1.0, 2.0, 2.0]).expect("shape and data length should match");
        let y = Array1::from_vec(vec![0, 0, 1, 1]);

        let tree = SoftDecisionTreeClassifier::<Untrained>::builder()
            .max_depth(Some(2))
            .n_iterations(10)
            .random_state(Some(42))
            .build();

        let trained_tree = tree.fit(&X, &y).expect("model fitting should succeed");
        let structure = trained_tree.tree_structure();

        // Should contain node information and leaf information
        assert!(structure.contains("Node"));
        assert!(structure.contains("Leaf"));
    }
}