Skip to main content

lib_jsl_machine_learning/supervised/classification/
random_forest.rs

1//! Decision trees and random forests.
2//!
3//! See the book entry [Decision trees and random forests](https://jwkunz.github.io/lib_jsl/book/machine_learning/decision-trees.html).
4
5use crate::common::{Classifier, MlRng, argmax, check_features, check_xy, class_count};
6use lib_jsl_core::{ErrorsJSL, R2D, VR2D};
7
8#[derive(Debug, Clone)]
9enum Node {
10    Leaf { distribution: Vec<f64> },
11    Split { feature: usize, threshold: f64, left: Box<Node>, right: Box<Node> },
12}
13
14/// A CART classification tree grown greedily by Gini impurity.
15#[derive(Debug, Clone)]
16pub struct DecisionTree {
17    max_depth: usize,
18    min_samples_split: usize,
19    /// Features examined at each split (`None` = all); used by forests for decorrelation.
20    max_features: Option<usize>,
21    seed: u64,
22    root: Option<Node>,
23    classes: usize,
24    features: usize,
25}
26
27fn gini(counts: &[f64], total: f64) -> f64 {
28    if total == 0.0 { 0.0 } else { 1.0 - counts.iter().map(|c| (c / total).powi(2)).sum::<f64>() }
29}
30
31impl DecisionTree {
32    pub fn new(max_depth: usize) -> Self {
33        DecisionTree { max_depth, min_samples_split: 2, max_features: None, seed: 0, root: None, classes: 0, features: 0 }
34    }
35
36    pub fn with_min_samples_split(mut self, n: usize) -> Self {
37        self.min_samples_split = n.max(2);
38        self
39    }
40
41    pub fn with_max_features(mut self, m: usize, seed: u64) -> Self {
42        self.max_features = Some(m);
43        self.seed = seed;
44        self
45    }
46
47    /// Depth of the grown tree (0 for a single leaf).
48    pub fn depth(&self) -> usize {
49        fn go(n: &Node) -> usize {
50            match n {
51                Node::Leaf { .. } => 0,
52                Node::Split { left, right, .. } => 1 + go(left).max(go(right)),
53            }
54        }
55        self.root.as_ref().map_or(0, go)
56    }
57
58    fn grow(&self, x: VR2D, labels: &[usize], idx: &[usize], depth: usize, rng: &mut MlRng) -> Node {
59        let mut counts = vec![0.0; self.classes];
60        idx.iter().for_each(|&i| counts[labels[i]] += 1.0);
61        let n = idx.len() as f64;
62        let leaf = |counts: &[f64]| Node::Leaf { distribution: counts.iter().map(|c| c / n).collect() };
63        let parent = gini(&counts, n);
64        if depth >= self.max_depth || idx.len() < self.min_samples_split || parent == 0.0 {
65            return leaf(&counts);
66        }
67        let candidates: Vec<usize> = match self.max_features {
68            Some(m) => rng.sample_indices(self.features, m.clamp(1, self.features)),
69            None => (0..self.features).collect(),
70        };
71        // ANCHOR: cart_split
72        let mut best: Option<(f64, usize, f64)> = None; // (impurity decrease, feature, threshold)
73        for &f in &candidates {
74            let mut order: Vec<usize> = idx.to_vec();
75            order.sort_by(|&a, &b| x[[a, f]].total_cmp(&x[[b, f]]));
76            let mut left = vec![0.0; self.classes];
77            for k in 0..order.len() - 1 {
78                left[labels[order[k]]] += 1.0;
79                let (a, b) = (x[[order[k], f]], x[[order[k + 1], f]]);
80                if a == b {
81                    continue;
82                }
83                let nl = (k + 1) as f64;
84                let right: Vec<f64> = counts.iter().zip(&left).map(|(c, l)| c - l).collect();
85                let weighted = (nl * gini(&left, nl) + (n - nl) * gini(&right, n - nl)) / n;
86                let gain = parent - weighted;
87                if best.is_none_or(|(g, _, _)| gain > g + 1e-15) {
88                    best = Some((gain, f, 0.5 * (a + b)));
89                }
90            }
91        }
92        match best {
93            // Zero-gain splits are allowed: structure such as XOR has no single split that improves
94            // purity, yet splitting twice separates it. Depth and node-size limits ensure termination.
95            Some((gain, feature, threshold)) if gain > -1e-12 => {
96                let (l, r): (Vec<usize>, Vec<usize>) = idx.iter().partition(|&&i| x[[i, feature]] <= threshold);
97                Node::Split { feature, threshold, left: Box::new(self.grow(x, labels, &l, depth + 1, rng)), right: Box::new(self.grow(x, labels, &r, depth + 1, rng)) }
98            }
99            _ => leaf(&counts),
100        }
101        // ANCHOR_END: cart_split
102    }
103
104    fn distribution(&self, row: &[f64]) -> &[f64] {
105        let mut node = self.root.as_ref().expect("fitted");
106        loop {
107            match node {
108                Node::Leaf { distribution } => return distribution,
109                Node::Split { feature, threshold, left, right } => node = if row[*feature] <= *threshold { left } else { right },
110            }
111        }
112    }
113
114    /// Class probabilities (the leaf's class shares) for each row.
115    pub fn predict_proba(&self, x: VR2D) -> Result<R2D, ErrorsJSL> {
116        if self.root.is_none() {
117            return Err(ErrorsJSL::Misconfiguration("The model has not been fitted."));
118        }
119        check_features(x)?;
120        if x.ncols() != self.features {
121            return Err(ErrorsJSL::IncompatibleArraySizes((x.ncols(), self.features)));
122        }
123        Ok(R2D::from_shape_fn((x.nrows(), self.classes), |(i, c)| self.distribution(&x.row(i).to_vec())[c]))
124    }
125
126    fn fit_subset(&mut self, x: VR2D, labels: &[usize], idx: &[usize], classes: usize) {
127        self.classes = classes;
128        self.features = x.ncols();
129        let mut rng = MlRng::new(self.seed);
130        self.root = Some(self.grow(x, labels, idx, 0, &mut rng));
131    }
132}
133
134impl Classifier for DecisionTree {
135    fn fit(&mut self, x: VR2D, labels: &[usize]) -> Result<(), ErrorsJSL> {
136        check_xy(x, labels.len())?;
137        let idx: Vec<usize> = (0..x.nrows()).collect();
138        self.fit_subset(x, labels, &idx, class_count(labels));
139        Ok(())
140    }
141
142    fn predict(&self, x: VR2D) -> Result<Vec<usize>, ErrorsJSL> {
143        Ok(self.predict_proba(x)?.rows().into_iter().map(|r| argmax(&r.to_vec()).unwrap_or(0)).collect())
144    }
145}
146
147/// A random forest: many decorrelated decision trees, each grown on a bootstrap resample of the
148/// data and restricted to a random subset of features at every split (default `√features`), with
149/// predictions made by averaging the trees' class probabilities. Averaging cancels the variance
150/// of the individual deep trees, so forests resist overfitting. The out-of-bag error (each tree
151/// scored on the samples it never saw) gives a free generalisation estimate.
152#[derive(Debug, Clone)]
153pub struct RandomForest {
154    trees: usize,
155    max_depth: usize,
156    max_features: Option<usize>,
157    seed: u64,
158    forest: Vec<DecisionTree>,
159    classes: usize,
160    oob_accuracy: Option<f64>,
161    importances: Vec<f64>,
162}
163
164impl RandomForest {
165    pub fn new(trees: usize, max_depth: usize, seed: u64) -> Self {
166        RandomForest { trees, max_depth, max_features: None, seed, forest: Vec::new(), classes: 0, oob_accuracy: None, importances: Vec::new() }
167    }
168
169    pub fn with_max_features(mut self, m: usize) -> Self {
170        self.max_features = Some(m);
171        self
172    }
173
174    /// Accuracy on out-of-bag samples from the last fit, if every sample was out of bag at least once.
175    pub fn oob_accuracy(&self) -> Option<f64> {
176        self.oob_accuracy
177    }
178
179    /// How often each feature is used for a split, normalised to sum to one.
180    pub fn feature_importances(&self) -> &[f64] {
181        &self.importances
182    }
183
184    pub fn predict_proba(&self, x: VR2D) -> Result<R2D, ErrorsJSL> {
185        if self.forest.is_empty() {
186            return Err(ErrorsJSL::Misconfiguration("The model has not been fitted."));
187        }
188        let mut total = self.forest[0].predict_proba(x)?;
189        for t in &self.forest[1..] {
190            total += &t.predict_proba(x)?;
191        }
192        Ok(total / self.forest.len() as f64)
193    }
194}
195
196fn count_splits(node: &Node, counts: &mut [f64]) {
197    if let Node::Split { feature, left, right, .. } = node {
198        counts[*feature] += 1.0;
199        count_splits(left, counts);
200        count_splits(right, counts);
201    }
202}
203
204impl Classifier for RandomForest {
205    fn fit(&mut self, x: VR2D, labels: &[usize]) -> Result<(), ErrorsJSL> {
206        check_xy(x, labels.len())?;
207        if self.trees == 0 {
208            return Err(ErrorsJSL::InvalidInputRange("A forest needs at least one tree."));
209        }
210        let (n, p) = x.dim();
211        let classes = class_count(labels);
212        let m = self.max_features.unwrap_or(((p as f64).sqrt().round() as usize).max(1));
213        let mut rng = MlRng::new(self.seed);
214        self.forest.clear();
215        let mut oob_votes = vec![vec![0.0; classes]; n];
216        let mut oob_seen = vec![false; n];
217        // ANCHOR: forest
218        for t in 0..self.trees {
219            let sample: Vec<usize> = (0..n).map(|_| rng.below(n)).collect();
220            let mut in_bag = vec![false; n];
221            sample.iter().for_each(|&i| in_bag[i] = true);
222            let mut tree = DecisionTree::new(self.max_depth).with_max_features(m, self.seed.wrapping_add(1 + t as u64));
223            tree.fit_subset(x, labels, &sample, classes);
224            for i in (0..n).filter(|&i| !in_bag[i]) {
225                let d = tree.distribution(&x.row(i).to_vec());
226                oob_votes[i].iter_mut().zip(d).for_each(|(v, p)| *v += p);
227                oob_seen[i] = true;
228            }
229            self.forest.push(tree);
230        }
231        // ANCHOR_END: forest
232        self.classes = classes;
233        self.oob_accuracy = oob_seen.iter().all(|&s| s).then(|| (0..n).filter(|&i| argmax(&oob_votes[i]) == Some(labels[i])).count() as f64 / n as f64);
234        let mut counts = vec![0.0; p];
235        self.forest.iter().filter_map(|t| t.root.as_ref()).for_each(|r| count_splits(r, &mut counts));
236        let total: f64 = counts.iter().sum();
237        self.importances = counts.iter().map(|c| if total > 0.0 { c / total } else { 0.0 }).collect();
238        Ok(())
239    }
240
241    fn predict(&self, x: VR2D) -> Result<Vec<usize>, ErrorsJSL> {
242        Ok(self.predict_proba(x)?.rows().into_iter().map(|r| argmax(&r.to_vec()).unwrap_or(0)).collect())
243    }
244}
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249    use crate::datasets::{make_classification, make_moons};
250    use crate::metrics::accuracy;
251    use crate::preprocessing::{select_labels, select_rows, train_test_split};
252    use ndarray::arr2;
253
254    #[test]
255    fn a_tree_learns_axis_aligned_rules_exactly() {
256        // XOR on a grid: class = (x0 > 0) xor (x1 > 0). No single axis split separates it, but a
257        // depth-limited tree still builds it from two levels of splits.
258        let pts: Vec<(f64, f64)> = (-4..=4).filter(|&v| v != 0).flat_map(|i| (-4..=4).filter(|&v| v != 0).map(move |j| (i as f64 - 0.3, j as f64 + 0.2))).collect();
259        let x = R2D::from_shape_fn((pts.len(), 2), |(i, j)| if j == 0 { pts[i].0 } else { pts[i].1 });
260        let l: Vec<usize> = pts.iter().map(|&(a, b)| usize::from((a > 0.0) != (b > 0.0))).collect();
261        let mut t = DecisionTree::new(8);
262        t.fit(x.view(), &l).unwrap();
263        assert_eq!(t.predict(x.view()).unwrap(), l);
264        assert!(t.depth() >= 2);
265        let mut stump = DecisionTree::new(1);
266        stump.fit(x.view(), &l).unwrap();
267        assert_eq!(stump.depth(), 1);
268        assert!(accuracy(&l, &stump.predict(x.view()).unwrap()).unwrap() < 1.0);
269    }
270
271    #[test]
272    fn forest_generalises_better_than_one_deep_tree_and_reports_oob() {
273        let (x, l) = make_moons(200, 0.3, 4);
274        let (tr, te) = train_test_split(x.nrows(), 0.3, 3).unwrap();
275        let (xtr, ltr) = (select_rows(x.view(), &tr), select_labels(&l, &tr));
276        let (xte, lte) = (select_rows(x.view(), &te), select_labels(&l, &te));
277        let mut tree = DecisionTree::new(30);
278        tree.fit(xtr.view(), &ltr).unwrap();
279        let mut forest = RandomForest::new(60, 30, 5);
280        forest.fit(xtr.view(), &ltr).unwrap();
281        let (a_tree, a_forest) = (accuracy(&lte, &tree.predict(xte.view()).unwrap()).unwrap(), accuracy(&lte, &forest.predict(xte.view()).unwrap()).unwrap());
282        assert!(a_forest >= a_tree && a_forest > 0.85, "{a_tree} {a_forest}");
283        let oob = forest.oob_accuracy().unwrap();
284        assert!((oob - a_forest).abs() < 0.1, "oob {oob} vs test {a_forest}");
285        let p = forest.predict_proba(xte.view()).unwrap();
286        assert!(p.rows().into_iter().all(|r| (r.sum() - 1.0).abs() < 1e-12));
287    }
288
289    #[test]
290    fn feature_importance_finds_the_informative_features() {
291        // Feature 0 determines the class; features 1-3 are noise.
292        let (x, _) = make_classification(100, 2);
293        let l: Vec<usize> = (0..x.nrows()).map(|i| usize::from(x[[i, 0]] > 0.5)).collect();
294        let mut f = RandomForest::new(40, 6, 1).with_max_features(4);
295        f.fit(x.view(), &l).unwrap();
296        let imp = f.feature_importances();
297        assert!((imp.iter().sum::<f64>() - 1.0).abs() < 1e-9);
298        assert!(imp[0] > imp[1] && imp[0] > imp[2] && imp[0] > imp[3], "{imp:?}");
299        // Same seed, same forest.
300        let mut g = RandomForest::new(40, 6, 1).with_max_features(4);
301        g.fit(x.view(), &l).unwrap();
302        assert_eq!(f.predict(x.view()).unwrap(), g.predict(x.view()).unwrap());
303    }
304
305    #[test]
306    fn errors() {
307        let x = arr2(&[[0.0], [1.0]]);
308        assert!(RandomForest::new(0, 3, 1).fit(x.view(), &[0, 1]).is_err());
309        assert!(RandomForest::new(3, 3, 1).predict(x.view()).is_err());
310        assert!(DecisionTree::new(3).predict(x.view()).is_err());
311        let mut t = DecisionTree::new(3);
312        t.fit(x.view(), &[0, 1]).unwrap();
313        assert!(t.predict(arr2(&[[1.0, 2.0]]).view()).is_err());
314    }
315}