You fit a simple model to a curve, and the errors show a pattern it has missed. One useful next step is to fit another small model to those errors and add its prediction to the first. Repeating that process lets modest pieces gradually describe a more complicated relationship. Gradient boosting builds on this idea, giving each new model work that the current prediction still leaves undone.
The ensemble survey introduced boosting alongside other ways to combine models. Here we can slow down its loop and watch a curve take shape, one addition at a time. Following the remaining errors makes the training procedure easier to understand before we connect it to gradient descent and the objective used by XGBoost.
By the end you will be able to implement gradient boosting from scratch, explain the shrinkage and early-stopping knobs that keep it from overfitting, and read the XGBoost objective and understand exactly what each term buys. The starting point is the picture every boosting tutorial should lead with: the errors getting smaller.
Let's Build It
Click the badge to open the interactive notebook:
Here is the entire idea in one animation. The top panel shows the ensemble's prediction (red) against the true function (dashed) as we add stumps one at a time. The bottom panel shows what each new stump is actually trained on: the residuals, the leftover errors of the model so far. Watch the red curve sharpen as the blue residual cloud collapses onto zero.

Round 1 is a single flat step that barely moves off the mean. By round 60 the red staircase hugs the curve and the residuals are a tight band around zero, with nothing left for the next stump to fit. Each tree is still a depth-1 stump; the power is entirely in the accumulation.
from sklearn.tree import DecisionTreeRegressor
import numpy as np
class GradientBoost:
"""Squared-loss gradient boosting: each tree fits the residuals."""
def __init__(self, n_rounds=60, lr=0.3, max_depth=1):
self.n_rounds, self.lr, self.max_depth = n_rounds, lr, max_depth
def fit(self, X, y):
self.f0 = float(np.mean(y)) # start from the mean
F = np.full(len(y), self.f0)
self.trees = []
for m in range(self.n_rounds):
residual = y - F # what the model still gets wrong
tree = DecisionTreeRegressor(max_depth=self.max_depth, random_state=m)
tree.fit(X, residual) # fit a weak learner to the errors
F = F + self.lr * tree.predict(X) # add it on, shrunk by the learning rate
self.trees.append(tree)
return self
def predict(self, X):
F = np.full(X.shape[0], self.f0)
for tree in self.trees:
F = F + self.lr * tree.predict(X)
return F
That is gradient boosting in its entirety. Start from a constant, compute residuals, fit a tree to them, add a shrunk version of that tree, repeat. Everything else (the loss functions, the second-order tricks, the regularisation) is a refinement of this loop.
What Just Happened?
A weak learner, made strong
The word "boosting" comes from a precise theoretical question. In the late 1980s Kearns and Valiant asked: is a weak learner, one that does only slightly better than a coin flip, enough to build a strong learner that can be made arbitrarily accurate? It was not obvious that the answer should be yes. Schapire (1990) proved that it is, and the constructive proof was the first boosting algorithm. The staircase you just watched is that theorem in action: each stump is weak (it beats predicting the mean, but only just), and their sum is strong.
The accumulation is the key. A single stump has high bias; it cannot represent a curve. Adding stumps trained on residuals drives the bias down round after round, because every round attacks exactly the part of the target the current model has not captured yet. This is the opposite of bagging, which averages independent high-variance trees to cut variance. Boosting reduces bias by building dependence in on purpose.
Residuals are the negative gradient
The phrase "fit the residuals" hides something deeper. Consider squared-error loss for a single point, . Differentiate with respect to the model's current prediction :
The residual is the negative gradient of the loss with respect to the prediction. So when each tree fits the residuals, it is fitting the negative gradient, and adding it on is a step of gradient descent. The twist, due to Friedman, is that the descent happens in function space: instead of nudging a fixed set of parameters, each round adds a whole new function (a tree) pointing in the steepest-descent direction. This is the same gradient-descent logic behind SGD, momentum, and Adam, lifted from updating weights to growing an ensemble.
Framing it as a gradient unlocks the generality. For squared loss the gradient is the residual, but for any differentiable loss you can fit the trees to its negative gradient instead. Absolute-error loss gives the sign of the residual (robust to outliers); the logistic loss gives a probability gap for classification. The residual loop is just the squared-loss special case of a single recipe.
Going Deeper
The additive model and the two knobs
Formally, gradient boosting builds an additive model one term at a time:
is the weak learner fit to the negative gradient, and is the learning rate (or shrinkage). It scales down each tree's contribution so no single round dominates. The two knobs that matter most are and the number of rounds , and they trade off against each other.

