Skip to content

38. Ensembles — Cheat sheet

The essentials of module 38 on one page. Every runnable block on this page is checked against its output. The blocks share one session:

import lightgbm as lgb
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import (
AdaBoostClassifier,
BaggingRegressor,
GradientBoostingRegressor,
HistGradientBoostingClassifier,
RandomForestRegressor,
StackingClassifier,
VotingClassifier,
)
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, root_mean_squared_error
from sklearn.model_selection import (
StratifiedKFold,
cross_val_predict,
cross_validate,
train_test_split,
)
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from threadpoolctl import threadpool_limits
from xgboost import XGBClassifier
threadpool_limits(limits=1) # whole script: 1 thread for OpenMP and BLAS
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()
X_train, X_test = X_train.fillna(medians), X_test.fillna(medians)
customers = pd.read_csv("data/customers.csv")
CAT = ["region", "plan", "contract", "payment_method"]
NUM = ["age", "has_autopay", "tenure_months", "monthly_charges", "total_charges",
"support_tickets", "logins_last_30d", "avg_session_minutes"]
X_c = customers[CAT + NUM].astype({c: "category" for c in CAT})
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
)
one_hot = ColumnTransformer([
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), CAT),
("num", SimpleImputer(strategy="median"), NUM),
])
I want to… Use…
average many copies of a high-variance model BaggingRegressor(DecisionTreeRegressor(), n_estimators=50)
a free validation score for bagging or a forest oob_score=True, then .oob_score_, .oob_prediction_
decorrelate the trees of a forest RandomForestRegressor(max_features=0.33) (default 1.0 is bagging)
add trees to a fitted forest warm_start=True, then set_params(n_estimators=k).fit(...)
boost stumps by reweighting rows AdaBoostClassifier(DecisionTreeClassifier(max_depth=1))
gradient boosting, small data GradientBoostingRegressor(learning_rate=0.05, n_estimators=300, max_depth=3)
gradient boosting, fast, blanks and categories HistGradientBoostingClassifier(categorical_features="from_dtype")
the error after each tree model.staged_predict(X), staged_predict_proba(X)
stop adding trees automatically early_stopping=True, n_iter_no_change=20 (HistGB)
XGBoost with early stopping XGBClassifier(early_stopping_rounds=50, eval_metric="auc"), fit(..., eval_set=[(X_val, y_val)])
LightGBM with early stopping fit(..., eval_X=X_val, eval_y=y_val, callbacks=[lgb.early_stopping(50)])
silence LightGBM verbose=-1
reproducible XGBoost / LightGBM random_state=42, n_jobs=1
row subsampling in LightGBM subsample=0.8, subsample_freq=1
combine labels by majority VotingClassifier(models, voting="hard")
combine probabilities VotingClassifier(models, voting="soft", weights=[...])
learn the combination StackingClassifier(models, final_estimator=LogisticRegression(), cv=5)
out-of-fold predictions by hand cross_val_predict(model, X, y, cv=cv, method="predict_proba")
compare models fairly one StratifiedKFold(5, shuffle=True, random_state=42) for all; cross_validate
limit threads for the whole script threadpool_limits(limits=1) after importing scikit-learn (caps OpenMP and BLAS)
limit OpenMP threads in one block with threadpool_limits(limits=1, user_api="openmp"):
Family Base learners Built Combined by Reduces Typical base model
Bagging / random forest same model, bootstrap samples (+ feature subsets) in parallel mean or vote variance deep tree
Boosting same model, each fits the previous mistakes in sequence weighted sum bias stump to depth-6 tree
Voting different models, same data in parallel mean of probabilities or labels variance (if diverse) any
Stacking different models, same data in parallel + a meta-learner learned weights on out-of-fold predictions both, if diverse any; simple meta-learner

Variance of an average of MM models with error variance σ2\sigma^2 and error correlation ρ\rho:

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

More models lower the second term; only diversity (lower ρ\rho) lowers the first.

Fact Value
share of distinct rows in a bootstrap sample 1−(1−1/n)n≈63.2%1 - (1 - 1/n)^n \approx 63.2\%
out-of-bag rows per model about 36.8%
OOB predictions per row with BB models about 0.368 B0.368\,B
RandomForestRegressor default max_features 1.0 (all features: bagging)
RandomForestClassifier default max_features "sqrt"
more trees never overfit; slower; gains flatten
bag = BaggingRegressor(DecisionTreeRegressor(), n_estimators=50, oob_score=True,
random_state=42).fit(X_train, y_train)
forest = RandomForestRegressor(n_estimators=100, max_features=0.33, oob_score=True,
random_state=42).fit(X_train, y_train)
for name, model in [("bagging", bag), ("forest", forest)]:
rmse = root_mean_squared_error(y_test, model.predict(X_test))
print(f"{name:<8} OOB R² {model.oob_score_:.3f} | test RMSE {rmse:,.0f}")
Output
bagging OOB R² 0.864 | test RMSE 106,163
forest OOB R² 0.874 | test RMSE 97,135

