Skip to content

38. Ensembles

An ensemble is a model that combines the predictions of several models. The models inside it are its base learners. A random forest is an ensemble of trees, and gradient boosting is another one. You met both in module 35 and module 36 as ready-made tools. This module opens them up. You learn why a group of models beats its members, build bagging and gradient boosting by hand, combine different model types with voting and stacking, and compare all of them fairly.

The examples use two course datasets: data/houses.csv (predict the sale price, scored with RMSE) and data/customers.csv (predict churn, scored with ROC-AUC). The data dictionary describes every column.

  • Explain with a simulation why averaging models with uncorrelated errors reduces variance, and why correlated errors limit the gain.
  • Build bagging by hand from bootstrap samples, then use BaggingRegressor and its out-of-bag score.
  • Explain a random forest as bagging plus feature subsampling, and choose max_features with the out-of-bag score.
  • Explain AdaBoost as reweighting, build gradient boosting by hand for 3 rounds and match GradientBoostingRegressor exactly.
  • Trade the learning rate against the number of trees, and stop early with HistGradientBoosting, XGBoost and LightGBM.
  • Combine models with hard and soft voting and with stacking, explain why cv prevents leakage, and compare models on the same folds with mean ± standard deviation.

One model makes errors. Several different models make different errors. If you combine their predictions well, part of the errors cancel. The combined model is an ensemble. Its accuracy depends on two things: how good each base learner is, and how different their errors are. The second property is the diversity of the ensemble.

There are three families. They differ in how they make the base learners different and in how they combine them.

Family How the base learners differ How they are combined Main effect scikit-learn
Bagging same model, trained on different bootstrap samples (and feature subsets) average or majority vote lowers variance BaggingRegressor, RandomForestRegressor
Boosting small models trained one after another, each one on the mistakes of the ones before weighted sum lowers bias AdaBoostClassifier, GradientBoostingRegressor, HistGradientBoostingClassifier
Voting and stacking different model types on the same data average, or a second model that learns the weights uses the strengths of each type VotingClassifier, StackingClassifier
flowchart TB
    subgraph Bagging["Bagging: in parallel"]
        direction LR
        D1["Training set"] --> S1["Bootstrap 1"] --> M1["Tree"]
        D1 --> S2["Bootstrap 2"] --> M2["Tree"]
        D1 --> S3["Bootstrap 3"] --> M3["Tree"]
        M1 --> A1["Average"]
        M2 --> A1
        M3 --> A1
    end
    subgraph Boosting["Boosting: in sequence"]
        direction LR
        B0["Start: the mean"] --> B1["Tree 1 fits<br/>the errors"] --> B2["Tree 2 fits the<br/>remaining errors"] --> B3["Tree 3 …"]
    end

Recall the bias–variance view of module 37. A deep tree has low bias and high variance: it fits the training set closely and changes a lot when the data change. A shallow tree has high bias and low variance. Bagging averages many deep trees and keeps their low bias while it removes much of their variance. Boosting adds many shallow trees and removes bias step by step.

The wisdom of crowds is the observation that the average guess of many people is often better than most single guesses. It works only when the people err independently. If everyone copies the same expert, the crowd is no wiser than the expert.

Simulate it. 25 appraisers estimate the price of 20,000 houses. Each appraiser is unbiased, and the standard deviation of each error is 50,000 USD. The error correlation ρ\rho (rho) measures how much the appraisers err in the same direction on the same house: 0 means independent, 1 means identical.

import numpy as np
import pandas as pd
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
rng = np.random.default_rng(42)
n_models, n_houses, sigma = 25, 20_000, 50_000
for rho in [0.0, 0.5, 0.9]:
corr = rho * np.ones((n_models, n_models)) + (1 - rho) * np.eye(n_models)
errors = rng.multivariate_normal(np.zeros(n_models), sigma**2 * corr, size=n_houses)
one = errors[:, 0].std() # error spread of a single appraiser
crowd = errors.mean(axis=1).std() # error spread of the average of 25
formula = sigma * np.sqrt(rho + (1 - rho) / n_models)
print(
f"rho {rho:.1f} | one {one:6,.0f} | average of 25 {crowd:6,.0f}"
f" | formula {formula:6,.0f}"
)
Output
rho 0.0 | one 50,167 | average of 25 10,007 | formula 10,000
rho 0.5 | one 50,091 | average of 25 36,090 | formula 36,056
rho 0.9 | one 50,361 | average of 25 47,839 | formula 47,539

Each row of errors holds the 25 errors on one house. multivariate_normal draws them with the chosen correlation. With independent errors, the average of 25 appraisers errs only a fifth as much as one appraiser. With ρ=0.5\rho = 0.5, the average cuts the error by only about 28% instead of 80%. With ρ=0.9\rho = 0.9, averaging barely helps.

The formula behind the last column: for MM models whose errors each have variance σ2\sigma^2 and pairwise correlation ρ\rho, the variance of the average error is

Var⁡(eˉ)=ρ σ2+1−ρM σ2.\operatorname{Var}(\bar{e}) = \rho\,\sigma^2 + \frac{1 - \rho}{M}\,\sigma^2 .

The second term shrinks as you add models. The first term does not. It is a floor that only lower correlation can lower. This one formula explains the design of every bagging method: train many models, and make their errors as uncorrelated as possible.

The same idea works for classifiers that vote. Suppose each classifier is right 60% of the time, independently of the others. The majority vote (the class most models predict) is right when more than half of them are right. The binomial distribution of module 29 gives that probability:

from scipy.stats import binom
for n in [1, 5, 25, 101]:
p_majority = binom.sf(n // 2, n, 0.6) # P(more than n // 2 of n are right)
print(f"{n:>3} independent voters at 60%: majority right {p_majority:.1%}")
Output
1 independent voters at 60%: majority right 60.0%
5 independent voters at 60%: majority right 68.3%
25 independent voters at 60%: majority right 84.6%
101 independent voters at 60%: majority right 97.9%

binom.sf(k, n, p) is the probability of more than k successes. 101 independent voters, each only a little better than a coin, are almost always right together. Real models are never independent, because they learn from the same data. The gain is therefore smaller in practice, and diversity is what you work for.

Bagging (bootstrap aggregating, introduced in module 35) trains the same model on many bootstrap samples and averages the predictions. A bootstrap sample draws nn rows from the nn training rows with replacement. Some rows appear twice or more, and others not at all. The chance that a given row is never drawn is

(1−1n)n≈e−1≈0.368.\left(1 - \frac{1}{n}\right)^{n} \approx e^{-1} \approx 0.368 .

So each bootstrap sample holds about 63.2% of the distinct rows. The other 36.8% are the out-of-bag (OOB) rows of that model. They are a free validation set: the model never saw them. The out-of-bag score predicts each training row with only the models that did not train on it, then scores those predictions. It estimates the test score without a separate validation set and without extra fits.

Bagging helps unstable models: models whose predictions change a lot when the training data change a little, such as deep trees. It does little for stable models such as linear regression, because every bootstrap copy gives almost the same line.

Random forests: bagging plus feature subsampling

Section titled “Random forests: bagging plus feature subsampling”

Bagged trees are still correlated. On the houses, every tree splits first on sqft, because it is the strongest feature. The trees then look alike, and the floor ρ σ2\rho\,\sigma^2 stays high. A random forest adds feature subsampling: at each split, a tree may choose only among a random subset of the features. The max_features parameter sets the size of the subset. Some trees must then split on other features first. Each tree becomes a little worse, but the trees become less correlated, and the average improves.

Setting Meaning Default
n_estimators number of trees; more never hurts accuracy, only time 100
max_features features tried at each split: a count, a share or "sqrt" 1.0 (all) for RandomForestRegressor, "sqrt" for RandomForestClassifier
min_samples_leaf smallest number of rows in a leaf 1
max_samples size of each bootstrap sample (share of rows) all rows
oob_score compute the out-of-bag score False

Boosting builds the ensemble in sequence. Each new base learner concentrates on the rows that the ensemble so far gets wrong. The base learners are weak learners: small models, such as a stump (a tree with one split), that are only a little better than guessing.

AdaBoost (adaptive boosting) was the first successful boosting method. It gives every training row a sample weight. The weights start equal. After each round, AdaBoost raises the weights of the misclassified rows, so the next stump must pay more attention to them. Each stump also gets a vote weight α\alpha that grows as its weighted error ε\varepsilon falls. For two classes and a learning rate of 1, scikit-learn uses

α=ln⁡1−εε,wi←wi eα for each misclassified row i,\alpha = \ln\frac{1 - \varepsilon}{\varepsilon}, \qquad w_i \leftarrow w_i \, e^{\alpha} \text{ for each misclassified row } i ,

and then rescales the weights so that they sum to 1. Here is one round by hand on 10 customers, with the stump “churn if tenure_months ≤ 8”:

tenure = np.array([1, 2, 3, 5, 8, 13, 20, 30, 45, 60])
churned = np.array([1, 1, 0, 1, 1, 0, 0, 1, 0, 0])
weights = np.full(10, 0.1) # equal weights to start
stump = (tenure <= 8).astype(int)
wrong = stump != churned
error = weights[wrong].sum() # weighted error of the stump
alpha = np.log((1 - error) / error) # vote weight of the stump
weights = weights * np.exp(alpha * wrong) # boost the misclassified rows
weights = weights / weights.sum()
print(f"misclassified: tenure {tenure[wrong]}, error {error:.1f}, alpha {alpha:.3f}")
print(weights.round(4))
Output
misclassified: tenure [ 3 30], error 0.2, alpha 1.386
[0.0625 0.0625 0.25 0.0625 0.0625 0.0625 0.0625 0.25 0.0625 0.0625]

The stump got two customers wrong: a short-tenure stayer and a long-tenure churner. Their weights quadrupled. After the rescaling, those two rows hold half of the total weight. The next stump therefore cannot ignore them. The final AdaBoost prediction is the α\alpha-weighted vote of all stumps.

Gradient boosting: fit the residuals step by step

Section titled “Gradient boosting: fit the residuals step by step”

Gradient boosting generalizes the idea to any differentiable loss. For regression with squared error, it is simple. Start with a constant prediction F0F_0, the mean of the target. Then repeat for m=1,2,…,Mm = 1, 2, \ldots, M:

  1. Compute the residuals of the current model: ri=yi−Fm−1(xi)r_i = y_i - F_{m-1}(\mathbf{x}_i).
  2. Fit a small tree hmh_m to the residuals (the residuals are its target).
  3. Add a fraction of it: Fm(x)=Fm−1(x)+ν hm(x)F_m(\mathbf{x}) = F_{m-1}(\mathbf{x}) + \nu\, h_m(\mathbf{x}).

ν\nu (nu) is the learning rate, also called shrinkage. Each tree corrects only a fraction of the remaining error, so later trees can still correct the earlier ones.

Why “gradient”? For the loss L=12(y−F)2L = \tfrac{1}{2}(y - F)^2, the derivative with respect to the prediction is ∂L/∂F=−(y−F)\partial L / \partial F = -(y - F). The residual is the negative gradient of the loss. Each tree therefore takes one step of gradient descent (module 32) in the space of predictions. For other losses (absolute error, log loss for classification), the tree fits the negative gradient of that loss instead. That target is called the pseudo-residual.

Two settings control the fit together:

More of… Effect Risk
n_estimators (trees) lower training error overfitting after the best point
learning_rate each tree corrects more, fewer trees needed overshoots and overfits faster
max_depth / max_leaf_nodes each tree models more interactions each tree overfits
subsample < 1 each tree sees a random share of rows (stochastic gradient boosting) too small: noisy trees

A lower learning rate needs more trees, but it usually reaches a slightly better optimum. As a rough guide, a learning rate 3 times smaller needs 2 to 3 times more trees: often fewer than in proportion (Example 4 shows real numbers). The practical recipe: fix a small learning rate (0.05 or 0.1), then let early stopping choose the number of trees. Early stopping holds out a validation set and stops adding trees when the validation score has not improved for a set number of rounds. HistGradientBoosting calls that number n_iter_no_change.

Fast gradient boosting: HistGradientBoosting, XGBoost and LightGBM

Section titled “Fast gradient boosting: HistGradientBoosting, XGBoost and LightGBM”

GradientBoostingRegressor tries every threshold of every feature at every split, so it is slow on large data. Modern libraries first bin each feature into about 256 bins (at most 255 by default in scikit-learn and LightGBM, 256 in XGBoost), which forms a histogram, and search only the bin edges. This is histogram-based gradient boosting. It is 10 to 100 times faster on large data, handles missing values and can handle categorical features natively.

Library Class Strengths
scikit-learn HistGradientBoostingRegressor / Classifier no extra dependency; native categories and NaN; built-in early stopping
XGBoost XGBRegressor / XGBClassifier regularized objective; mature; GPU support; widely used in competitions and industry
LightGBM LGBMRegressor / LGBMClassifier grows trees leaf-wise (always splits the leaf with the largest gain), so it is very fast; strong on large data

The libraries use different names for the same ideas:

Idea HistGradientBoosting XGBoost LightGBM
number of trees max_iter n_estimators n_estimators
step size learning_rate learning_rate learning_rate
tree size max_leaf_nodes, max_depth max_depth num_leaves
minimum rows per leaf min_samples_leaf min_child_weight (a weight sum) min_child_samples
L2 penalty on leaf values l2_regularization reg_lambda reg_lambda
row subsampling — subsample subsample with subsample_freq=1
column subsampling max_features colsample_bytree colsample_bytree
early stopping early_stopping=True, n_iter_no_change early_stopping_rounds + eval_set lgb.early_stopping(...) callback + eval_X, eval_y
seed random_state random_state random_state
threads (OpenMP, see below) n_jobs n_jobs
quiet verbose=0 (default) verbosity=0 verbose=-1

For reproducible results and stable timings, fix the seed and the thread count. XGBoost and LightGBM take n_jobs. LightGBM also prints [LightGBM] [Info] lines and warnings to the terminal on every fit unless you pass verbose=-1. scikit-learn’s HistGradientBoosting has no n_jobs. It uses all CPU cores through OpenMP (a library for running loops on several threads). On a table of a few thousand rows, starting and syncing the threads costs more than they save, and the cost grows when the machine is busy. The threadpoolctl package (installed with scikit-learn) limits the threads. Call it after scikit-learn is imported, so that its OpenMP library is already loaded:

from sklearn.ensemble import HistGradientBoostingRegressor
from threadpoolctl import threadpool_limits
threadpool_limits(limits=1) # 1 thread for OpenMP and BLAS, for the whole script

Called like this, without with, the limit holds for the whole process until the script ends. limits=1 without user_api caps every thread pool that is loaded: OpenMP and also the BLAS libraries (OpenBLAS, MKL) that NumPy uses for matrix products. threadpool_limits(limits=1, user_api="openmp") caps OpenMP only, and with threadpool_limits(limits=1): caps it only inside the with block. On small tables the limit can make the boosting fits much faster, especially on a busy machine. Remove it for data with hundreds of thousands of rows, where the threads pay off. The scores are the same either way.

A voting ensemble fits several different models on the same data and combines their predictions with a fixed rule. It needs no training of its own.

  • Hard voting predicts the class that most models predict. It uses only the labels.
  • Soft voting averages the predicted probabilities and predicts the class with the highest average: p^(x)=1M∑m=1Mp^m(x)\hat{p}(\mathbf{x}) = \frac{1}{M} \sum_{m=1}^{M} \hat{p}_m(\mathbf{x}). It uses how sure each model is. Optional weights give some models more say.

Soft voting is usually better when the models give sensible probabilities. It also gives a probability, so you can rank customers and compute ROC-AUC. A hard-voting ensemble has no predict_proba at all. For regression, VotingRegressor averages the predictions.

Stacking: a model that learns how to combine

Section titled “Stacking: a model that learns how to combine”

Stacking replaces the fixed rule of voting with a second model, the meta-learner (final_estimator in scikit-learn). The meta-learner takes the predictions of the base models as its input features. These features are meta-features. It learns which model to trust, and how much.

The trap is leakage. If you fit the base models on the training set and then predict the same training set, the meta-features are too good. A random forest predicts its own training rows almost perfectly. The meta-learner then learns “trust the forest” and gives it a huge weight. On new data, the forest is not nearly that good, and the stack fails.

The fix is out-of-fold predictions. Split the training set into kk folds. For each fold, fit the base models on the other k−1k-1 folds and predict the held-out fold. Every training row then gets a prediction from models that never saw it. Those predictions behave like predictions on new data, so the meta-learner learns honest weights. StackingClassifier(cv=5) does exactly this. After that, it refits each base model on the full training set for use at prediction time.

flowchart LR
    T["Training set"] --> CV["cv=5: out-of-fold<br/>predictions of each<br/>base model"]
    CV --> MF["Meta-features<br/>one column per model"]
    MF --> ML["Meta-learner<br/>(logistic regression)"]
    T --> FULL["Base models refit<br/>on all training rows"]
    FULL --> P["New data: base<br/>predictions"]
    P --> ML
    ML --> Y["Final prediction"]

Use a simple meta-learner, such as logistic regression or ridge regression. The meta-features are few and strongly correlated, and a complex meta-learner overfits them. passthrough=True also gives the meta-learner the original features. It rarely helps on small data.

A comparison is fair when every model faces the same test. Three rules:

  1. Same splits. Create one CV splitter, such as StratifiedKFold(5, shuffle=True, random_state=42), and pass the same object to every model. Then fold 3 holds the same customers for every model.
  2. Mean ± standard deviation. Report the spread of the fold scores, not only the mean. A gain smaller than the spread may be noise.
  3. Paired differences. Because the folds are the same, you can subtract the scores fold by fold. A model that wins on all 5 folds is more convincing than a mean that is higher by 0.002.

Fit time matters too. A model that is 0.002 better and 50 times slower to train is rarely the right choice. Time varies between machines and runs, so treat it as a rough guide.

Ensembles are not free. They cost training time, prediction time and memory, and they are hard to explain. Skip them, or at least test a simpler model first, when:

  • The signal is close to linear. A regularized linear model then matches the trees, with readable coefficients.
  • The data are small. With a few hundred rows, a forest has little to average and the CV spread hides any gain.
  • The base models agree. Voting or stacking models whose predictions correlate at 0.95 cannot add much: the ρ σ2\rho\,\sigma^2 floor again.
  • Interpretability is required. A credit decision or a medical rule may need a model that a person can check line by line.
  • Latency or memory is tight. A stack of 3 models with 300 trees each is slow on a phone or in a 10 ms web request.

The bundled diabetes dataset (442 patients, 10 standardized features, a disease progression score) shows the first two points. Compare a ridge regression with two tree ensembles on the same 5 folds:

from sklearn.datasets import load_diabetes
from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor
from sklearn.linear_model import RidgeCV
from sklearn.model_selection import KFold, cross_val_score
X_d, y_d = load_diabetes(return_X_y=True, as_frame=True)
cv_d = KFold(5, shuffle=True, random_state=42)
small_models = {
"ridge": RidgeCV(alphas=np.logspace(-3, 3, 13)),
"random forest": RandomForestRegressor(min_samples_leaf=5, random_state=42),
"gradient boosting": GradientBoostingRegressor(
n_estimators=200, learning_rate=0.05, max_depth=2, random_state=42
),
}
for name, model in small_models.items():
rmse = -cross_val_score(
model, X_d, y_d, cv=cv_d, scoring="neg_root_mean_squared_error"
)
print(f"{name:<17} RMSE {rmse.mean():.1f} ± {rmse.std():.1f}")
Output
ridge RMSE 54.9 ± 2.5
random forest RMSE 56.6 ± 2.9
gradient boosting RMSE 56.2 ± 3.1

The ridge regression wins, it trains in milliseconds, and its 10 coefficients explain the model. The ensembles are worse by less than one standard deviation of the folds. On this dataset, an ensemble buys nothing. The diabetes features are already centered and on one common scale, so the ridge needs no scaler here.

Example 1 — Bag decision trees by hand for house prices

Section titled “Example 1 — Bag decision trees by hand for house prices”

Goal: An estate agency’s single decision tree gives unstable price estimates. Build bagging by hand from bootstrap samples, see how the error falls as trees are added, and check the result with BaggingRegressor and its out-of-bag score.

from sklearn.metrics import root_mean_squared_error
from sklearn.model_selection import train_test_split
houses = pd.read_csv("data/houses.csv")
X = pd.get_dummies(
houses.drop(columns=["house_id", "sold_date", "price"]),
columns=["neighborhood"],
dtype=int,
)
y = houses["price"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42
)
medians = X_train.median() # learned on the training rows only
X_train, X_test = X_train.fillna(medians), X_test.fillna(medians)
print(X_train.shape, X_test.shape)
print(f"mean training price {y_train.mean():,.0f}")
Output
(2250, 18) (750, 18)
mean training price 474,008

pd.get_dummies turns neighborhood into 8 columns of 0 and 1. It learns nothing from the data (the 8 names are fixed), so it is safe before the split. The median imputation learns from data, so it uses the training medians only. Every tree-based model on this page uses these 18 columns.

from sklearn.tree import DecisionTreeRegressor
tree = DecisionTreeRegressor(random_state=42).fit(X_train, y_train)
print(f"depth {tree.get_depth()}, leaves {tree.get_n_leaves()}")
print(f"train RMSE {root_mean_squared_error(y_train, tree.predict(X_train)):>9,.0f}")
print(f"test RMSE {root_mean_squared_error(y_test, tree.predict(X_test)):>9,.0f}")
Output
depth 27, leaves 2234
train RMSE 0
test RMSE 149,682

With no depth limit, the tree grows until almost every house has its own leaf. The training error is zero and the test error is about 150,000 USD. That is the high-variance behavior that bagging targets.

n = len(X_train)
rows = rng.integers(0, n, size=n) # n draws with replacement
times_drawn = np.bincount(rows, minlength=n)
in_bag = times_drawn > 0
print(f"distinct rows: {in_bag.sum()} of {n} ({in_bag.mean():.1%})")
print(f"out-of-bag rows: {(times_drawn == 0).sum()}")
print("rows drawn 0, 1, 2, ... times:", np.bincount(times_drawn))
Output
distinct rows: 1393 of 2250 (61.9%)
out-of-bag rows: 857
rows drawn 0, 1, 2, ... times: [857 775 443 121 44 10]

rng.integers(0, n, size=n) draws n row positions, and the same position can come up again. np.bincount counts how often each row was drawn. About 62% of the rows are in the sample, close to the 63.2% of the formula. A few rows were drawn 4 or 5 times.

all_preds = []
for b in range(50):
rows = rng.integers(0, n, size=n)
tree_b = DecisionTreeRegressor(random_state=b)
tree_b.fit(X_train.iloc[rows], y_train.iloc[rows])
all_preds.append(tree_b.predict(X_test))
all_preds = np.array(all_preds) # shape: (trees, test houses)
print(all_preds.shape)
for m in [1, 2, 5, 10, 25, 50]:
rmse = root_mean_squared_error(y_test, all_preds[:m].mean(axis=0))
print(f"average of {m:>2} trees: test RMSE {rmse:,.0f}")
Output
(50, 750)
average of 1 trees: test RMSE 151,969
average of 2 trees: test RMSE 126,803
average of 5 trees: test RMSE 113,153
average of 10 trees: test RMSE 107,183
average of 25 trees: test RMSE 108,375
average of 50 trees: test RMSE 107,666

Each tree trains on its own bootstrap sample. The prediction of the bag is the column mean of all_preds. One bootstrapped tree is a little worse than the tree from Step 2, because it saw only about 63% of the distinct rows. The average of 10 trees cuts the error by 30%. After about 10 trees the curve is flat: the remaining error is the correlated part, ρ σ2\rho\,\sigma^2, plus the bias.

Step 5 — Use BaggingRegressor and its out-of-bag score

Section titled “Step 5 — Use BaggingRegressor and its out-of-bag score”
from sklearn.ensemble import BaggingRegressor
bag = BaggingRegressor(
DecisionTreeRegressor(), n_estimators=50, oob_score=True, random_state=42
)
bag.fit(X_train, y_train)
print(f"test RMSE {root_mean_squared_error(y_test, bag.predict(X_test)):,.0f}")
print(f"OOB R² {bag.oob_score_:.3f} | test R² {bag.score(X_test, y_test):.3f}")
print(f"OOB RMSE {root_mean_squared_error(y_train, bag.oob_prediction_):,.0f}")
outlier_ids = ["H0537", "H0542", "H0751", "H0914", "H2277", "H0887", "H0957", "H1990"]
in_test = houses.loc[X_test.index, "house_id"].isin(outlier_ids).sum()
print(f"known price outliers in the test set: {in_test} of {len(outlier_ids)}")
Output
test RMSE 106,163
OOB R² 0.864 | test R² 0.892
OOB RMSE 116,908
known price outliers in the test set: 0 of 8

BaggingRegressor does the loop of Step 4 for you, with its own random draws, so the error differs slightly. oob_score_ is the R² of the out-of-bag predictions, and oob_prediction_ holds them, one per training house. The OOB RMSE is about 10,000 USD above the test RMSE. Fewer trees explain only a small part of the gap: each OOB prediction averages the 18 or so trees that did not see that house, and Step 4 showed that 25 trees already do almost as well as 50. The main cause is the split. The data dictionary lists 8 houses with injected price errors, and all 8 fell into the training rows. They inflate the OOB error, which is measured on training rows, but not the test error. The OOB score is a fair estimate for the training rows; this test split happens to be easier.

Common mistakes:

  • Bagging a stable model, such as a linear regression. All bootstrap copies give nearly the same line, so the average equals one model. Bag high-variance models.
  • Reading the OOB score of a bag with few trees. With 10 trees, some rows are out of bag for only 2 or 3 trees, or for none (scikit-learn then warns). Use at least 50 trees for an OOB score.
  • Imputing with the medians of all rows before the split. The test rows then leak into the training features.

Example 2 — Decorrelate the trees with a random forest

Section titled “Example 2 — Decorrelate the trees with a random forest”

Goal: Improve on bagging with feature subsampling. Measure how often the trees start with the same split and how strongly their errors correlate for several max_features values, and choose the value with the out-of-bag score, not with the test set.

Step 1 — Measure root splits, error correlation and OOB R² for four settings

Section titled “Step 1 — Measure root splits, error correlation and OOB R² for four settings”
from sklearn.ensemble import RandomForestRegressor
def oob_error_correlation(forest: RandomForestRegressor) -> float:
"""Mean correlation of two trees' errors on the rows that neither tree saw."""
errors = np.array([t.predict(X_train.to_numpy()) for t in forest.estimators_])
errors = errors - y_train.to_numpy()
out_of_bag = np.ones(errors.shape, dtype=bool)
for i, rows in enumerate(forest.estimators_samples_):
out_of_bag[i, rows] = False # rows in tree i's bootstrap sample
corrs = []
for i in range(len(errors)):
for j in range(i + 1, len(errors)):
both = out_of_bag[i] & out_of_bag[j]
corrs.append(np.corrcoef(errors[i, both], errors[j, both])[0, 1])
return np.mean(corrs)
sqft_col = X_train.columns.get_loc("sqft")
results, forests = [], {}
for share in [1.0, 0.6, 0.33, 0.15]:
forest = RandomForestRegressor(
n_estimators=100, max_features=share, oob_score=True, random_state=42
).fit(X_train, y_train)
forests[share] = forest
results.append({
"max_features": share,
"root_is_sqft": np.mean([t.tree_.feature[0] == sqft_col for t in forest]),
"error_corr": oob_error_correlation(forest),
"oob_r2": forest.oob_score_,
})
print(pd.DataFrame(results).round(3).to_string(index=False))
Output
max_features root_is_sqft error_corr oob_r2
1.00 1.00 0.450 0.868
0.60 0.48 0.402 0.873
0.33 0.30 0.369 0.874
0.15 0.13 0.340 0.859

Iterating over a forest yields its fitted trees (forest.estimators_). t.tree_.feature[0] is the feature of a tree’s first split, its root. estimators_samples_ holds the bootstrap rows of each tree, so the error correlation of each pair of trees is measured only on rows that neither tree saw; no test house is used. The trees were fitted on a NumPy array internally, so they get one too (to_numpy()), which avoids a feature-name warning.

With max_features=1.0 (plain bagging), all 100 trees split first on sqft, and their errors correlate at about 0.45. Fewer features per split force other first splits and lower the correlation. The OOB R² peaks at 0.33: below that, each tree gets too weak, and the gain in diversity no longer pays for it.

Step 2 — Choose by OOB, then report the test score once

Section titled “Step 2 — Choose by OOB, then report the test score once”
best = max(results, key=lambda r: r["oob_r2"])["max_features"]
chosen = forests[best]
print(f"chosen by OOB: max_features={best}")
print(f"its test RMSE {root_mean_squared_error(y_test, chosen.predict(X_test)):,.0f}")
Output
chosen by OOB: max_features=0.33
its test RMSE 97,135

The choice uses only the training data, through the OOB score. The test set is read once, for the chosen forest only, so its score stays an honest estimate. It is about 9,000 USD below the test RMSE of the bag in Example 1 (106,163), at no extra cost: each split even searches fewer features.

Step 3 — Add trees with warm_start and watch OOB R² level off

Section titled “Step 3 — Add trees with warm_start and watch OOB R² level off”
forest = RandomForestRegressor(
max_features=0.33, oob_score=True, warm_start=True, random_state=42
)
for n_trees in [25, 50, 100, 200, 300]:
forest.set_params(n_estimators=n_trees).fit(X_train, y_train)
print(f"{n_trees:>3} trees: OOB R² {forest.oob_score_:.4f}")
Output
25 trees: OOB R² 0.8586
50 trees: OOB R² 0.8702
100 trees: OOB R² 0.8744
200 trees: OOB R² 0.8771
300 trees: OOB R² 0.8770

warm_start=True keeps the trees that are already fitted and adds only the new ones on each fit. The OOB R² rises quickly and then levels off. More trees never make a forest overfit. They only cost time and memory, and after about 200 trees they buy almost nothing here.

Common mistakes:

  • Tuning max_features on the test set. The test score then becomes part of the training process and is too optimistic. Use the OOB score or cross-validation.
  • Expecting RandomForestRegressor() with defaults to decorrelate the trees. Its default max_features=1.0 is plain bagging.
  • Raising n_estimators to fix a forest that underfits. More trees reduce variance, not bias. Look at max_features, min_samples_leaf or the features themselves.

Example 3 — Build gradient boosting by hand and match scikit-learn

Section titled “Example 3 — Build gradient boosting by hand and match scikit-learn”

Goal: See exactly what gradient boosting does. Run 3 rounds by hand with depth-3 trees on the residuals, then show that GradientBoostingRegressor with the same settings gives the same predictions.

learning_rate = 0.1
f0 = y_train.mean()
pred_train = np.full(len(y_train), f0)
pred_test = np.full(len(y_test), f0)
rmse_0 = root_mean_squared_error(y_train, pred_train)
print(f"F0 = {f0:,.0f} | train RMSE {rmse_0:,.0f}")
Output
F0 = 474,008 | train RMSE 317,178

The first model predicts the mean price for every house. Its RMSE equals the standard deviation of the prices. Every tree from now on corrects this guess.

Step 2 — Fit the first tree to the residuals

Section titled “Step 2 — Fit the first tree to the residuals”
residuals = y_train - pred_train
tree_1 = DecisionTreeRegressor(max_depth=3, random_state=42).fit(X_train, residuals)
first = pd.DataFrame({
"price": y_train.head(4),
"residual": residuals.head(4),
"tree_1": tree_1.predict(X_train.head(4)),
})
print(first.round(0))
pred_train = pred_train + learning_rate * tree_1.predict(X_train)
pred_test = pred_test + learning_rate * tree_1.predict(X_test)
print(f"after round 1: train RMSE {root_mean_squared_error(y_train, pred_train):,.0f}")
Output
price residual tree_1
2922 583500 109492.0 571297.0
340 458000 -16008.0 -93632.0
1099 213500 -260508.0 -207319.0
1543 238500 -235508.0 -207319.0
after round 1: train RMSE 295,344

The target of the tree is the residual, not the price. The tree predicts the mean residual of the leaf that each house falls into. The model then moves only 10% of the way toward the tree’s correction. One round lowers the training RMSE by about 22,000 USD.

for round_no in [2, 3]:
residuals = y_train - pred_train # what is still wrong
tree_m = DecisionTreeRegressor(max_depth=3, random_state=42).fit(X_train, residuals)
pred_train = pred_train + learning_rate * tree_m.predict(X_train)
pred_test = pred_test + learning_rate * tree_m.predict(X_test)
print(
f"after round {round_no}: train RMSE "
f"{root_mean_squared_error(y_train, pred_train):,.0f}, "
f"test RMSE {root_mean_squared_error(y_test, pred_test):,.0f}"
)
Output
after round 2: train RMSE 276,218, test RMSE 284,709
after round 3: train RMSE 259,286, test RMSE 269,527

Each round recomputes the residuals of the current model, fits a new tree to them and adds 10% of its prediction. The training error falls each round, and so does the test error. Each round adds only 10% of a tree’s correction, so three rounds are far too few: the test RMSE is still 270,000 USD. Example 4 runs hundreds of rounds.

Step 4 — Match GradientBoostingRegressor

Section titled “Step 4 — Match GradientBoostingRegressor”
from sklearn.ensemble import GradientBoostingRegressor
gbr = GradientBoostingRegressor(
n_estimators=3, learning_rate=0.1, max_depth=3, random_state=42
).fit(X_train, y_train)
sk_pred = gbr.predict(X_test)
print("same predictions:", np.allclose(sk_pred, pred_test))
print(f"largest difference: {np.abs(sk_pred - pred_test).max():.1e} USD")
print(f"sklearn starts from {gbr.init_.constant_[0][0]:,.0f}")
Output
same predictions: True
largest difference: 1.2e-10 USD
sklearn starts from 474,008

np.allclose confirms that the 750 test predictions match. The largest difference is a rounding error far below one cent. init_ is the starting model, a constant equal to the mean. The library does nothing more than this loop for squared error. It adds options (other losses, subsample, early stopping) and speed.

Common mistakes:

  • Fitting each new tree to the original price instead of the current residuals. Every tree then learns the same thing, and nothing is corrected.
  • Forgetting the learning rate in the update. With ν=1\nu = 1, the first trees overfit the residuals, and later trees spend their effort undoing it.
  • Using a deep tree as the base learner. Boosting works best with small trees (depth 2 to 6), each one adding a small correction.

Example 4 — Trade the learning rate against the number of trees

Section titled “Example 4 — Trade the learning rate against the number of trees”

Goal: Choose the learning rate and the number of trees for the house price model. Trace the test error tree by tree for four learning rates, then let HistGradientBoostingRegressor choose the number of trees with early stopping.

Step 1 — Trace the error after each tree

Section titled “Step 1 — Trace the error after each tree”
curves = {}
for lr in [1.0, 0.3, 0.1, 0.03]:
model = GradientBoostingRegressor(
n_estimators=300, learning_rate=lr, max_depth=3, random_state=42
).fit(X_train, y_train)
staged_preds = model.staged_predict(X_test) # after 1 tree, 2 trees, ...
curves[lr] = [root_mean_squared_error(y_test, p) for p in staged_preds]
for lr, curve in curves.items():
best = int(np.argmin(curve))
print(
f"lr {lr:<4} best after {best + 1:>3} trees: RMSE {curve[best]:,.0f} "
f"| after 300: {curve[-1]:,.0f}"
)
Output
lr 1.0 best after 14 trees: RMSE 125,381 | after 300: 135,383
lr 0.3 best after 31 trees: RMSE 100,352 | after 300: 105,878
lr 0.1 best after 145 trees: RMSE 96,430 | after 300: 98,460
lr 0.03 best after 298 trees: RMSE 96,451 | after 300: 96,456

staged_predict yields the predictions after 1 tree, after 2 trees, and so on, from one fit. A staged prediction like this traces the whole curve without refitting. The test set is used here only to draw the curves for teaching. To choose the settings, use a validation set or cross-validation, as Step 3 does.

import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 4.5))
for lr, curve in curves.items():
ax.plot(range(1, 301), np.array(curve) / 1000, label=f"learning_rate={lr}")
ax.set_ylim(90, 200)
ax.set(xlabel="Number of trees", ylabel="Test RMSE (thousand USD)")
ax.set_title("Gradient boosting on house prices")
ax.legend()
plt.show()
Four test-error curves against the number of trees. The learning rate 1.0 curve drops fastest, bottoms out near 125 thousand USD after about 14 trees and then rises. The 0.3 curve reaches about 100 thousand after 31 trees and rises slowly. The 0.1 curve reaches about 96 thousand after 145 trees. The 0.03 curve falls slowly and is still falling at 300 trees.
Test RMSE of gradient boosting after each tree, for four learning rates.