The left panel is the warning every boosting practitioner learns. Training error falls forever, because more trees can always memorise more of the training set. Test error does not: it bottoms out (here around round 20) and then climbs as the ensemble starts fitting noise. Boosting overfits if you let it run too long, which is why early stopping on a validation set is standard practice.
The right panel shows what shrinkage buys. A learning rate of 1.0 (no shrinkage) overfits fastest and lands at the worst test error. Smaller rates descend more slowly but reach lower minima, because each tiny step is less likely to overshoot into noise. The standard recipe is a small learning rate (0.01 to 0.1) plus as many rounds as early stopping allows. It is the same stability-through-small-steps logic as learning-rate scheduling in neural networks, and tuning the pair well is exactly the kind of search the hyperparameter optimisation post is built for.

XGBoost: the same loop, a better objective
Everything so far uses only the first derivative of the loss. XGBoost, the library that made gradient boosting the default tool for tabular data, keeps the residual loop but upgrades the objective in two ways: it adds explicit regularisation, and it uses the second derivative as well as the first.
Start with the regularised objective. XGBoost minimises
where is the number of leaves in a tree and are the leaf values. The term charges a price per leaf (discouraging complex trees) and the term is an L2 penalty on leaf weights. Regularisation is baked into the model definition, not bolted on afterwards.
Now the second-order part. At round , expand the loss to second order around the current prediction using the per-example gradient and Hessian :
For a fixed tree structure, this is a quadratic in each leaf's weight, so the optimal weight has a closed form, and plugging it back gives a score for how good that structure is:
That second expression is the "structure score". XGBoost uses it directly to decide splits: the gain of a candidate split is the structure score of the two children minus the parent, minus . A split that does not improve the regularised score by at least is not made. The Hessian acts as a per-example weight, so points the loss is more curved around count for more, which connects straight to the curvature story in the backprop post: the Hessian tells you how confident to be in each step.
For plain squared-error loss the Hessian is 1 everywhere, so XGBoost's leaf weight reduces to a regularised mean of the residuals and the advantage over first-order boosting is modest. The second-order machinery earns its keep on losses where the curvature varies, like logistic loss for classification, and the regularisation earns its keep on noisy, high-dimensional data. On a standard Friedman benchmark, the same depth and learning rate, XGBoost edges out a from-scratch first-order booster:

