Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Concept · 20 min · revision 2

Bagging vs Boosting: Two Ways to Combine Trees

Measure bias and variance for single trees, bagged trees, random forests and boosted stumps on a simulated problem, see how feature subsampling decorrelates the trees of a forest, and write gradient boosting by hand as a loop that fits each new tree to the residuals of the ensemble so far.

Contentsand lesson path

What you will learn

  • Explain how a decision tree chooses splits and why bagging (random forests) mainly reduces variance while boosting mainly reduces bias.

01. Why it matters

The previous lesson ended with two problems. A deep tree has high variance: its shape changes with every new sample. A shallow tree has high bias: it is too simple to follow the pattern. An ensemble combines many trees into one model, and the two big families fix one problem each. Bagging, and its best-known form the random forest, grows many deep trees independently and averages them, which mainly reduces variance. Boosting grows many shallow trees one after another, each correcting the ones before, which mainly reduces bias.

Knowing which problem each family attacks tells you how to set it up: how deep the trees should be, whether more trees can hurt, and what to tune. This lesson measures the effect on a simulated problem where the true function is known, then builds boosting by hand so that nothing about it is magic. You need scikit-learn 1.9 and NumPy 2.x. The scripts run in a few seconds each, except bias_variance.py, which fits 120 models and takes under half a minute on a laptop.

02. Bias and variance of four kinds of model

make_friedman1 generates a regression problem from a known non-linear formula of five features, plus five useless features and noise with a standard deviation of 1. Because the formula is known, you can do what real data does not allow: train each model on 20 independent training sets and compare its predictions with the truth at 500 fixed points. Bias² is how far the average prediction is from the truth. Variance is how much the 20 predictions spread around their average. The expected test MSE is bias² + variance + 1.0 (the noise variance, which no model can remove).

A bagged model draws a bootstrap sample for each tree, meaning n rows drawn with replacement from the n training rows, so each tree sees about 63% of the distinct rows, some of them twice. It grows a deep tree on each sample and averages their predictions. A random forest does the same and also restricts every split to a random subset of the features (max_features). In scikit-learn, RandomForestRegressor with max_features=1.0 (its default) is plain bagging; RandomForestClassifier defaults to the square root of the number of features.

Python · bias_variance.py
import numpy as np
from sklearn.datasets import make_friedman1
from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor
from sklearn.tree import DecisionTreeRegressor

X_grid, truth = make_friedman1(n_samples=500, noise=0.0, random_state=999)
models = {
    "one deep tree": lambda s: DecisionTreeRegressor(random_state=s),
    "bagged deep trees": lambda s: RandomForestRegressor(
        100, max_features=1.0, random_state=s, n_jobs=-1),
    "random forest": lambda s: RandomForestRegressor(
        100, max_features=0.3, random_state=s, n_jobs=-1),
    "one stump": lambda s: DecisionTreeRegressor(max_depth=1),
    "bagged stumps": lambda s: RandomForestRegressor(
        100, max_depth=1, max_features=1.0, random_state=s, n_jobs=-1),
    "boosted stumps": lambda s: GradientBoostingRegressor(
        n_estimators=300, max_depth=1, random_state=s),
}
print(f"{'model':<18} {'bias^2':>7} {'variance':>9} {'test MSE':>9}")
for name, make in models.items():
    preds = []
    for seed in range(20):                  # 20 independent training sets of 300 rows
        X, y = make_friedman1(n_samples=300, noise=1.0, random_state=seed)
        preds.append(make(seed).fit(X, y).predict(X_grid))
    preds = np.array(preds)
    bias_sq = np.mean((preds.mean(axis=0) - truth) ** 2)
    variance = np.mean(preds.var(axis=0))
    print(f"{name:<18} {bias_sq:7.2f} {variance:9.2f} {bias_sq + variance + 1.0:9.2f}")
Terminal
python bias_variance.py
Expected output
model               bias^2  variance  test MSE
one deep tree         3.41      7.93     12.33
bagged deep trees     3.65      1.11      5.76
random forest         4.66      0.69      6.35
one stump            16.12      1.32     18.44
bagged stumps        15.25      0.67     16.93
boosted stumps        2.45      0.69      4.14

Read the rows in pairs. One deep tree has a moderate bias² (3.41) and a large variance (7.93). Averaging 100 bagged copies keeps the bias about where it was (3.65) and cuts the variance by a factor of seven, to 1.11, so the test MSE falls from 12.33 to 5.76. The random forest cuts variance further (0.69) but pays with more bias (4.66): with only 30% of the features at each split, some splits must use a weaker feature. On this problem that trade does not pay; on the real data in the next section it does.

