Gradient Boosting

Build a strong model by adding small trees that correct the mistakes left behind.

The Problem

Random Forest solved an important weakness of decision trees. A single tree was unstable, so Random Forest averaged many trees to make the final prediction more reliable.

But the trees in a Random Forest are trained independently. They receive different bootstrap samples, make their own predictions, and vote equally. They never talk to each other.

This raises a natural question. Instead of asking many independent trees for their opinions, what if every new tree focused specifically on the mistakes made by the previous trees?

Gradient Boosting turns an ensemble from a vote into a sequence of corrections.

Core Intuition

Imagine predicting whether Jessie will order a burger. The first tree learns a simple rule:

Hungry?
  yes -> Burger
  no  -> No Burger

It gets some visits wrong. Maybe it predicts burger when Jessie is trying to diet. Gradient Boosting does not throw the tree away. It asks what the tree failed to explain.

Tree 1: learns the broad pattern
Tree 2: corrects dieting mistakes
Tree 3: corrects special restaurant cravings
Tree 4: corrects the remaining edge cases

Every new tree is a specialist. It does not learn the whole problem from scratch. It learns the remaining error of the current ensemble.

That is the key difference from Random Forest. Random Forest asks what everyone thinks. Gradient Boosting asks what mistake it should fix next.

Interactive Demo

Boosting residual lab
ExampleSignalTargetPredictionResidual
Visit 1Hungry8.58.0
0.5
Visit 2Friends ordering7.27.2
-0.0
Visit 3Dieting2.43.6
-1.2
Visit 4Truffle fries9.18.4
0.7
Visit 5Late dinner3.14.0
-0.9
Visit 6Weekend6.86.9
-0.1
Training loss by round0.48
0
1
2
3
Current ensemble
3 trees

The model starts at the mean target, 6.2. Each round fits a shallow tree to the residuals and adds a small correction.

F_m(x) = F_{m-1}(x) + eta h_m(x)

A larger learning rate moves faster. Deeper trees can fit more complicated residual patterns, but they also make overfitting easier.

Watch the residuals shrink as boosting rounds increase. The model does not replace earlier trees. It adds corrections to what the ensemble already predicts.

Mathematics

Gradient Boosting also has two stories: the computations performed by the algorithm, and the optimization idea that explains the word gradient.

The Algorithm

Suppose the training set is D={(x1,y1),,(xn,yn)}D=\{(x_1,y_1),\ldots,(x_n,y_n)\}. The prediction after mm trees is Fm(x)F_m(x). For regression, we usually start with the mean target value:

F0(x)=yˉF_0(x)=\bar y

First compute the residual for every training example. The residual is what the current model still fails to explain.

ri=yiF0(xi)r_i=y_i-F_0(x_i)

A positive residual means the prediction was too small. A negative residual means the prediction was too large.

Next, train a shallow decision tree on the residuals, not on the original targets. If that tree is h1(x)h_1(x), it is learning a correction.

Then add the correction to the existing model:

F1(x)=F0(x)+ηh1(x)F_1(x)=F_0(x)+\eta h_1(x)

The learning rate η\eta controls how much we trust each new tree. Smaller values make learning slower but often more stable.

The general update is:

Fm(x)=Fm1(x)+ηhm(x)F_m(x)=F_{m-1}(x)+\eta h_m(x)

After each update, compute new residuals, fit a new tree, and add another correction. The model is additive: every tree remains part of the final prediction.

Worked Example

Suppose the first tree predicts Jessie correctly on two visits but misses three. Instead of relearning everything, the second tree focuses on the missed visits. If only one hard case remains, the third tree spends most of its capacity explaining that remaining error.

RoundModel focusWhat improves
Tree 1Broad burger patternCaptures the obvious hungry visits
Tree 2Dieting residualsFixes cases where hunger was misleading
Tree 3Remaining cravingsCatches restaurant-specific exceptions

Why It Works

Random Forest mainly reduces variance by averaging many independent trees. Gradient Boosting mainly reduces bias by building a sequence of increasingly accurate models.

