Sub topic 14
Related methods: extremely randomized trees and boosting
What this chapter assumes
You have read the earlier chapters on random forests. You know how bagging and random feature subsets work, and you can train a RandomForestClassifier in scikit-learn. You also know the bias-variance trade-off: variance is how much a model changes when the training data changes, and bias is the error from a model being too simple.
This chapter covers two methods that sit next to random forests. Extremely randomized trees keep the "average many trees" idea and add more randomness. Boosting builds trees one after another, so it is a different idea.
Extremely randomized trees
Extremely randomized trees (often called Extra-Trees) were introduced by Geurts, Ernst and Wehenkel in 2006. The method is the same as a random forest except for how each split is chosen.
How the split differs
A random forest picks a random subset of features at each node. For each feature in that subset, it searches for the best threshold, then keeps the best feature and threshold pair.
Extra-Trees also picks a random subset of features. For each feature in the subset, it draws one threshold at random, uniformly between that feature's minimum and maximum in the node. It then scores only those random candidate splits and keeps the best one.
This changes two things:
- No threshold search. Training is faster, because sorting values and scanning every possible cut point is the expensive part of fitting a tree.
- More randomness. Two trees grown on the same data still differ, because their thresholds differ.
Default data sampling
In scikit-learn, ExtraTreesClassifier uses bootstrap=False by default. Each tree sees the whole training set, and the randomness comes from the split thresholds. A random forest defaults to bootstrap=True.
You can turn bootstrapping on for Extra-Trees. This is required if you want an out-of-bag score, because without a bootstrap every sample is in every tree and no sample is out of bag.
Effect on bias and variance
Random thresholds are rarely the best thresholds, so each Extra-Tree is a slightly worse fit than a random forest tree. That raises bias a little. The trees are also less correlated, so averaging removes more variance. Extra-Trees often come out close to a random forest in accuracy. They can do better on noisy data, where an exact search for the best threshold mostly fits noise. They can also do worse. Treat the choice as something to test, not something to assume.
Smoothness
Because thresholds are random, the decision boundary of an Extra-Trees model is often smoother than a random forest's, especially for regression. This can help on small datasets with continuous features.
Boosting
Boosting is a different way to combine trees. A random forest trains its trees independently and in parallel, then averages them. Boosting trains trees in sequence, and each new tree is trained to correct the errors of the ensemble so far.
Gradient boosting for regression
In gradient boosting with squared-error loss, the procedure is:
- Start with a constant prediction, such as the mean of
y. - Compute the residuals: the true value minus the current prediction.
- Fit a small tree to the residuals.
- Add that tree's predictions to the ensemble, multiplied by a small number called the learning rate.
- Repeat steps 2 to 4.
For other loss functions, the tree is fit to the negative gradient of the loss, which is where the name comes from. For squared error, the negative gradient is exactly the residual.
The following code does this by hand and prints the training error as trees are added.
import numpy as np
from sklearn.tree import DecisionTreeRegressor
rng = np.random.default_rng(0)
X = rng.uniform(-3, 3, size=(300, 1))
y = np.sin(X[:, 0]) + rng.normal(0, 0.2, size=300)
learning_rate = 0.1
pred = np.full_like(y, y.mean())
trees = []
for m in range(100):
residual = y - pred
tree = DecisionTreeRegressor(max_depth=2, random_state=0)
tree.fit(X, residual)
pred += learning_rate * tree.predict(X)
trees.append(tree)
if (m + 1) in (1, 10, 100):
mse = np.mean((y - pred) ** 2)
print(f"after {m + 1:>3} trees: train MSE = {mse:.4f}")The error falls with each tree. Each tree is shallow (max_depth=2), so on its own it is a weak model. The ensemble becomes strong through the sum.
Opposite weak points
The two methods start from opposite places:
- A random forest uses deep, low-bias, high-variance trees and reduces variance by averaging.
- Boosting uses shallow, high-bias, low-variance trees and reduces bias by adding corrections.
This explains most of the practical differences below.
Hyperparameters that matter in boosting
| Parameter | Typical role | Notes |
|---|---|---|
| `n_estimators` (`max_iter` in the histogram version) | Number of sequential trees | More trees fit the training data more closely. Too many overfit. |
| `learning_rate` | Scale of each tree's contribution | Smaller values need more trees but usually generalize better. |
| `max_depth` (or `max_leaf_nodes`) | Size of each tree | Shallow trees, often depth 3 or less, are common. |
| `subsample` | Fraction of rows used per tree | Values below 1.0 give stochastic gradient boosting and can reduce overfitting. |
Learning rate and number of trees trade off against each other. Halving the learning rate roughly means you need more trees for the same fit. Tune them together, and use early stopping to choose the number of trees.
Early stopping
Adding trees to a random forest does not cause overfitting in the usual sense. The error levels off. Boosting is different: validation error falls, reaches a minimum, and then rises as the model starts fitting noise. Early stopping watches a validation score and stops when it has not improved for a set number of rounds.
In scikit-learn, GradientBoostingClassifier takes n_iter_no_change and validation_fraction. HistGradientBoostingClassifier has early_stopping. Its default is "auto", which turns early stopping on only when there are more than 10,000 training samples.
Library choices
GradientBoostingClassifier is the classic implementation and is slow on large data. HistGradientBoostingClassifier bins features into histograms first, which makes it much faster on large datasets, and it handles missing values natively. XGBoost, LightGBM and CatBoost are separate libraries built on the same idea with extra engineering. Their parameter names differ from scikit-learn's, so check each one's documentation.
Comparing the methods on one dataset
This script compares four models with 5-fold cross-validation. Running it on your machine shows how close they are on this dataset. The exact numbers depend on your library versions.
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import (
ExtraTreesClassifier,
GradientBoostingClassifier,
HistGradientBoostingClassifier,
RandomForestClassifier,
)
from sklearn.model_selection import cross_val_score
X, y = load_breast_cancer(return_X_y=True)
models = {
"random forest": RandomForestClassifier(
n_estimators=300, random_state=0, n_jobs=-1
),
"extra trees": ExtraTreesClassifier(
n_estimators=300, random_state=0, n_jobs=-1
),
"gradient boosting": GradientBoostingClassifier(
n_estimators=200, learning_rate=0.1, max_depth=3, random_state=0
),
"hist gradient boosting": HistGradientBoostingClassifier(
learning_rate=0.1, max_iter=200, random_state=0
),
}
for name, model in models.items():
scores = cross_val_score(model, X, y, cv=5)
print(f"{name:<24} mean={scores.mean():.3f} std={scores.std():.3f}")To use an out-of-bag score with Extra-Trees, enable the bootstrap:
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import ExtraTreesClassifier
X, y = load_breast_cancer(return_X_y=True)
et = ExtraTreesClassifier(
n_estimators=300, bootstrap=True, oob_score=True, n_jobs=-1, random_state=0
)
et.fit(X, y)
print("Extra-Trees OOB accuracy:", et.oob_score_)If you set oob_score=True while bootstrap=False, scikit-learn raises an error.
Failure modes and gotchas
- Boosting overfits noisy labels. Each new tree tries to fix the remaining errors, and mislabeled points keep producing large errors. A random forest is more tolerant here.
- Boosting is harder to tune. A random forest usually works well with defaults. Boosting needs the learning rate, tree size and number of trees chosen together.
- Boosting does not parallelize across trees. Tree
kneeds treek-1. Parallelism happens inside each tree, such as across features or histogram bins. - Extra-Trees can underfit with few trees or irrelevant features. Random thresholds on uninformative features waste candidate splits. Use more trees, or raise
max_features. - Feature importances carry over. Both Extra-Trees and boosted trees expose
feature_importances_, and they share the weaknesses of impurity-based importance covered earlier. Permutation importance works on any of them.
Choosing between them
| Situation | Reasonable first choice |
|---|---|
| You want a strong baseline with little tuning | Random forest |
| You want fast training and are willing to test a variant | Extra-Trees |
| The data is noisy and the dataset is small | Extra-Trees or random forest |
| You need the highest accuracy on tabular data and can tune | Gradient boosting |
| The dataset has many rows | `HistGradientBoostingClassifier` or LightGBM |
| You need an out-of-bag estimate | Random forest, or Extra-Trees with `bootstrap=True` |
Exercise
In scikit-learn, why does ExtraTreesClassifier(oob_score=True) fail with default settings, and how do you fix it?
Show answer
ExtraTreesClassifier defaults to bootstrap=False, so every tree is trained on the full training set and no samples are out of bag. Set bootstrap=True along with oob_score=True.
Exercise
A gradient boosting model reaches 100% training accuracy but its validation accuracy starts to fall after 150 trees. Name two changes that could help.
Show answer
Use early stopping (for example n_iter_no_change) so training halts near the validation minimum. Other valid changes: lower the learning rate and raise the number of trees, use shallower trees, or set subsample below 1.0.
Exercise
A random forest uses deep trees and boosting uses shallow trees. Which error component does each approach mainly reduce?
Show answer
A random forest averages low-bias, high-variance deep trees, so it mainly reduces variance. Boosting adds corrections to high-bias shallow trees, so it mainly reduces bias.