Gradient boosting with squared error, by hand (this is all GradientBoostingRegressor does for that loss):

lr, pred = 0.1, np.full(len(y_train), y_train.mean()) # F0 = mean
for _ in range(3):
tree = DecisionTreeRegressor(max_depth=3, random_state=42)
tree.fit(X_train, y_train - pred) # fit the residuals
pred += lr * tree.predict(X_train) # F_m = F_{m-1} + lr * h_m
gbr = GradientBoostingRegressor(n_estimators=3, learning_rate=0.1, max_depth=3,
random_state=42).fit(X_train, y_train)
print(np.allclose(gbr.predict(X_train), pred))
Output
True
Setting Raise it → Lower it →
learning_rate fewer trees needed; overfits sooner more trees needed; usually slightly better
n_estimators / max_iter lower training error; past the optimum, overfitting underfitting
max_depth, max_leaf_nodes, num_leaves more interactions per tree; overfits weaker trees, more of them
min_samples_leaf, min_child_samples smoother, less overfitting fits small groups, noise
subsample < 1, colsample_bytree < 1 — more randomness, less variance, slower convergence
l2_regularization, reg_lambda smaller leaf values, less overfitting —

AdaBoost: weighted error ε\varepsilon, stump weight α=ln⁡1−εε\alpha = \ln\frac{1-\varepsilon}{\varepsilon} (2 classes, learning rate 1), misclassified rows’ weights × eαe^{\alpha}, then rescale.

HistGradientBoosting, XGBoost and LightGBM

Section titled “HistGradientBoosting, XGBoost and LightGBM”
Idea HistGradientBoosting XGBoost LightGBM
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
rows per leaf min_samples_leaf min_child_weight min_child_samples
L2 penalty l2_regularization reg_lambda reg_lambda
row sampling — subsample subsample + subsample_freq=1
column sampling max_features colsample_bytree colsample_bytree
categories categorical_features="from_dtype" enable_categorical=True category dtype, automatic
missing values native native native
early stopping early_stopping=True, n_iter_no_change, validation_fraction early_stopping_rounds + eval_set in fit lgb.early_stopping(n) + eval_X, eval_y
trees used to predict n_iter_ (includes the last n_iter_no_change trees that did not improve; no rollback) best_iteration + 1 (more trees are stored) best_iteration_
seed / threads / quiet random_state / OpenMP / default quiet random_state / n_jobs / verbose=False in fit random_state / n_jobs / verbose=-1
X_fit, X_val, y_fit, y_val = train_test_split(
Xc_train, yc_train, test_size=0.2, stratify=yc_train, random_state=42
)
hgb = HistGradientBoostingClassifier(
learning_rate=0.05, max_iter=1000, early_stopping=True, n_iter_no_change=30,
categorical_features="from_dtype", random_state=42,
).fit(Xc_train, yc_train)
xgb = XGBClassifier(
n_estimators=1000, learning_rate=0.05, max_depth=4, enable_categorical=True,
early_stopping_rounds=50, eval_metric="auc", random_state=42, n_jobs=1,
).fit(X_fit, y_fit, eval_set=[(X_val, y_val)], verbose=False)
lgbm = lgb.LGBMClassifier(
n_estimators=1000, learning_rate=0.05, num_leaves=15, random_state=42,
n_jobs=1, verbose=-1,
).fit(X_fit, y_fit, eval_X=X_val, eval_y=y_val, eval_metric="auc",
callbacks=[lgb.early_stopping(50, verbose=False)])
kept = {"hgb": hgb.n_iter_, "xgb": xgb.best_iteration + 1, "lgbm": lgbm.best_iteration_}
for name, model in [("hgb", hgb), ("xgb", xgb), ("lgbm", lgbm)]:
auc = roc_auc_score(yc_test, model.predict_proba(Xc_test)[:, 1])
print(f"{name:<5} trees used {kept[name]:>3} | test ROC-AUC {auc:.3f}")
Output
hgb trees used 91 | test ROC-AUC 0.830
xgb trees used 68 | test ROC-AUC 0.836
lgbm trees used 45 | test ROC-AUC 0.837
Hard voting Soft voting Stacking
combines labels probabilities out-of-fold predictions
weights fixed (weights=) fixed (weights=) learned by final_estimator
predict_proba no yes yes
extra cost none none cv + 1 fits per base model
leakage risk none none high without cv
members = [
("logreg", make_pipeline(
ColumnTransformer([
("cat", OneHotEncoder(handle_unknown="ignore"), CAT),
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()),
NUM),
]),
LogisticRegression(max_iter=1000),
)),
("tree", make_pipeline(
one_hot, DecisionTreeClassifier(max_depth=5, random_state=42)
)),
("lgbm", lgb.LGBMClassifier(n_estimators=100, learning_rate=0.05, num_leaves=15,
random_state=42, n_jobs=1, verbose=-1)),
]
cv5 = StratifiedKFold(5, shuffle=True, random_state=42)
soft = VotingClassifier(members, voting="soft")
stack = StackingClassifier(members, final_estimator=LogisticRegression(), cv=cv5)
for name, model in [("soft voting", soft), ("stacking", stack)]:
model.fit(Xc_train, yc_train)
auc = roc_auc_score(yc_test, model.predict_proba(Xc_test)[:, 1])
print(f"{name:<11} ROC-AUC {auc:.3f}")
print("meta weights:", stack.final_estimator_.coef_.round(2))
Output
soft voting ROC-AUC 0.834
stacking ROC-AUC 0.837
meta weights: [[2.49 0.83 3.4 ]]