A large learning rate reaches its best point quickly, and that best point is poor. Then the error rises again: the model overfits. Smaller learning rates descend more slowly and reach a lower minimum. At 0.03, 300 trees are not yet enough. That is the trade-off: a small learning rate is more accurate but needs more trees, so more time. These curves use the test set only to show the trade-off; choosing the number of trees or the learning rate from them would be tuning on the test set. Step 3 lets a validation split choose.

Step 3 — Let early stopping choose the number of trees

Section titled “Step 3 — Let early stopping choose the number of trees”
for lr in [0.3, 0.1, 0.03]:
hgb = HistGradientBoostingRegressor(
learning_rate=lr,
max_iter=2000, # an upper limit; early stopping ends sooner
early_stopping=True,
validation_fraction=0.15,
n_iter_no_change=20,
random_state=42,
).fit(X_train, y_train)
best_trees = int(np.argmax(hgb.validation_score_)) # entry 0: before any tree
rmse = root_mean_squared_error(y_test, hgb.predict(X_test))
print(f"lr {lr:<4} kept {hgb.n_iter_:>3} trees, best after {best_trees:>3}"
f" | test RMSE {rmse:,.0f}")
Output
lr 0.3 kept 37 trees, best after 17 | test RMSE 104,101
lr 0.1 kept 70 trees, best after 50 | test RMSE 100,102
lr 0.03 kept 191 trees, best after 171 | test RMSE 99,608

