Gradient boosting
| Problem | Build an accurate predictor as a sum of many small regression trees, each fitted to the errors of the sum so far |
| Devised by | Robert Schapire (1990) and Yoav Freund and Schapire (1997), boosting and AdaBoost; Leo Breiman (1997), boosting as gradient descent; Jerome Friedman (2001), gradient boosting machines, and (2002), stochastic gradient boosting; Tianqi Chen and Carlos Guestrin (2016), XGBoost |
| Accuracy | Training loss decreases at every stage; test error is controlled by the learning rate, tree depth, subsampling and the number of stages |
| Cost | Each tree for depth (a sort per feature per level); trees per stage for classes |
| Read first | Decision trees and random forests |
| API | GradientBoostingRegressor (feature_importances, training_loss), GradientBoostingClassifier (predict_proba, training_loss), BoostingParameters (stages, learning_rate, max_depth, min_samples_leaf, subsample, seed), RegressionTree |
Overview
A random forest averages deep trees grown independently. Boosting does the opposite: it grows shallow trees one after another, each correcting what the previous ones got wrong. Gradient boosting makes this precise. At each stage it computes the gradient of the loss with respect to the current predictions, fits a small regression tree to the negative gradient, and adds a fraction of that tree to the model. It is gradient descent in the space of functions, with trees as steps. For squared error the negative gradient is just the residual, so each tree fits what is left to explain. Gradient-boosted trees, in implementations such as XGBoost and LightGBM, are the most successful general method for tabular data.
Where it is used
Gradient boosting is among the most accurate methods on tabular data.
- Business and engineering analytics. Predicting credit risk, customer churn, equipment failure and demand from many measured features, often winning data-science competitions.
- Web search and ranking. Learning-to-rank systems are boosted trees.
- Physics and sensing. Particle identification in high-energy physics, and classification of sensor signals.
- Practical qualities. Handles mixed feature types and missing values and needs little preprocessing.
History
Michael Kearns and Leslie Valiant (1988) asked whether “weak” learners, slightly better than guessing, could be combined into a strong one. Robert Schapire (1990) proved they could, and Yoav Freund and Schapire’s AdaBoost (1997) made it practical by reweighting misclassified examples. Leo Breiman (1997) and Jerome Friedman, Trevor Hastie and Robert Tibshirani (2000) showed that AdaBoost minimises an exponential loss stage by stage. Friedman (2001) generalised this to any differentiable loss as gradient boosting, with shrinkage and Newton steps in the leaves, and (2002) added row subsampling. Tianqi Chen and Carlos Guestrin’s XGBoost (2016), Microsoft’s LightGBM (2017) and Yandex’s CatBoost (2017) added second-order splits, histograms and careful engineering, and dominate machine-learning competitions on tabular data.
The idea
Functional gradient descent
Boosting by fitting residuals. Start with the simplest possible model for a regression problem, a constant equal to the mean of the targets. It is wrong at every training point by a residual . Fit a small regression tree to those residuals: it captures the largest pattern in what the constant missed. Add it to the model, compute the new residuals, fit another tree to them, and continue. Each tree corrects the errors of the sum of its predecessors. The final model is an additive expansion
where each is a small tree. The factor , the learning rate, adds only a fraction of each tree, so that no single tree is trusted too much.
The connection with gradient descent. For the squared-error loss , the derivative of the loss with respect to the prediction is . The residual is therefore the negative gradient of the loss with respect to the model’s prediction at that point. Adding a tree that approximates the residuals moves the predictions at all the training points a step in the direction of steepest descent. Boosting is gradient descent, not on a vector of parameters, but on the function itself.
This observation, due to Friedman, generalises the method to any differentiable loss. At stage :
- compute the pseudo-residuals , evaluated at the current prediction ;
- fit a regression tree to the pseudo-residuals by least squares;
- add to the model.
For squared error the pseudo-residuals are the ordinary residuals, and the description above is recovered. For other losses, such as the cross-entropy used for classification, they are whatever the gradient says would reduce the loss fastest.
Figure 13.3. Boosting a sine.
One depth-2 tree, scaled by , barely moves from the mean. Ten stages capture the shape coarsely, and a hundred follow the sine as a fine staircase.
Newton steps in the leaves
A regression tree does two things: it divides the points into groups (its leaves), and it assigns a value to each group. Fitting the tree to the pseudo-residuals by least squares is a good way to find the groups. But the least-squares leaf value, the mean pseudo-residual, is only the best value for the squared-error loss. For another loss, the value can be chosen to reduce that loss as much as possible for the points in the leaf.
One step of Newton’s method on the loss, restricted to the points of a leaf and to a single unknown , the leaf’s value, gives
where is the negative gradient (the pseudo-residual) and the second derivative of the loss at point . For squared error , and is the mean residual as before.
For classification with classes the model keeps one score per class, converts the scores to probabilities by a softmax, and minimises the cross-entropy (the multinomial deviance). The pseudo-residual for class is , where is 1 if point belongs to class and 0 otherwise: the familiar prediction error. Each stage fits one tree per class to these, with leaf values . (Friedman’s factor allows for the fact that the softmax has one redundant degree of freedom: adding a constant to all the scores changes nothing.)
Figure 13.4. Gradient boosting on moons.
The boundary is built from axis-parallel pieces, like a tree’s, but a hundred small trees give it far more resolution than one deep tree.
Shrinkage and the number of stages
The learning rate and the number of stages trade off. A small needs more stages but generalises better, a regularisation effect Friedman found empirically, related to the lasso’s path. On a nonlinear regression problem with 300 training points:
Figure 13.5. Test error against stages.
| learning rate ν | best test MSE | at stages | test MSE at 1000 stages |
|---|---|---|---|
| 1 | 17.19 | 10 | 18.93 |
| 0.3 | 9.92 | 150 | 9.94 |
| 0.1 | 7.24 | 1000 | 7.24 |
| 0.03 | 7.47 | 1000 | 7.47 |
With the test error bottoms out after 10 stages, then rises as the trees fit noise. With it keeps improving to 1000 stages and ends far lower. With , 1000 stages are not yet enough. In practice one sets a small and chooses the number of stages by cross-validation or a held-out set.
Stochastic gradient boosting
Fitting each tree to a random fraction of the rows (subsample) both speeds training up and, by decorrelating the trees, reduces
overfitting:
Table 13.4. Effect of row subsampling on gradient boosting.
| subsample (300 stages, ν = 0.1) | test MSE (mean of 5 seeds) |
|---|---|
| 1 | 7.35 |
| 0.8 | 6.61 |
| 0.5 | 6.43 |
| 0.2 | 6.63 |
Half the rows per tree gives the lowest error here. With subsampling the training loss is no longer guaranteed to fall at every stage.
Algorithm
Training, with stages, learning rate , tree depth and subsample fraction .
-
Initial model. Set to the mean of the targets (regression), or, for classification, set one score per class to the smoothed logarithm of the class’s share of the training data.
-
For each stage :
- subsample: if , draw a random fraction of the rows for this stage;
- derivatives: at the current predictions, compute for each row the pseudo-residual and the second derivative of the loss;
- grow a tree of depth at most on the subsample, with the pseudo-residuals as targets, choosing at each node the split that most reduces their squared error;
- set the leaf values: replace the value of each leaf by its Newton step, the sum of the pseudo-residuals of its rows divided by the sum of their second derivatives;
- update: add times the tree’s prediction to the model’s prediction for every row, including those not in the subsample.
For classification with classes, the last four steps are carried out once for each class, giving trees per stage.
-
Feature importances. Add up, over all the splits in all the trees, the reduction in squared error that each split achieved, grouped by the feature it used; divide by the total so that the importances sum to one.
Prediction: add and times the prediction of every tree. For classification, apply the softmax to the scores.
Implementation
for _ in 0..p.stages {
let residual: Vec<f64> = (0..n).map(|i| y[i] - prediction[i]).collect();
let mut tree = RegressionTree::new(p.max_depth, p.min_samples_leaf);
tree.fit(&data, &residual, &ones, &p.sample(n, &mut rng), &mut self.importances);
for (i, row) in data.iter().enumerate() {
prediction[i] += p.learning_rate * tree.predict_row(row);
}
self.trees.push(tree);
self.training_loss.push((0..n).map(|i| (y[i] - prediction[i]).powi(2)).sum::<f64>() / n as f64);
}
for c in 0..k {
let residual: Vec<f64> = (0..n).map(|i| f64::from(u8::from(labels[i] == c)) - probabilities[i][c]).collect();
let hessian: Vec<f64> = (0..n).map(|i| probabilities[i][c] * (1.0 - probabilities[i][c])).collect();
let mut tree = RegressionTree::new(p.max_depth, p.min_samples_leaf);
tree.fit(&data, &residual, &hessian, &sample, &mut importances);
// Friedman's (K − 1)/K factor for the multinomial Newton step.
let factor = (k - 1) as f64 / k as f64;
for node in tree.nodes.iter_mut() {
if let Node::Leaf(v) = node {
*v = (*v * factor).clamp(-20.0, 20.0);
}
}
stage.push(tree);
}
- Split search sorts each feature at each node, per level. Histogram-based implementations bin the features once and are much faster on large data.
- Classification leaf values are clamped to ±20 to avoid overflow when a leaf is pure.
- Predictions check the number of features. (Before this chapter, a row with too few features panicked.)
In practice
//! Gradient boosting for regression and classification.
use lib_jsl_machine_learning::common::{Classifier, Regressor};
use lib_jsl_machine_learning::datasets::{make_classification, make_regression};
use lib_jsl_machine_learning::ensembles::{BoostingParameters, GradientBoostingClassifier, GradientBoostingRegressor};
use lib_jsl_machine_learning::metrics::{accuracy, r2_score};
use ndarray::s;
fn main() {
// Eight features, of which the target depends nonlinearly on the first three.
let (x, linear, _, _) = make_regression(600, 8, 1.0, 5);
let y = ndarray::Array1::from_iter((0..600).map(|i| linear[i] + 3.0 * x[[i, 0]] * x[[i, 1]] + 2.0 * x[[i, 2]].powi(2)));
let (train, test) = ((x.slice(s![..400, ..]), y.slice(s![..400])), (x.slice(s![400.., ..]), y.slice(s![400..])));
let mut gb = GradientBoostingRegressor::new(BoostingParameters { stages: 500, learning_rate: 0.05, max_depth: 3, subsample: 0.8, seed: 1, ..Default::default() });
gb.fit(train.0, train.1).unwrap();
println!("regression: test R² {:.3}", r2_score(test.1, gb.predict(test.0).unwrap().view()).unwrap());
let importances: Vec<String> = gb.feature_importances().iter().map(|v| format!("{v:.3}")).collect();
println!("feature importances [{}]", importances.join(", "));
let (cx, cl) = make_classification(150, 2);
let (tx, tl) = make_classification(300, 3);
let mut clf = GradientBoostingClassifier::new(BoostingParameters { stages: 150, max_depth: 2, ..Default::default() });
clf.fit(cx.view(), &cl).unwrap();
println!("classification: test accuracy {:.3}, training deviance {:.3} → {:.3}", accuracy(&tl, &clf.predict(tx.view()).unwrap()).unwrap(), clf.training_loss[0], clf.training_loss.last().unwrap());
}
regression: test R² 0.855
feature importances [0.087, 0.108, 0.323, 0.210, 0.012, 0.046, 0.012, 0.202]
classification: test accuracy 0.889, training deviance 0.973 → 0.050
Feature 2, which enters both linearly (coefficient −2.41) and quadratically, is the most important. Features 3 and 7 have the largest linear coefficients (−2.65 and −2.59); features 0 and 1 matter partly through their product, which trees can only approximate in pieces; features 4 and 6, with coefficients 0.16 and −0.24, are almost unused. The classifier drives its training deviance close to zero; the gap to its test accuracy is the usual warning that training loss says little about generalisation.
Strengths
- State-of-the-art accuracy on tabular data; handles mixed feature scales, interactions and missing structure with little preprocessing.
- Any differentiable loss; feature importances come for free.
Weaknesses
- Sequential: stages cannot be trained in parallel, and many settings need tuning (rate, stages, depth, subsampling).
- Can overfit with too many stages or too large a rate; piecewise-constant predictions do not extrapolate.
Exercises
- Show that the pseudo-residual of the squared loss is the residual, and that of the absolute loss is the sign of the residual.
- Derive the Newton leaf value for the binary logistic loss.
- Show that boosting depth-1 trees (stumps) gives an additive model with no interactions.
- Explain why the training loss of full-sample boosting with Newton leaves for squared error can never increase.
- Implement early stopping: hold out 20% of the training data and stop when its error has not improved for 20 stages.
Hints and answers
- For the negative gradient is . For it is .
- With the gradient is and the Hessian , so the Newton leaf value is .
- Each stump depends on a single feature, so the sum of stumps is with collecting the stumps on feature : no interaction terms.
- With squared loss the Newton leaf value is the mean residual, which exactly minimises the squared error in each leaf; a leaf value of 0 (no change) is always available, so the loss cannot increase.
- Track the validation loss after each stage and stop (returning to the best stage) once it has not improved for 20 consecutive stages.
Further reading
- J. H. Friedman, “Greedy function approximation: a gradient boosting machine”, Annals of Statistics 29 (2001) 1189–1232.
- J. H. Friedman, “Stochastic gradient boosting”, Computational Statistics and Data Analysis 38 (2002) 367–378.
- T. Chen and C. Guestrin, “XGBoost: a scalable tree boosting system”, Proceedings of the 22nd ACM SIGKDD Conference (2016) 785–794.
- T. Hastie, R. Tibshirani and J. Friedman, The Elements of Statistical Learning, 2nd ed., Springer, 2009, chapter 10.