The same meta-features by hand (what cv does inside the stack):

oof = np.column_stack([
cross_val_predict(m, Xc_train, yc_train, cv=cv5, method="predict_proba")[:, 1]
for _, m in members
])
meta = LogisticRegression().fit(oof, yc_train)
print(np.allclose(meta.coef_, stack.final_estimator_.coef_))
Output
True
cv = StratifiedKFold(5, shuffle=True, random_state=42) # one splitter for all
scores = {}
for name, model in [("tree", members[1][1]), ("lgbm", members[2][1])]:
res = cross_validate(model, X_c, y_c, cv=cv, scoring="roc_auc")
scores[name] = res["test_score"]
print(f"{name:<5} {scores[name].mean():.3f} ± {scores[name].std():.3f}")
gain = scores["lgbm"] - scores["tree"] # paired: same customers per fold
print(f"lgbm wins {(gain > 0).sum()} of 5 folds, mean gain {gain.mean():.3f}")
Output
tree 0.804 ± 0.005
lgbm 0.847 ± 0.010
lgbm wins 5 of 5 folds, mean gain 0.043
  1. One splitter object, passed to every model.
  2. Every preprocessing step inside a pipeline.
  3. Report mean ± standard deviation.
  4. Check the paired fold differences before you call a winner.
  5. Weigh fit and prediction time; prefer the simpler model when the gain is within the noise.
  6. Read the test set once, for the chosen model.
Situation Choice
tabular data, any size, best accuracy HistGradientBoosting, LightGBM or XGBoost with early stopping
a strong default with little tuning RandomForest (max_features 0.3–0.6 for regression)
need an internal validation score for free a bagging model or forest with oob_score=True
a few very different good models soft voting; stacking if the gain survives a paired CV check
models that agree (correlation 0.95+) keep the best single model
near-linear signal, small data, explanations needed a regularized linear model; no ensemble
tight latency or memory one boosted model with few trees, or a linear model
  • RandomForestRegressor() defaults to max_features=1.0: plain bagging, no feature subsampling.
  • Bagging a stable model (linear regression) gains nothing; bag high-variance models.
  • An OOB score with few trees is noisy, and with very few trees some rows get no OOB prediction (a warning).
  • Never choose max_features, the number of trees or the early-stopping point with the test set.
  • The learning rate and the number of trees trade off: a smaller learning rate needs more trees, often fewer than in proportion (3 times smaller: about 2 to 3 times the trees in module 38).
  • HistGradientBoosting turns on early stopping automatically only above 10,000 rows (early_stopping="auto"). Set it explicitly on small data.
  • LightGBM ignores subsample unless subsample_freq ≥ 1, and logs to the terminal unless verbose=-1.
  • LightGBM 4.7 deprecates eval_set in fit; use eval_X and eval_y.
  • XGBoost 3 takes early_stopping_rounds and eval_metric in the constructor, not in fit.
  • Hard voting has no predict_proba, so no ROC-AUC and no custom threshold.
  • A meta-learner trained on in-sample predictions overweights the most overfit model. Use cv.
  • HistGradientBoosting uses all cores through OpenMP; on small tables, threadpool_limits(limits=1) after importing scikit-learn can be much faster. Without with, the limit holds for the whole process and also caps BLAS.
  • HistGradientBoosting early stopping does not roll back: n_iter_ includes the last n_iter_no_change trees that did not improve. XGBoost and LightGBM predict with the best iteration.
  • Fit times vary with the machine and the load. Compare orders of magnitude, not decimals.