early_stopping=True holds out 15% of the training rows (validation_fraction). After each tree, the model scores that validation set. It stops when 20 trees in a row (n_iter_no_change) bring no improvement. n_iter_ is the number of trees it fitted, and validation_score_ holds the validation score before the first tree and after each tree. When early stopping triggers, the best score comes exactly 20 trees before the end: scikit-learn does not roll back, so the model keeps those last 20 trees too. XGBoost and LightGBM instead predict with the trees up to their best iteration. The test set played no part in the stopping. The smaller the learning rate, the more trees early stopping keeps, but less than in proportion: 3 times smaller roughly doubles or triples the trees. The test errors are a little above the best points of Step 1, for two reasons: the model trains on 15% fewer houses, and the stopping point is chosen without the test set. That is the honest number. The three test scores only report each run; choose the learning rate with cross-validation on the training rows, not from these scores.

Common mistakes:

  • Tuning n_estimators and learning_rate as if they were independent. A smaller learning rate needs more trees (Step 3: 0.3 → 0.1 roughly doubled them). Fix one, then tune the other, or use early stopping.
  • Early stopping on the test set. The number of trees is then chosen on test data and the test score is optimistic. Stop on a validation split of the training data.
  • Setting max_iter to the default 100 with a learning rate of 0.03. The model stops long before it has converged. Raise the limit and let early stopping cut it.