Each individual tree can be weak. It may be shallow and unable to represent the full pattern alone. But the ensemble can represent a complicated function because every tree adds another correction.

The word gradient comes from optimization. Suppose we want to minimize a loss function L(y,F(x))L(y,F(x)). The negative gradient tells us the direction that most rapidly decreases the loss.

For squared error, the negative gradient is exactly the residual:

LF=yF(x)-\frac{\partial L}{\partial F}=y-F(x)

For other losses, such as logistic loss, the residual is replaced by the negative gradient of that loss. Each new tree approximates the direction that most reduces the current loss.

Random Forest Versus Gradient Boosting

IdeaRandom ForestGradient Boosting
TreesTrained independentlyTrained sequentially
CombinationMajority vote or averagingAdditive corrections
Main effectReduces varianceReduces bias
ParallelismTrees can train in parallelEach tree depends on the previous model
OverfittingOften robust as trees increaseCan overfit if boosted too long

Complexity

If we build TT trees, training costs approximately:

O(T×Tree Training Cost)O(T\times\text{Tree Training Cost})

Unlike Random Forest, the trees cannot be trained independently because tree mm depends on the residuals left by the previous ensemble. Prediction also grows linearly with the number of trees because every tree contributes to the final prediction.

Implementation

This basic version implements Gradient Boosting for regression. It starts with the mean target, repeatedly fits shallow trees to residuals, and adds each correction with a learning rate.

import numpy as np

class GradientBoostingRegressor:
    def __init__(self, n_estimators=100, learning_rate=0.1, max_depth=2):
        self.n_estimators = n_estimators
        self.learning_rate = learning_rate
        self.max_depth = max_depth
        self.initial_prediction = 0.0
        self.trees = []

    def fit(self, X, y):
        self.initial_prediction = np.mean(y)
        predictions = np.full(len(y), self.initial_prediction)
        self.trees = []

        for _ in range(self.n_estimators):
            residuals = y - predictions

            tree = DecisionTreeRegressor(max_depth=self.max_depth)
            tree.fit(X, residuals)
            correction = tree.predict(X)

            predictions += self.learning_rate * correction
            self.trees.append(tree)

        return self

    def predict(self, X):
        predictions = np.full(X.shape[0], self.initial_prediction)

        for tree in self.trees:
            predictions += self.learning_rate * tree.predict(X)

        return predictions

Libraries such as XGBoost, LightGBM, and CatBoost build on this core idea with stronger split finding, regularization, missing-value handling, categorical features, and systems-level optimizations.

Interview Discussion

What is the difference between bagging and boosting?

Bagging trains models independently and combines them. Boosting trains models sequentially so each new model focuses on the mistakes left by the current ensemble.

Why is Gradient Boosting sequential?

Each tree is trained on residuals or negative gradients computed from the current ensemble, so it cannot be trained before the previous trees exist.

What does the learning rate control?

It scales each tree's correction. Lower learning rates usually require more trees but can improve generalization.

Why is it called Gradient Boosting?

Each new tree approximates the negative gradient of the loss with respect to the current predictions. For squared error, that negative gradient is the residual.

Why can boosting overfit?

If the sequence keeps fitting tiny remaining errors for too long, it can start modeling noise. Depth, learning rate, number of trees, and regularization control this.

Active Recall

1. Explain Gradient Boosting without mentioning equations.

2. Why are residuals computed after every tree?

3. Why are trees added rather than replaced?

4. Why does Random Forest reduce variance while Gradient Boosting reduces bias?

5. Explain where the word gradient comes from.

Common Mistakes

  • Thinking every tree predicts the original target.
  • Confusing boosting with bagging.
  • Assuming boosting mainly reduces variance.
  • Forgetting that trees are trained sequentially.
  • Using too many boosting rounds without regularization.

Connection To Support Vector Machines

Random Forest improved decision trees by averaging many independent models. Gradient Boosting improves decision trees by allowing every new model to learn from the mistakes of the previous ones. One reduces variance through voting. The other reduces bias through iterative correction.