Skip to main content

lib_jsl_machine_learning/
ensembles.rs

1//! Ensembles: gradient-boosted regression trees for regression and classification.
2//!
3//! Gradient boosting (Friedman) builds an additive model `F(x) = F₀ + ν Σ_m h_m(x)` stage by
4//! stage: each small regression tree `h_m` is fitted to the negative gradient of the loss at the
5//! current predictions, and its leaves take the Newton step `Σ(−g) / Σh` of the loss restricted to
6//! the leaf. The learning rate `ν` (shrinkage) and row subsampling (stochastic boosting)
7//! regularise the fit.
8//!
9//! See the book entry [Gradient boosting](https://jwkunz.github.io/lib_jsl/book/learning/gradient-boosting.html).
10
11use crate::common::{Classifier, MlRng, Regressor, check_xy, class_count, rows};
12use lib_jsl_core::{ErrorsJSL, R1D, R2D, VR1D, VR2D};
13
14#[derive(Debug, Clone)]
15enum Node {
16    Leaf(f64),
17    Split { feature: usize, threshold: f64, left: usize, right: usize },
18}
19
20/// A least-squares regression tree whose leaves hold Newton steps `Σr / Σw` (the mean residual
21/// when every weight is one).
22#[derive(Debug, Clone)]
23pub struct RegressionTree {
24    nodes: Vec<Node>,
25    max_depth: usize,
26    min_samples_leaf: usize,
27}
28
29impl RegressionTree {
30    pub fn new(max_depth: usize, min_samples_leaf: usize) -> Self {
31        RegressionTree { nodes: Vec::new(), max_depth, min_samples_leaf: min_samples_leaf.max(1) }
32    }
33
34    /// Fits the tree on rows `samples` of `x` to residuals `r` with Newton weights `w`; adds each
35    /// split's squared-error reduction to `importances`.
36    pub fn fit(&mut self, x: &[Vec<f64>], r: &[f64], w: &[f64], samples: &[usize], importances: &mut [f64]) {
37        self.nodes.clear();
38        self.grow(x, r, w, samples.to_vec(), 0, importances);
39    }
40
41    fn leaf_value(r: &[f64], w: &[f64], idx: &[usize]) -> f64 {
42        let (num, den) = idx.iter().fold((0.0, 0.0), |(a, b), &i| (a + r[i], b + w[i]));
43        if den > 1e-12 { num / den } else { 0.0 }
44    }
45
46    #[allow(clippy::needless_range_loop)]
47    fn grow(&mut self, x: &[Vec<f64>], r: &[f64], w: &[f64], idx: Vec<usize>, depth: usize, importances: &mut [f64]) -> usize {
48        let id = self.nodes.len();
49        self.nodes.push(Node::Leaf(Self::leaf_value(r, w, &idx)));
50        if depth >= self.max_depth || idx.len() < 2 * self.min_samples_leaf {
51            return id;
52        }
53        let n = idx.len() as f64;
54        let total: f64 = idx.iter().map(|&i| r[i]).sum();
55        let parent = total * total / n;
56        let mut best: Option<(f64, usize, f64)> = None;
57        let features = x[0].len();
58        let mut order = idx.clone();
59        for f in 0..features {
60            order.sort_by(|&a, &b| x[a][f].total_cmp(&x[b][f]));
61            let mut left_sum = 0.0;
62            for k in 0..order.len() - 1 {
63                left_sum += r[order[k]];
64                let (nl, nr) = ((k + 1) as f64, (order.len() - k - 1) as f64);
65                if k + 1 < self.min_samples_leaf || order.len() - k - 1 < self.min_samples_leaf || x[order[k]][f] == x[order[k + 1]][f] {
66                    continue;
67                }
68                // Reduction in the sum of squared residuals: S_L²/n_L + S_R²/n_R − S²/n.
69                let gain = left_sum * left_sum / nl + (total - left_sum).powi(2) / nr - parent;
70                if best.is_none_or(|(g, _, _)| gain > g) {
71                    best = Some((gain, f, 0.5 * (x[order[k]][f] + x[order[k + 1]][f])));
72                }
73            }
74        }
75        let Some((gain, feature, threshold)) = best else { return id };
76        if gain <= 1e-12 {
77            return id;
78        }
79        importances[feature] += gain;
80        let (left_idx, right_idx): (Vec<usize>, Vec<usize>) = idx.iter().partition(|&&i| x[i][feature] <= threshold);
81        let left = self.grow(x, r, w, left_idx, depth + 1, importances);
82        let right = self.grow(x, r, w, right_idx, depth + 1, importances);
83        self.nodes[id] = Node::Split { feature, threshold, left, right };
84        id
85    }
86
87    pub fn predict_row(&self, row: &[f64]) -> f64 {
88        let mut i = 0;
89        loop {
90            match self.nodes[i] {
91                Node::Leaf(v) => return v,
92                Node::Split { feature, threshold, left, right } => i = if row[feature] <= threshold { left } else { right },
93            }
94        }
95    }
96}
97
98/// Shared boosting settings.
99#[derive(Debug, Clone)]
100pub struct BoostingParameters {
101    pub stages: usize,
102    pub learning_rate: f64,
103    pub max_depth: usize,
104    pub min_samples_leaf: usize,
105    /// Fraction of rows used per stage (1 for deterministic boosting).
106    pub subsample: f64,
107    pub seed: u64,
108}
109
110impl Default for BoostingParameters {
111    fn default() -> Self {
112        BoostingParameters { stages: 200, learning_rate: 0.1, max_depth: 3, min_samples_leaf: 1, subsample: 1.0, seed: 0 }
113    }
114}
115
116impl BoostingParameters {
117    fn validate(&self) -> Result<(), ErrorsJSL> {
118        if self.stages == 0 || self.learning_rate.is_nan() || self.learning_rate <= 0.0 || !(0.0..=1.0).contains(&self.subsample) || self.subsample == 0.0 {
119            return Err(ErrorsJSL::InvalidInputRange("Need stages > 0, a positive learning rate and 0 < subsample <= 1."));
120        }
121        Ok(())
122    }
123
124    fn sample(&self, n: usize, rng: &mut MlRng) -> Vec<usize> {
125        if self.subsample >= 1.0 { (0..n).collect() } else { rng.sample_indices(n, ((self.subsample * n as f64).round() as usize).max(1)) }
126    }
127}
128
129/// Gradient boosting for regression with the squared-error loss.
130#[derive(Debug, Clone)]
131pub struct GradientBoostingRegressor {
132    pub parameters: BoostingParameters,
133    features: usize,
134    base: f64,
135    trees: Vec<RegressionTree>,
136    importances: Vec<f64>,
137    /// Training mean squared error after each stage.
138    pub training_loss: Vec<f64>,
139}
140
141impl GradientBoostingRegressor {
142    pub fn new(parameters: BoostingParameters) -> Self {
143        GradientBoostingRegressor { parameters, features: 0, base: 0.0, trees: Vec::new(), importances: Vec::new(), training_loss: Vec::new() }
144    }
145
146    /// Relative feature importances (normalised squared-error reductions).
147    pub fn feature_importances(&self) -> Vec<f64> {
148        let total: f64 = self.importances.iter().sum();
149        self.importances.iter().map(|v| if total > 0.0 { v / total } else { 0.0 }).collect()
150    }
151}
152
153impl Regressor for GradientBoostingRegressor {
154    fn fit(&mut self, x: VR2D, y: VR1D) -> Result<(), ErrorsJSL> {
155        check_xy(x, y.len())?;
156        self.parameters.validate()?;
157        let p = &self.parameters;
158        let data = rows(x);
159        let n = data.len();
160        self.features = x.ncols();
161        self.base = y.iter().sum::<f64>() / n as f64;
162        let mut prediction = vec![self.base; n];
163        let ones = vec![1.0; n];
164        let mut rng = MlRng::new(p.seed);
165        self.importances = vec![0.0; x.ncols()];
166        self.trees.clear();
167        self.training_loss.clear();
168        // ANCHOR: boost_regression
169        for _ in 0..p.stages {
170            let residual: Vec<f64> = (0..n).map(|i| y[i] - prediction[i]).collect();
171            let mut tree = RegressionTree::new(p.max_depth, p.min_samples_leaf);
172            tree.fit(&data, &residual, &ones, &p.sample(n, &mut rng), &mut self.importances);
173            for (i, row) in data.iter().enumerate() {
174                prediction[i] += p.learning_rate * tree.predict_row(row);
175            }
176            self.trees.push(tree);
177            self.training_loss.push((0..n).map(|i| (y[i] - prediction[i]).powi(2)).sum::<f64>() / n as f64);
178        }
179        // ANCHOR_END: boost_regression
180        Ok(())
181    }
182
183    fn predict(&self, x: VR2D) -> Result<R1D, ErrorsJSL> {
184        check_fitted(self.trees.is_empty(), self.features, x)?;
185        Ok(x.rows().into_iter().map(|row| {
186            let r = row.to_vec();
187            self.base + self.parameters.learning_rate * self.trees.iter().map(|t| t.predict_row(&r)).sum::<f64>()
188        }).collect())
189    }
190}
191
192/// Gradient boosting for classification with the multinomial deviance (softmax cross-entropy):
193/// one tree per class per stage, leaves taking the Newton step `Σ(y − p) / Σ p(1 − p)`.
194#[derive(Debug, Clone)]
195pub struct GradientBoostingClassifier {
196    pub parameters: BoostingParameters,
197    features: usize,
198    base: Vec<f64>,
199    trees: Vec<Vec<RegressionTree>>,
200    /// Mean training deviance (cross-entropy) after each stage.
201    pub training_loss: Vec<f64>,
202}
203
204/// Errors for an unfitted model or a feature count different from training.
205fn check_fitted(unfitted: bool, features: usize, x: VR2D) -> Result<(), ErrorsJSL> {
206    if unfitted {
207        return Err(ErrorsJSL::RuntimeError("The model has not been fitted."));
208    }
209    if x.ncols() != features {
210        return Err(ErrorsJSL::IncompatibleArraySizes((x.ncols(), features)));
211    }
212    Ok(())
213}
214
215fn softmax(scores: &[f64]) -> Vec<f64> {
216    let m = scores.iter().copied().fold(f64::NEG_INFINITY, f64::max);
217    let e: Vec<f64> = scores.iter().map(|s| (s - m).exp()).collect();
218    let z: f64 = e.iter().sum();
219    e.into_iter().map(|v| v / z).collect()
220}
221
222impl GradientBoostingClassifier {
223    pub fn new(parameters: BoostingParameters) -> Self {
224        GradientBoostingClassifier { parameters, features: 0, base: Vec::new(), trees: Vec::new(), training_loss: Vec::new() }
225    }
226
227    fn scores(&self, row: &[f64]) -> Vec<f64> {
228        let mut s = self.base.clone();
229        for stage in &self.trees {
230            for (k, tree) in stage.iter().enumerate() {
231                s[k] += self.parameters.learning_rate * tree.predict_row(row);
232            }
233        }
234        s
235    }
236
237    /// Class probabilities, one row per sample.
238    pub fn predict_proba(&self, x: VR2D) -> Result<R2D, ErrorsJSL> {
239        check_fitted(self.trees.is_empty(), self.features, x)?;
240        let k = self.base.len();
241        let mut out = R2D::zeros((x.nrows(), k));
242        for (i, row) in x.rows().into_iter().enumerate() {
243            for (c, p) in softmax(&self.scores(&row.to_vec())).into_iter().enumerate() {
244                out[[i, c]] = p;
245            }
246        }
247        Ok(out)
248    }
249}
250
251impl Classifier for GradientBoostingClassifier {
252    #[allow(clippy::needless_range_loop)]
253    fn fit(&mut self, x: VR2D, labels: &[usize]) -> Result<(), ErrorsJSL> {
254        check_xy(x, labels.len())?;
255        self.parameters.validate()?;
256        let p = self.parameters.clone();
257        let k = class_count(labels).max(2);
258        let data = rows(x);
259        let n = data.len();
260        self.features = x.ncols();
261        // Start from the log class priors (smoothed so absent classes stay finite).
262        self.base = (0..k).map(|c| ((labels.iter().filter(|&&l| l == c).count() as f64 + 0.5) / (n as f64 + 0.5 * k as f64)).ln()).collect();
263        let mut scores: Vec<Vec<f64>> = vec![self.base.clone(); n];
264        let mut rng = MlRng::new(p.seed);
265        let mut importances = vec![0.0; x.ncols()];
266        self.trees.clear();
267        self.training_loss.clear();
268        for _ in 0..p.stages {
269            let probabilities: Vec<Vec<f64>> = scores.iter().map(|s| softmax(s)).collect();
270            let sample = p.sample(n, &mut rng);
271            let mut stage = Vec::with_capacity(k);
272            // ANCHOR: boost_classification
273            for c in 0..k {
274                let residual: Vec<f64> = (0..n).map(|i| f64::from(u8::from(labels[i] == c)) - probabilities[i][c]).collect();
275                let hessian: Vec<f64> = (0..n).map(|i| probabilities[i][c] * (1.0 - probabilities[i][c])).collect();
276                let mut tree = RegressionTree::new(p.max_depth, p.min_samples_leaf);
277                tree.fit(&data, &residual, &hessian, &sample, &mut importances);
278                // Friedman's (K − 1)/K factor for the multinomial Newton step.
279                let factor = (k - 1) as f64 / k as f64;
280                for node in tree.nodes.iter_mut() {
281                    if let Node::Leaf(v) = node {
282                        *v = (*v * factor).clamp(-20.0, 20.0);
283                    }
284                }
285                stage.push(tree);
286            }
287            // ANCHOR_END: boost_classification
288            for (i, row) in data.iter().enumerate() {
289                for (c, tree) in stage.iter().enumerate() {
290                    scores[i][c] += p.learning_rate * tree.predict_row(row);
291                }
292            }
293            self.trees.push(stage);
294            self.training_loss.push(-(0..n).map(|i| softmax(&scores[i])[labels[i]].max(1e-300).ln()).sum::<f64>() / n as f64);
295        }
296        Ok(())
297    }
298
299    fn predict(&self, x: VR2D) -> Result<Vec<usize>, ErrorsJSL> {
300        let proba = self.predict_proba(x)?;
301        Ok(proba.rows().into_iter().map(|r| crate::common::argmax(&r.to_vec()).unwrap_or(0)).collect())
302    }
303}
304
305#[cfg(test)]
306mod tests {
307    use super::*;
308    use crate::datasets::{make_circles, make_moons, make_sine};
309    use crate::metrics::{accuracy, mean_squared_error};
310    use crate::preprocessing::train_test_split;
311    use ndarray::Axis;
312
313    #[test]
314    fn boosting_fits_a_sine_far_better_than_one_tree() {
315        let (x, y) = make_sine(400, 0.1, 1);
316        let (train, test) = train_test_split(400, 0.25, 2).unwrap();
317        let (xt, yt) = (x.select(Axis(0), &train), y.select(Axis(0), &train));
318        let (xs, ys) = (x.select(Axis(0), &test), y.select(Axis(0), &test));
319        let mut gb = GradientBoostingRegressor::new(BoostingParameters { stages: 300, learning_rate: 0.05, ..Default::default() });
320        gb.fit(xt.view(), yt.view()).unwrap();
321        let boosted = mean_squared_error(ys.view(), gb.predict(xs.view()).unwrap().view()).unwrap();
322        let mut stump = GradientBoostingRegressor::new(BoostingParameters { stages: 1, learning_rate: 1.0, ..Default::default() });
323        stump.fit(xt.view(), yt.view()).unwrap();
324        let single = mean_squared_error(ys.view(), stump.predict(xs.view()).unwrap().view()).unwrap();
325        // Compare the error above the noise floor (noise variance 0.01).
326        assert!(boosted < 0.02 && boosted - 0.01 < (single - 0.01) / 3.0, "boosted {boosted} single {single}");
327        // Training loss decreases monotonically for full-sample boosting.
328        assert!(gb.training_loss.windows(2).all(|w| w[1] <= w[0] + 1e-12));
329        assert!((gb.feature_importances().iter().sum::<f64>() - 1.0).abs() < 1e-12);
330    }
331
332    #[test]
333    fn boosted_classifiers_separate_nonlinear_classes() {
334        for (name, (x, labels)) in [("moons", make_moons(400, 0.15, 3)), ("circles", make_circles(400, 0.08, 0.5, 4))] {
335            let (train, test) = train_test_split(400, 0.25, 5).unwrap();
336            let lt: Vec<usize> = train.iter().map(|&i| labels[i]).collect();
337            let ls: Vec<usize> = test.iter().map(|&i| labels[i]).collect();
338            let mut gb = GradientBoostingClassifier::new(BoostingParameters { stages: 100, subsample: 0.8, seed: 6, ..Default::default() });
339            gb.fit(x.select(Axis(0), &train).view(), &lt).unwrap();
340            let predicted = gb.predict(x.select(Axis(0), &test).view()).unwrap();
341            assert!(accuracy(&ls, &predicted).unwrap() > 0.93, "{name}");
342            let proba = gb.predict_proba(x.select(Axis(0), &test).view()).unwrap();
343            assert!(proba.rows().into_iter().all(|r| (r.sum() - 1.0).abs() < 1e-12));
344            assert!(gb.training_loss.last().unwrap() < &gb.training_loss[0]);
345        }
346        let mut bad = GradientBoostingClassifier::new(BoostingParameters { learning_rate: 0.0, ..Default::default() });
347        let (x, l) = make_moons(20, 0.1, 1);
348        assert!(bad.fit(x.view(), &l).is_err());
349        // Predicting with the wrong number of features is an error, not a panic.
350        let mut gb = GradientBoostingClassifier::new(BoostingParameters { stages: 3, ..Default::default() });
351        gb.fit(x.view(), &l).unwrap();
352        assert!(gb.predict(R2D::zeros((2, 1)).view()).is_err());
353        let mut gr = GradientBoostingRegressor::new(BoostingParameters { stages: 3, ..Default::default() });
354        gr.fit(x.view(), x.column(0)).unwrap();
355        assert!(gr.predict(R2D::zeros((2, 3)).view()).is_err());
356    }
357}