Example 5 — Boost churn predictions with AdaBoost, XGBoost and LightGBM

Section titled “Example 5 — Boost churn predictions with AdaBoost, XGBoost and LightGBM”

Goal: A retention team needs a churn ranking. Fit AdaBoost with stumps and watch it learn, then fit XGBoost and LightGBM with early stopping on a validation split, with fixed seeds, one thread and no log output.

Step 1 — Prepare the churn data and three splits

Section titled “Step 1 — Prepare the churn data and three splits”
customers = pd.read_csv("data/customers.csv")
cat_cols = ["region", "plan", "contract", "payment_method"]
num_cols = [
"age", "has_autopay", "tenure_months", "monthly_charges", "total_charges",
"support_tickets", "logins_last_30d", "avg_session_minutes",
]
X_c = customers[cat_cols + num_cols].astype({c: "category" for c in cat_cols})
y_c = customers["churned"]
Xc_train, Xc_test, yc_train, yc_test = train_test_split(
X_c, y_c, test_size=0.25, stratify=y_c, random_state=42
)
Xc_fit, Xc_val, yc_fit, yc_val = train_test_split(
Xc_train, yc_train, test_size=0.2, stratify=yc_train, random_state=42
)
print(Xc_fit.shape, Xc_val.shape, Xc_test.shape)
print(
f"churn rate: fit {yc_fit.mean():.3f}, val {yc_val.mean():.3f},"
f" test {yc_test.mean():.3f}"
)
Output
(3000, 12) (750, 12) (1250, 12)
churn rate: fit 0.193, val 0.192, test 0.193

The four text columns become the pandas category dtype. XGBoost, LightGBM and HistGradientBoosting use that dtype to treat them as categories natively. The training set is split again: the models fit on Xc_fit and stop early on Xc_val. The test set stays untouched until the end. stratify keeps the churn rate equal in the three parts.

Step 2 — Watch AdaBoost learn from its mistakes