Stumps, trees with a single split, tell the opposite story. One stump is stable (variance 1.32) but badly biased (16.12), because one split cannot follow a five-feature formula. Bagging stumps lowers the variance a little and leaves the bias almost unchanged, since an average of many similar, simple models is still simple. Boosting 300 stumps brings the bias down to 2.45, the lowest in the table, and gives the best test MSE.

03. Why a forest restricts the features at each split

If B trees each have error variance σ² and the errors of any two trees have correlation ρ, the variance of their average is ρσ² + (1 − ρ)σ²/B. The second term shrinks as you add trees, but the first does not. So beyond a few hundred trees, adding more changes little, and the only way to cut the remaining variance is to make the trees less alike. When one feature is strong, every bagged tree tends to split on it first, and the trees end up similar. Hiding it from some splits forces other trees to find other routes. The script measures the average correlation between the test errors of 200 trees, on the diabetes data, for four values of max_features.

Python · decorrelation.py
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split

X, y = load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)

print("max_features  tree MSE  error corr  forest MSE")
for m in [1.0, 0.6, 0.3, 0.1]:
    forest = RandomForestRegressor(200, max_features=m, random_state=0, n_jobs=-1)
    forest.fit(X_train, y_train)
    errors = np.array([t.predict(X_test) for t in forest.estimators_]) - y_test
    corr = np.corrcoef(errors)[np.triu_indices(len(errors), k=1)].mean()
    forest_mse = np.mean((forest.predict(X_test) - y_test) ** 2)
    print(f"{m:12.1f} {np.mean(errors**2):9.0f} {corr:11.2f} {forest_mse:11.0f}")
Terminal
python decorrelation.py
Expected output
max_features  tree MSE  error corr  forest MSE
         1.0      6600        0.53        3492
         0.6      6700        0.52        3481
         0.3      6828        0.50        3385
         0.1      7471        0.44        3272

As max_features falls, each tree gets worse (its MSE rises from 6600 to 7471), but the errors of the trees become less correlated (0.53 to 0.44), and the forest as a whole improves from 3492 to 3385 at 0.3 and 3272 at 0.1. On the Friedman data in the previous section the same change made the forest worse. Neither result is a rule: max_features is a hyperparameter to choose with cross-validation, and the square root of the number of features is only a starting point. One more useful property: each tree skips about 37% of the rows, so the forest can score every row with the trees that did not see it. Setting oob_score=True gives this out-of-bag estimate without a separate validation set.

04. Boosting: each tree fixes what is left

Gradient boosting builds its prediction as a sum. It starts from a constant, the mean target, and then repeats one step: compute the residuals (the target minus the current prediction), fit a small tree to them, and add that tree times a learning rate, a number such as 0.1 that keeps each step small. Each tree is weak, but each one is aimed at the part of the error that the sum so far has not explained, which is why the bias keeps falling. The loop below is the whole algorithm for squared error.

Python · boosting_by_hand.py
import numpy as np
from sklearn.datasets import make_friedman1
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.tree import DecisionTreeRegressor

X, y = make_friedman1(n_samples=200, noise=2.0, random_state=0)
X_val, y_val = make_friedman1(n_samples=2000, noise=2.0, random_state=1)
lr, rounds = 0.1, 1000

pred, pred_val = np.full(len(y), y.mean()), np.full(len(y_val), y.mean())
print("round  train MSE  val MSE")
for m in range(1, rounds + 1):
    residual = y - pred                     # what the ensemble still gets wrong
    tree = DecisionTreeRegressor(max_depth=3, random_state=0).fit(X, residual)
    pred += lr * tree.predict(X)            # take a small step towards the residual
    pred_val += lr * tree.predict(X_val)
    if m in (1, 10, 50, 100, 200, 400, 1000):
        train_mse, val_mse = np.mean((y - pred)**2), np.mean((y_val - pred_val)**2)
        print(f"{m:5d} {train_mse:10.2f} {val_mse:8.2f}")

gbr = GradientBoostingRegressor(n_estimators=rounds, learning_rate=lr, max_depth=3,
                                random_state=0).fit(X, y)
print(f"GradientBoostingRegressor, same settings: val MSE "
      f"{np.mean((y_val - gbr.predict(X_val))**2):.2f}")
Terminal
python boosting_by_hand.py
Expected output
round  train MSE  val MSE
    1      28.05    24.70
   10      11.36    13.55
   50       1.47     8.24
  100       0.53     8.04
  200       0.12     8.11
  400       0.01     8.18
 1000       0.00     8.19
