sklears_tree/
decision_tree.rs1use scirs2_core::ndarray::{Array1, Array2, ArrayView1, ArrayView2};
18use sklears_core::error::{Result, SklearsError};
19use sklears_core::traits::{Estimator, Fit, Predict, Trained, Untrained};
20use std::marker::PhantomData;
21
22pub use crate::config::DecisionTreeConfig;
24pub use crate::criteria::{ConditionalTestType, FeatureType, MonotonicConstraint, SplitCriterion};
25pub use crate::node::{CompactTreeNode, CustomSplit, SurrogateSplit, TreeNode};
26pub use crate::splits::{ChaidSplit, HyperplaneSplit};
27
28#[derive(Debug, Clone)]
30pub struct DecisionTree<State = Untrained> {
31 config: DecisionTreeConfig,
32 root: Option<TreeNode>,
33 feature_importances: Option<Array1<f64>>,
34 n_features: usize,
35 n_samples: usize,
36 state: PhantomData<State>,
37}
38
39impl<State> Default for DecisionTree<State> {
40 fn default() -> Self {
41 Self::new()
42 }
43}
44
45impl<State> DecisionTree<State> {
46 pub fn new() -> Self {
48 Self {
49 config: DecisionTreeConfig::default(),
50 root: None,
51 feature_importances: None,
52 n_features: 0,
53 n_samples: 0,
54 state: PhantomData,
55 }
56 }
57
58 pub fn with_config(config: DecisionTreeConfig) -> Self {
60 Self {
61 config,
62 root: None,
63 feature_importances: None,
64 n_features: 0,
65 n_samples: 0,
66 state: PhantomData,
67 }
68 }
69
70 pub fn builder() -> DecisionTreeBuilder<State> {
72 DecisionTreeBuilder::new()
73 }
74
75 pub fn config(&self) -> &DecisionTreeConfig {
77 &self.config
78 }
79
80 pub fn root(&self) -> Option<&TreeNode> {
82 self.root.as_ref()
83 }
84
85 pub fn feature_importances(&self) -> Option<&Array1<f64>> {
87 self.feature_importances.as_ref()
88 }
89
90 pub fn n_features(&self) -> usize {
92 self.n_features
93 }
94
95 pub fn n_samples(&self) -> usize {
97 self.n_samples
98 }
99
100 pub fn depth(&self) -> usize {
102 match &self.root {
103 Some(root) => root.depth,
104 None => 0,
105 }
106 }
107
108 pub fn criterion(mut self, criterion: SplitCriterion) -> Self {
110 self.config.criterion = criterion;
111 self
112 }
113
114 pub fn max_depth(mut self, max_depth: usize) -> Self {
116 self.config.max_depth = Some(max_depth);
117 self
118 }
119
120 pub fn min_samples_split(mut self, min_samples_split: usize) -> Self {
122 self.config.min_samples_split = min_samples_split;
123 self
124 }
125
126 pub fn min_samples_leaf(mut self, min_samples_leaf: usize) -> Self {
128 self.config.min_samples_leaf = min_samples_leaf;
129 self
130 }
131
132 pub fn missing_values(mut self, strategy: crate::config::MissingValueStrategy) -> Self {
134 self.config.missing_values = strategy;
135 self
136 }
137
138 pub fn random_state(mut self, random_state: Option<u64>) -> Self {
140 self.config.random_state = random_state;
141 self
142 }
143}
144
145#[derive(Debug)]
147pub struct DecisionTreeBuilder<State> {
148 config: DecisionTreeConfig,
149 _marker: PhantomData<State>,
150}
151
152impl<State> DecisionTreeBuilder<State> {
153 pub fn new() -> Self {
155 Self {
156 config: DecisionTreeConfig::default(),
157 _marker: PhantomData,
158 }
159 }
160
161 pub fn criterion(mut self, criterion: SplitCriterion) -> Self {
163 self.config.criterion = criterion;
164 self
165 }
166
167 pub fn max_depth(mut self, max_depth: Option<usize>) -> Self {
169 self.config.max_depth = max_depth;
170 self
171 }
172
173 pub fn min_samples_split(mut self, min_samples_split: usize) -> Self {
175 self.config.min_samples_split = min_samples_split;
176 self
177 }
178
179 pub fn min_samples_leaf(mut self, min_samples_leaf: usize) -> Self {
181 self.config.min_samples_leaf = min_samples_leaf;
182 self
183 }
184
185 pub fn min_impurity_decrease(mut self, min_impurity_decrease: f64) -> Self {
187 self.config.min_impurity_decrease = min_impurity_decrease;
188 self
189 }
190
191 pub fn max_features(self, _max_features: Option<usize>) -> Self {
193 self
196 }
197
198 pub fn random_state(mut self, random_state: Option<u64>) -> Self {
200 self.config.random_state = random_state;
201 self
202 }
203
204 pub fn build(self) -> DecisionTree<State> {
206 DecisionTree::with_config(self.config)
207 }
208}
209
210impl<State> Default for DecisionTreeBuilder<State> {
211 fn default() -> Self {
212 Self::new()
213 }
214}
215
216impl DecisionTree<Untrained> {
219 pub fn is_fitted(&self) -> bool {
221 false
222 }
223
224 pub fn n_classes(&self) -> usize {
226 0 }
228}
229
230pub struct TreeValidator;
232
233impl TreeValidator {
234 pub fn validate_input(x: &ArrayView2<'_, f64>, y: &ArrayView1<'_, f64>) -> Result<()> {
236 if x.nrows() != y.len() {
237 return Err(SklearsError::InvalidInput(format!(
238 "Number of samples in X ({}) does not match number of targets in y ({})",
239 x.nrows(),
240 y.len()
241 )));
242 }
243
244 if x.nrows() == 0 {
245 return Err(SklearsError::InvalidInput(
246 "Input arrays must contain at least one sample".to_string(),
247 ));
248 }
249
250 if x.ncols() == 0 {
251 return Err(SklearsError::InvalidInput(
252 "Input arrays must contain at least one feature".to_string(),
253 ));
254 }
255
256 Ok(())
257 }
258
259 pub fn validate_fitted(_tree: &DecisionTree<Trained>) -> Result<()> {
261 Ok(())
263 }
264
265 pub fn validate_prediction_input(
267 tree: &DecisionTree<Trained>,
268 x: &ArrayView2<'_, f64>,
269 ) -> Result<()> {
270 Self::validate_fitted(tree)?;
271
272 if x.ncols() != tree.n_features() {
273 return Err(SklearsError::InvalidInput(format!(
274 "Number of features in X ({}) does not match number of features seen during fit ({})",
275 x.ncols(),
276 tree.n_features()
277 )));
278 }
279
280 Ok(())
281 }
282}
283
284impl Estimator<Untrained> for DecisionTree<Untrained> {
287 type Config = DecisionTreeConfig;
288 type Error = SklearsError;
289 type Float = f64;
290
291 fn config(&self) -> &Self::Config {
292 &self.config
293 }
294}
295
296impl Estimator<Trained> for DecisionTree<Trained> {
297 type Config = DecisionTreeConfig;
298 type Error = SklearsError;
299 type Float = f64;
300
301 fn config(&self) -> &Self::Config {
302 &self.config
303 }
304}
305
306impl Fit<Array2<f64>, Array1<f64>, Untrained> for DecisionTree<Untrained> {
307 type Fitted = DecisionTree<Trained>;
308
309 fn fit(self, x: &Array2<f64>, y: &Array1<f64>) -> Result<Self::Fitted> {
310 TreeValidator::validate_input(&x.view(), &y.view())?;
312
313 let fitted_tree = DecisionTree::<Trained> {
319 config: self.config,
320 root: None,
321 feature_importances: None,
322 n_features: x.ncols(),
323 n_samples: x.nrows(),
324 state: PhantomData,
325 };
326
327 Ok(fitted_tree)
328 }
329}
330
331impl Predict<Array2<f64>, Array1<f64>> for DecisionTree<Trained> {
332 fn predict(&self, x: &Array2<f64>) -> Result<Array1<f64>> {
333 TreeValidator::validate_prediction_input(self, &x.view())?;
334
335 let predictions = Array1::zeros(x.nrows());
339
340 Ok(predictions)
341 }
342}
343
344impl DecisionTree<Trained> {
345 pub fn is_fitted(&self) -> bool {
347 true
348 }
349
350 pub fn n_classes(&self) -> usize {
355 2
356 }
357}