Section titled “Step 2 — Watch AdaBoost learn from its mistakes”
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import AdaBoostClassifier
from sklearn.impute import SimpleImputer
from sklearn.metrics import roc_auc_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder
from sklearn.tree import DecisionTreeClassifier
one_hot = ColumnTransformer([
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), cat_cols),
("num", SimpleImputer(strategy="median"), num_cols),
])
ada = make_pipeline(
one_hot,
AdaBoostClassifier(
DecisionTreeClassifier(max_depth=1), n_estimators=300, learning_rate=0.5,
random_state=42,
),
).fit(Xc_fit, yc_fit)
X_val_encoded = ada[0].transform(Xc_val)
staged = [
roc_auc_score(yc_val, p[:, 1])
for p in ada[-1].staged_predict_proba(X_val_encoded)
]
for k in [1, 2, 10, 50, 300]:
print(f"{k:>3} stumps: validation ROC-AUC {staged[k - 1]:.3f}")
print("first stump errors:", ada[-1].estimator_errors_[:4].round(3))
Output
1 stumps: validation ROC-AUC 0.500
2 stumps: validation ROC-AUC 0.687
10 stumps: validation ROC-AUC 0.825
50 stumps: validation ROC-AUC 0.861
300 stumps: validation ROC-AUC 0.870
first stump errors: [0.193 0.256 0.383 0.364]

scikit-learn’s trees and AdaBoost need numbers, so a ColumnTransformer one-hot encodes the categories and imputes the 10 blank total_charges. The first stump scores 0.5, a random ranking. Its weighted error, 0.193, is exactly the churn rate: with equal weights, the best single split still predicts “no churn” on both sides. AdaBoost then raises the weights of the churners, and the second stump must find them. After 50 stumps, the ensemble ranks churners well. staged_predict_proba gives the ensemble’s probabilities after each stump.

Step 3 — Fit XGBoost with early stopping

Section titled “Step 3 — Fit XGBoost with early stopping”
from xgboost import XGBClassifier
xgb = XGBClassifier(
n_estimators=1000, # upper limit
learning_rate=0.05,
max_depth=4,
subsample=0.8,
colsample_bytree=0.8,
enable_categorical=True, # use the category dtype
early_stopping_rounds=50,
eval_metric="auc",
random_state=42,
n_jobs=1,
)
xgb.fit(Xc_fit, yc_fit, eval_set=[(Xc_val, yc_val)], verbose=False)
xgb_auc = roc_auc_score(yc_test, xgb.predict_proba(Xc_test)[:, 1])
print(f"best iteration {xgb.best_iteration}, validation AUC {xgb.best_score:.3f}")
print(f"test ROC-AUC {xgb_auc:.3f}")
Output
best iteration 86, validation AUC 0.860
test ROC-AUC 0.842

eval_set is the data that XGBoost scores after each tree. early_stopping_rounds=50 stops after 50 trees without a gain in validation AUC, and best_iteration is the index (from 0) of the best tree count. predict_proba then uses the trees up to the best iteration only. verbose=False in fit silences the log of each round. The validation AUC is higher than the test AUC: the stopping point was chosen on the validation set, so its score is slightly optimistic.

import lightgbm as lgb
lgbm = lgb.LGBMClassifier(
n_estimators=1000,
learning_rate=0.05,
num_leaves=15,
subsample=0.8,
subsample_freq=1, # row subsampling is off unless this is set
colsample_bytree=0.8,
random_state=42,
n_jobs=1,
verbose=-1, # no warnings in the terminal
)
lgbm.fit(
Xc_fit, yc_fit, eval_X=Xc_val, eval_y=yc_val, eval_metric="auc",
callbacks=[lgb.early_stopping(50, verbose=False)],
)
lgbm_auc = roc_auc_score(yc_test, lgbm.predict_proba(Xc_test)[:, 1])
print(f"best iteration {lgbm.best_iteration_}, test ROC-AUC {lgbm_auc:.3f}")
Output
best iteration 96, test ROC-AUC 0.840

LightGBM controls tree size with num_leaves instead of a depth, because it grows trees leaf by leaf. subsample has no effect unless subsample_freq is at least 1. Early stopping is a callback, and eval_X and eval_y pass the validation data (LightGBM 4.7 deprecates the older eval_set). XGBoost and LightGBM stop after a similar number of trees and reach a similar test score.

Common mistakes:

  • Leaving LightGBM’s default verbose. Every fit then prints lines such as [LightGBM] [Info] Number of positive: 963, number of negative: 4037, and cross-validation prints them for every fold. Pass verbose=-1.
  • Passing text columns (the pandas str dtype) to XGBoost. It raises ValueError: DataFrame.dtypes for data must be int, float, bool or category. Cast them to category and pass enable_categorical=True.
  • Reporting the validation score from early stopping as the final score. The stopping point was chosen on it. Report a separate test or CV score.

Example 6 — Vote and stack three churn models

Section titled “Example 6 — Vote and stack three churn models”

Goal: Combine a logistic regression, a random forest and LightGBM. Compare hard voting, soft voting and stacking, then build the stack by hand twice to see why cv prevents leakage.

from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import StandardScaler
scaled = ColumnTransformer([
("cat", OneHotEncoder(handle_unknown="ignore"), cat_cols),
(
"num",
make_pipeline(SimpleImputer(strategy="median"), StandardScaler()),
num_cols,
),
])
base_models = [
("logreg", make_pipeline(scaled, LogisticRegression(max_iter=1000))),
("forest", make_pipeline(
one_hot,
RandomForestClassifier(n_estimators=100, min_samples_leaf=3, random_state=42),
)),
("lgbm", lgb.LGBMClassifier(
n_estimators=100, learning_rate=0.05, num_leaves=15, subsample=0.8,
subsample_freq=1, colsample_bytree=0.8, random_state=42, n_jobs=1, verbose=-1,
)),
]
test_probs = {}
for name, model in base_models:
model.fit(Xc_train, yc_train)
test_probs[name] = model.predict_proba(Xc_test)[:, 1]
acc = accuracy_score(yc_test, model.predict(Xc_test))
auc = roc_auc_score(yc_test, test_probs[name])
print(f"{name:<7} ROC-AUC {auc:.3f} | accuracy {acc:.3f}")
print(pd.DataFrame(test_probs).corr().round(2))
Output
logreg ROC-AUC 0.813 | accuracy 0.836
forest ROC-AUC 0.828 | accuracy 0.847
lgbm ROC-AUC 0.842 | accuracy 0.847
logreg forest lgbm
logreg 1.00 0.82 0.84
forest 0.82 1.00 0.95
lgbm 0.84 0.95 1.00

The logistic regression gets scaled features; the tree models get the unscaled one-hot columns; LightGBM takes the category columns directly. All three are fitted on the full training set, with 100 trees for LightGBM (about the early-stopping point of Example 5). The correlation table matters most. The forest and LightGBM agree strongly with each other, while the logistic regression differs more. A combination can only gain from the differences.

from sklearn.ensemble import VotingClassifier
hard = VotingClassifier(base_models, voting="hard").fit(Xc_train, yc_train)
soft = VotingClassifier(base_models, voting="soft").fit(Xc_train, yc_train)
print(f"hard voting accuracy {accuracy_score(yc_test, hard.predict(Xc_test)):.3f}")
print(f"soft voting accuracy {accuracy_score(yc_test, soft.predict(Xc_test)):.3f}")
soft_auc = roc_auc_score(yc_test, soft.predict_proba(Xc_test)[:, 1])
print(f"soft voting ROC-AUC {soft_auc:.3f}")
print("hard voting has predict_proba:", hasattr(hard, "predict_proba"))
Output
hard voting accuracy 0.847
soft voting accuracy 0.850
soft voting ROC-AUC 0.839
hard voting has predict_proba: False

VotingClassifier clones and refits each base model. Hard voting counts the three labels per customer; soft voting averages the three probabilities. Soft voting is slightly more accurate than hard voting here. Hard voting cannot rank customers at all: it has no predict_proba, so it has no ROC-AUC. Soft voting’s ROC-AUC lands between its members, a little below LightGBM alone. Two of its three members are highly correlated, and the weakest member pulls the average down.

Step 3 — Stack with a logistic regression meta-learner

Section titled “Step 3 — Stack with a logistic regression meta-learner”
from sklearn.ensemble import StackingClassifier
from sklearn.model_selection import StratifiedKFold
cv5 = StratifiedKFold(5, shuffle=True, random_state=42)
stack = StackingClassifier(
base_models, final_estimator=LogisticRegression(), cv=cv5
).fit(Xc_train, yc_train)
stack_auc = roc_auc_score(yc_test, stack.predict_proba(Xc_test)[:, 1])
print(f"stacking ROC-AUC {stack_auc:.3f}")
print("meta-learner weights:", stack.final_estimator_.coef_.round(2))
Output
stacking ROC-AUC 0.840
meta-learner weights: [[2.14 2.03 2.62]]

The stack trains each base model 6 times: 5 times for the out-of-fold meta-features and once on all rows. The meta-learner gives the three models similar positive weights, a little more to LightGBM. The stack comes close to LightGBM alone (0.842) but does not beat it. With strongly correlated members, neither voting nor stacking has much to add.