GradientBoostingRegressor, same settings: val MSE 8.15

Training MSE falls with every round and reaches 0.00 by round 1000: with 200 rows, depth-3 trees eventually fit every residual, noise included. Validation MSE falls quickly to about 8.04 by round 100 and then creeps up to 8.19. The noise variance is 4.0, so there was still room to improve, but the later rounds spend their effort on fitting noise rather than the formula. Unlike a forest, a boosted model can overfit by having too many trees, so the number of rounds must be chosen on held-out data. The lab does this with early stopping. scikit-learn's GradientBoostingRegressor with the same settings lands at 8.15; it is the same algorithm, and the small difference comes from ties between equally good splits late in training, which the library breaks in a different order.

Why "gradient"? For squared error, the residual is exactly the negative gradient of the loss with respect to the prediction. Other losses have other gradients, and boosting fits each tree to whatever the negative gradient is. For binary log loss, the model works on the log-odds scale and the negative gradient is y − p, the label minus the current predicted probability.

Python · logloss_gradient.py
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.tree import DecisionTreeRegressor

X, y = make_classification(n_samples=500, n_features=6, random_state=0)
p = np.full(len(y), y.mean())                # start: the share of positives
residual = y - p                             # negative gradient of log loss
print("first rows  y:", y[:4], " p:", p[:4].round(3))
print("            y - p:", residual[:4].round(3))

mine = DecisionTreeRegressor(max_depth=2, random_state=0).fit(X, residual)
gbc = GradientBoostingClassifier(n_estimators=1, max_depth=2, random_state=0).fit(X, y)
first = gbc.estimators_[0, 0]                # the regression tree fitted in round 1
print("my tree, first two splits:     ", mine.tree_.feature[:2],
      mine.tree_.threshold[:2].round(3))
print("library tree, first two splits:", first.tree_.feature[:2],
      first.tree_.threshold[:2].round(3))
Terminal
python logloss_gradient.py
Expected output
first rows  y: [1 0 1 0]  p: [0.502 0.502 0.502 0.502]
            y - p: [ 0.498 -0.502  0.498 -0.502]
my tree, first two splits:      [5 4] [-0.102  1.138]
library tree, first two splits: [5 4] [-0.102  1.138]

The first tree of GradientBoostingClassifier splits exactly where a regression tree fitted to y − p does. The library then sets each leaf value with a Newton step, which also uses p(1 − p), rather than the plain mean, so the leaf values differ while the splits match. To sum up the contrast:

  • Bagging and random forests grow deep, low-bias trees independently, on bootstrap samples, and average them. They can be trained in parallel, more trees rarely hurt, and the main settings are max_features and the leaf size.
  • Boosting grows shallow, high-bias trees in sequence, each fitted to the negative gradient. Tuned well, it often reaches lower error on tabular data, but it can overfit with too many rounds and needs the learning rate and the number of trees tuned together.

05. Check your understanding

Practice check · 3 questions

Bagging and boosting in practice

Use the outputs and the reasoning of this lesson.

Q1. In `bias_variance.py`, averaging 100 bagged stumps lowers the test MSE only from 18.44 to 16.93. Why does bagging help so little here?
Q2. A random forest with 200 trees scores well on validation. You raise `n_estimators` to 2,000. What should you expect?
Q3. A gradient-boosted classifier with log loss currently gives a churner (label 1) a predicted probability of 0.8. What target does the next tree get for this row?
Practice only: not graded, not saved, not evidence.

06. Apply it

Add the first two ensembles to your skill project.

  1. On your project dataset, with one fixed set of cross-validation folds (KFold(5, shuffle=True, random_state=0), or StratifiedKFold for classification), score a random forest with max_features set to 1.0, 0.5 and the square root of the number of features. Keep the folds; you will reuse them for every model in this skill.
  2. Fit GradientBoostingRegressor or GradientBoostingClassifier with depth-2 and depth-6 trees, and record the training and validation score at several numbers of trees using staged_predict.
  3. Write three sentences: which family helps more on your data, whether that matches a high-variance or high-bias starting point, and what the curve from step 2 says about the number of trees.

07. Review prompt

Without looking back, explain what a bootstrap sample is and what a random forest adds to bagging; why averaging reduces variance but not bias; why the variance of a forest stops falling after enough trees; what each new tree fits in gradient boosting with squared error and with log loss; and why a boosted model, unlike a forest, can be hurt by adding trees.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check