The two curves nearly overlap, and that is the honest picture: at small scale, with matched settings, XGBoost's edge is real but small. Its decisive advantages show up on larger datasets, under heavy hyperparameter tuning, and on losses where second-order information matters. The core loop, fit the negative gradient and add it on, is identical to the twelve-line version above.
When boosting is the wrong tool
Boosting is not always the answer. It is sequential, so it is harder to parallelise than bagging or a random forest, where each tree is independent. It is sensitive to noisy labels, because it keeps directing capacity at the points it gets wrong, and a mislabelled point is one it can never get right. And on small or very clean datasets the extra rounds buy little over a well-tuned random forest, which needs far less tuning. The general rule from the ensemble survey still holds: reach for a random forest when you want a strong baseline with no tuning, and for gradient boosting when you want the top of the leaderboard and are willing to tune for it.
Where This Comes From
Boosting has an unusually clean intellectual lineage, from a theoretical question to the most-used tabular library in production.
Kearns and Valiant (1988, 1989) posed the hypothesis-boosting question: can a learner that is only slightly better than random be boosted into one that is arbitrarily accurate?
Schapire (1990), "The Strength of Weak Learnability", answered yes, with a constructive procedure that was the first boosting algorithm. Weak and strong learnability are equivalent.
"A model of learnability... in which the concept is required to be learned only slightly better than guessing is shown to be equivalent to the standard model, in which the concept must be learned with arbitrarily high accuracy." (Schapire, 1990)
Freund and Schapire (1997) turned the theory into AdaBoost, the practical re-weighting algorithm covered in the ensemble survey, and won the 2003 Gödel Prize for it.
Friedman (2001), "Greedy Function Approximation: A Gradient Boosting Machine", is the paper this post is built on. Friedman recast boosting as gradient descent in function space: each round fits a weak learner to the negative gradient of any differentiable loss, which for squared error is exactly the residual. His follow-up, "Stochastic Gradient Boosting" (2002), added row subsampling per round, the boosting analogue of mini-batching, which both regularises and speeds up training.
Chen and Guestrin (2016), "XGBoost: A Scalable Tree Boosting System", is the engineering capstone. The contribution was not a new learning principle but a better objective and a faster system: the second-order Taylor expansion, regularisation in the split criterion, sparsity-aware split finding, and cache-efficient histogram building. It is the reason gradient boosting is a one-line import today.
The throughline from 1990 to 2016 is a single idea getting sharper: combine many weak rules, each correcting the last. Schapire proved it was possible, Friedman showed it was gradient descent, and Chen and Guestrin made it fast enough to win every tabular leaderboard.
Further Reading
- Schapire (1990), "The Strength of Weak Learnability": the theorem that started boosting
- Friedman (2001), "Greedy Function Approximation: A Gradient Boosting Machine": gradient boosting as function-space descent
- Friedman, Hastie, Tibshirani (2000), "Additive Logistic Regression": the statistical view that links AdaBoost to gradient boosting
- Chen and Guestrin (2016), "XGBoost: A Scalable Tree Boosting System": the regularised, second-order, production-grade version
Interactive Tools
- Overfitting Explorer: Watch the train-test gap open as model complexity grows; the same U-shaped test curve that early stopping cuts off in boosting
- Regression Playground: Fit linear and regularised regression as a baseline; if a straight line wins, you do not need a boosted ensemble
- Classification Metrics Calculator: Turn a boosted classifier's outputs into precision, recall, and F1 once you switch from squared to logistic loss
Related Posts
- Stacking and Ensemble Methods in Python: The survey this post expands on; where boosting sits next to bagging, stacking, and mixture of experts
- Backprop, Jacobians, Hessians: Why First-Order Wins: The gradient and Hessian that XGBoost's second-order objective is built from
- SGD, Momentum, and Adam: Optimisers from First Principles: Gradient descent on weights; gradient boosting is the same idea on functions
- Learning Rate Scheduling: From Step Decay to One-Cycle: The shrinkage knob in boosting is a learning rate, with the same stability trade-off
- Hyperparameter Optimization: Grid vs Random vs Bayesian: How to tune the learning rate, depth, and number of rounds that decide whether boosting overfits
- Random Forests from Scratch: Bagging and OOB Error: Bagging-based ensembles vs boosting
- Tabular Foundation Models: How TabPFN Predicts Without Training: TabPFN versus the gradient-boosting champion on tabular benchmarks
- SMOTE vs Class Weights: Imbalanced Classification: Boosted trees often face skewed labels; this post covers the resampling and weighting fixes that keep the minority class from being ignored
- AIC and BIC: Model Selection Without Overfitting: Where information criteria fit for parametric models; boosted trees instead control complexity by early stopping on held-out error rather than an AIC or BIC penalty
- Conformal Prediction: 90% Coverage, 29% Where It Counts: Quantile-loss gradient boosting turned into intervals with guaranteed average coverage by conformalised quantile regression