Step 4 — Build the meta-features without cv and see the leak

Section titled “Step 4 — Build the meta-features without cv and see the leak”
in_sample = np.column_stack([m.predict_proba(Xc_train)[:, 1] for _, m in base_models])
test_meta = np.column_stack(list(test_probs.values()))
print("AUC of each model on its own training rows:", [
round(roc_auc_score(yc_train, in_sample[:, j]), 3) for j in range(3)
])
leaky = LogisticRegression().fit(in_sample, yc_train)
leaky_auc = roc_auc_score(yc_test, leaky.predict_proba(test_meta)[:, 1])
print("leaky weights:", leaky.coef_.round(2), f"| test ROC-AUC {leaky_auc:.3f}")
Output
AUC of each model on its own training rows: [0.819, 0.99, 0.923]
leaky weights: [[-3.06 16.89 -2.64]] | test ROC-AUC 0.810

The base models from Step 1 were fitted on the training set, and here they predict the same rows. The forest scores 0.99 on its own training rows, so the meta-learner trusts it heavily and gives the other two models negative weights. On the test set, the forest is not nearly that good, and the leaky stack scores worse than any single base model.

Step 5 — Build the meta-features out of fold

Section titled “Step 5 — Build the meta-features out of fold”
from sklearn.model_selection import cross_val_predict
out_of_fold = np.column_stack([
cross_val_predict(m, Xc_train, yc_train, cv=cv5, method="predict_proba")[:, 1]
for _, m in base_models
])
print("out-of-fold AUC of each model:", [
round(roc_auc_score(yc_train, out_of_fold[:, j]), 3) for j in range(3)
])
honest = LogisticRegression().fit(out_of_fold, yc_train)
honest_auc = roc_auc_score(yc_test, honest.predict_proba(test_meta)[:, 1])
print("honest weights:", honest.coef_.round(2), f"| test ROC-AUC {honest_auc:.3f}")
same = np.allclose(honest.coef_, stack.final_estimator_.coef_)
print("same as StackingClassifier:", same)
Output
out-of-fold AUC of each model: [0.813, 0.834, 0.841]
honest weights: [[2.14 2.03 2.62]] | test ROC-AUC 0.840
same as StackingClassifier: True

cross_val_predict returns, for each training row, the prediction of a model fitted on the other 4 folds. The out-of-fold AUCs look like real test AUCs, so the meta-learner learns sensible weights. The weights equal those of StackingClassifier from Step 3, because it uses the same folds and the same procedure. This is what cv does inside the stack.

Common mistakes:

  • Training the meta-learner on in-sample predictions. Overfit models get huge weights, and the stack fails on new data. Always use out-of-fold predictions (cv in StackingClassifier).
  • Using voting="hard" when you need probabilities, for ranking, ROC-AUC or a custom threshold. Use voting="soft".
  • Soft voting with a model whose probabilities are poorly calibrated, such as an SVM’s decision values turned into probabilities. One overconfident member dominates the average. Calibrate it (module 36) or give it a lower weight.

Example 7 — Compare every model on the same folds

Section titled “Example 7 — Compare every model on the same folds”

Goal: Recommend one churn model to the retention team. Evaluate ten models on the same 5 stratified folds, report ROC-AUC as mean ± standard deviation with the fit time, and check the gains fold by fold.

from sklearn.ensemble import BaggingClassifier, HistGradientBoostingClassifier
candidates = {
"logistic regression": base_models[0][1],
"decision tree": make_pipeline(
one_hot, DecisionTreeClassifier(max_depth=5, random_state=42)
),
"bagging": make_pipeline(one_hot, BaggingClassifier(
DecisionTreeClassifier(min_samples_leaf=3), n_estimators=50, random_state=42
)),
"random forest": base_models[1][1],
"AdaBoost": make_pipeline(one_hot, AdaBoostClassifier(
DecisionTreeClassifier(max_depth=1), n_estimators=100, random_state=42
)),
"HistGradientBoosting": HistGradientBoostingClassifier(
learning_rate=0.05, max_iter=300, max_leaf_nodes=15, early_stopping=True,
categorical_features="from_dtype", random_state=42,
),
"XGBoost": XGBClassifier(
n_estimators=100, learning_rate=0.05, max_depth=4, subsample=0.8,
colsample_bytree=0.8, enable_categorical=True, random_state=42, n_jobs=1,
),
"LightGBM": base_models[2][1],
"soft voting": VotingClassifier(base_models, voting="soft"),
"stacking": StackingClassifier(
base_models, final_estimator=LogisticRegression(), cv=cv5
),
}
print(len(candidates), "candidates")
Output
10 candidates

Every candidate is a complete pipeline, so its preprocessing is refitted inside each fold and nothing leaks. cross_validate clones each model before fitting, so reusing the objects of Example 6 is safe. HistGradientBoosting with early_stopping=True holds out 10% of each training fold to choose its number of trees.

Step 2 — Cross-validate all of them on the same folds

Section titled “Step 2 — Cross-validate all of them on the same folds”
from sklearn.model_selection import cross_validate
rows, fold_auc = [], {}
for name, model in candidates.items():
res = cross_validate(model, X_c, y_c, cv=cv5, scoring="roc_auc")
fold_auc[name] = res["test_score"]
rows.append({"model": name, "mean": res["test_score"].mean(),
"std": res["test_score"].std(), "fit": res["fit_time"].mean()})
board = pd.DataFrame(rows).sort_values("mean", ascending=False)
for r in board.itertuples():
print(f"{r.model:<21} ROC-AUC {r.mean:.3f} ± {r.std:.3f} | fit {r.fit:.2f}s")
Output
XGBoost ROC-AUC 0.849 ± 0.010 | fit 0.03s
LightGBM ROC-AUC 0.849 ± 0.008 | fit 0.03s
stacking ROC-AUC 0.847 ± 0.010 | fit 1.52s
HistGradientBoosting ROC-AUC 0.847 ± 0.007 | fit 0.06s
soft voting ROC-AUC 0.845 ± 0.010 | fit 0.28s
AdaBoost ROC-AUC 0.844 ± 0.010 | fit 0.20s
random forest ROC-AUC 0.836 ± 0.010 | fit 0.23s
bagging ROC-AUC 0.820 ± 0.010 | fit 0.53s
logistic regression ROC-AUC 0.814 ± 0.018 | fit 0.02s
decision tree ROC-AUC 0.804 ± 0.005 | fit 0.02s

The same cv5 object gives every model the same 5 folds of all 5,000 customers. The fit time is the mean per fold, in seconds; it changes from run to run and from machine to machine. The four boosting models and the two combinations sit within 0.005 of each other, inside one standard deviation. The forest is a little behind, plain bagging further, and the single tree last.

folds = pd.DataFrame(fold_auc)
gain = folds.sub(folds["logistic regression"], axis=0) # paired: same customers
summary = pd.DataFrame({
"mean_gain": gain.mean(),
"folds_won": (gain > 0).sum(),
}).drop("logistic regression")
print(summary.sort_values("mean_gain", ascending=False).round(3))
print("LightGBM minus stacking per fold:",
(folds["LightGBM"] - folds["stacking"]).round(3).to_list())
Output
mean_gain folds_won
XGBoost 0.035 5
LightGBM 0.035 5
stacking 0.033 5
HistGradientBoosting 0.032 5
soft voting 0.031 5
AdaBoost 0.030 5
random forest 0.021 5
bagging 0.006 3
decision tree -0.010 1
LightGBM minus stacking per fold: [-0.002, 0.0, 0.002, 0.008, 0.001]

Subtracting fold by fold removes the difficulty of each fold, which affects all models alike. Every boosting model beats the logistic regression on all 5 folds, by about 0.03 AUC: a real gain. The differences among the top models are tiny and change sign from fold to fold, so they are noise. Recommendation: LightGBM (or HistGradientBoosting). It is in the top group, trains in a fraction of a second and is one model to maintain. The stack costs about 50 times more fit time for no measurable gain.

Common mistakes:

  • Creating a new splitter with a different seed for each model, or none at all. The models then face different folds, and part of each difference is luck.
  • Declaring a winner by the third decimal of the mean. Look at the standard deviation and the paired differences first.
  • Reporting fit time from one run as a fact. Time depends on the machine, the load and the thread settings. Compare orders of magnitude.
Mistake Symptom Fix
Bagging a stable model (linear regression, KNN with large k) the bag scores the same as one model bag high-variance models such as deep trees
RandomForestRegressor() with default max_features the forest is no better than bagging try max_features 0.3–0.6; choose by OOB or CV
OOB score with few trees UserWarning: Some inputs do not have OOB scores use 50+ trees
Tuning on the test set (max_features, number of trees, early stopping) the test score drops on new data use OOB, a validation split or CV; read the test score once
Gradient boosting with a high learning rate and many trees the test error rises after an early minimum lower learning_rate; use early stopping
max_iter=100 with learning_rate=0.03 underfitting; the model has not converged raise max_iter, let early stopping cut it
LightGBM without verbose=-1 [LightGBM] [Info] lines and warnings in the terminal and the logs pass verbose=-1
No seed or default threads in XGBoost/LightGBM results or timings change between runs random_state=42, n_jobs=1 (or a fixed number)
subsample=0.8 in LightGBM without subsample_freq no row subsampling happens add subsample_freq=1
Hard voting when you need probabilities AttributeError on predict_proba; no ROC-AUC voting="soft"
Meta-learner trained on in-sample predictions a huge weight on the forest; the stack scores below its members out-of-fold predictions: StackingClassifier(cv=5)
A complex meta-learner (a forest) on 3 meta-features the stack overfits logistic or ridge regression as final_estimator
Different CV splits per model rankings change when you rerun one splitter object for every model
An ensemble whose members correlate at 0.95+ no gain over the best member add a different model type, or keep the best single model
  • Reliable hardware and distributed systems: aircraft and spacecraft computers run the same calculation on three units and take the majority vote (triple modular redundancy). Database clusters accept a write when a majority of replicas agree.
  • Search and recommendations: web search engines rank results with gradient-boosted trees (LambdaMART). LightGBM and XGBoost have ranking objectives for exactly this.
  • Weather forecasting: forecast centers run the same model 50 times from slightly different starting conditions and publish the average and the spread. That ensemble mean beats any single run.
  • Software tooling: spam and fraud filters combine many rules and models with weighted votes. Benchmark tools resample timings with the bootstrap to report a stable average and a confidence interval.
  • An ensemble combines base learners. It wins when the learners are good and their errors differ. The variance of an average is ρ σ2+(1−ρ) σ2/M\rho\,\sigma^2 + (1-\rho)\,\sigma^2 / M: more models lower the second term, and only diversity lowers the first.
  • Bagging trains the same high-variance model on bootstrap samples and averages them. About 36.8% of the rows are out of bag for each model, which gives the free OOB score.
  • A random forest is bagging plus feature subsampling. max_features lowers the correlation of the trees. The regressor’s default (1.0) is plain bagging.
  • Boosting builds small models in sequence. AdaBoost reweights the misclassified rows. Gradient boosting fits each tree to the residuals (the negative gradient of the loss) and adds it with a learning rate.
  • A smaller learning rate needs more trees and usually generalizes better. Fix the learning rate and let early stopping choose the number of trees on a validation split.
  • HistGradientBoosting, XGBoost and LightGBM are fast histogram-based boosters with native missing values and categories. Fix random_state and the threads, and pass verbose=-1 to LightGBM.
  • Hard voting counts labels; soft voting averages probabilities and is usually better. Stacking learns the combination with a meta-learner trained on out-of-fold predictions; cv prevents the leak.
  • Compare models on the same folds, with mean ± standard deviation and paired differences, and weigh the fit time. Keep the simpler model when the gain is within the noise.

Q1. 25 models each have an error standard deviation of 10. Their errors correlate at ρ=0.5\rho = 0.5. What is the error standard deviation of their average, and what is the limit as you add more models?

Answer

The variance is 0.5⋅100+0.5⋅100/25=50+2=520.5 \cdot 100 + 0.5 \cdot 100 / 25 = 50 + 2 = 52, so the standard deviation is 52≈7.2\sqrt{52} \approx 7.2. With infinitely many models, the second term vanishes and the variance falls to ρ σ2=50\rho\,\sigma^2 = 50, a standard deviation of about 7.1. Adding models barely helps; only lower correlation would.

Q2. What share of the distinct training rows does one bootstrap sample contain, and what are the other rows used for?

Answer

About 63.2%, because the chance that a row is never drawn in nn draws is (1−1/n)n≈e−1≈36.8%(1 - 1/n)^n \approx e^{-1} \approx 36.8\%. The rows that a model did not see are its out-of-bag rows. Each training row is predicted by the models that did not see it, and those predictions give the out-of-bag score, an estimate of the test score without a separate validation set.

Q3. How does a random forest differ from bagged decision trees, and why does the difference help?

Answer

A random forest also subsamples the features: each split may choose only among max_features random features. Strong features can then not dominate the top of every tree, so the trees differ more and their errors correlate less. That lowers the ρ σ2\rho\,\sigma^2 floor of the average’s variance. Each tree is a little worse, but the average is better.

Q4. Bagging lowers variance and boosting lowers bias. Which base learners does each one use, and why?

Answer

Bagging uses deep trees: low bias and high variance. Averaging removes much of the variance and keeps the low bias. Boosting uses shallow trees (stumps to depth 6): high bias and low variance. Each new tree corrects part of the remaining error, so the bias falls step by step. Deep trees in boosting would overfit the residuals quickly.

Q5. In gradient boosting with squared error, what is the target of the third tree?

Answer

The residuals of the model after two trees: yi−F2(xi)y_i - F_2(\mathbf{x}_i), where F2=F0+νh1+νh2F_2 = F_0 + \nu h_1 + \nu h_2 and F0F_0 is the mean. These residuals are the negative gradient of the squared-error loss with respect to the predictions. The third tree is fitted to them, and ν\nu times its prediction is added.

Q6. You halve the learning rate of a gradient boosting model. What happens to the best number of trees, and how do you find it without the test set?

Answer

It rises, because each tree now corrects half as much. It often rises less than in proportion: in Example 4, a learning rate 3 times smaller needed about 2 to 3 times more trees. Find it with early stopping on a validation split of the training data (early_stopping=True with n_iter_no_change in HistGradientBoosting, early_stopping_rounds with eval_set in XGBoost, the lgb.early_stopping callback in LightGBM), or with cross-validation and staged_predict.

Q7. Three classifiers predict churn probabilities 0.9, 0.3 and 0.4 for one customer. What do hard voting and soft voting predict, with a threshold of 0.5?

Answer

Hard voting turns the probabilities into labels first: 1, 0, 0. The majority says 0, no churn. Soft voting averages the probabilities: (0.9+0.3+0.4)/3≈0.53(0.9 + 0.3 + 0.4) / 3 \approx 0.53, which is above 0.5, so it predicts 1, churn. Soft voting lets the confident first model outweigh two unsure ones.

Q8. Why does StackingClassifier use cv to build the meta-features, and what goes wrong without it?

Answer

Without cv, the meta-features would be predictions of base models on their own training rows. Flexible models such as forests predict those rows almost perfectly, so the meta-learner gives them huge weights. On new data they are much worse, and the stack fails. With cv, each meta-feature comes from a model that did not see that row, so the meta-features look like predictions on new data and the weights are honest. Example 6 showed a test ROC-AUC of 0.810 with the leak and 0.840 without it.

Q9. Model A scores ROC-AUC 0.849 ± 0.008 and model B 0.847 ± 0.010 on the same 5 folds. A wins on 3 folds and loses on 2. A trains in 0.03 s per fold, B in 2.4 s. Which do you deploy?

Answer

A. The difference of 0.002 is far smaller than the fold spread, and the paired comparison is mixed (3 to 2), so the two models perform the same within the noise. A is 80 times faster to train and is probably simpler to maintain. Choose the simpler, faster model when the gain is not measurable.

Q10. Name three situations where you would not use an ensemble.

Answer

Any three of: the signal is close to linear, so a regularized linear model matches the trees (the diabetes data); the dataset is small, so the CV spread hides any gain; the candidate members are highly correlated; the model must be explainable line by line (credit, medicine); prediction latency or memory is tight; the extra maintenance of several models is not worth a tiny gain.

Your progress

0 / 4 done

  • Exercises: 26 exercises on bootstrap samples, bagging, OOB scores, random forests, AdaBoost, gradient boosting by hand, early stopping, XGBoost, LightGBM, voting, stacking and fair comparisons, with hints and full solutions.
  • Mini-project: choose and defend an ensemble for house prices with a fair cross-validated comparison.
  • Cheat sheet: every ensemble class, its key hyperparameters and the comparison recipe on one page.
  • Next module: 39. Unsupervised learning finds structure without a target: clustering with k-means, DBSCAN and Gaussian mixtures, PCA, t-SNE, UMAP and anomaly detection with Isolation Forest (itself an ensemble of random trees).