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 lgbimport numpy as npimport pandas as pdfrom sklearn.compose import ColumnTransformerfrom sklearn.ensemble import ( AdaBoostClassifier, BaggingRegressor, GradientBoostingRegressor, HistGradientBoostingClassifier, RandomForestRegressor, StackingClassifier, VotingClassifier,)from sklearn.impute import SimpleImputerfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import roc_auc_score, root_mean_squared_errorfrom sklearn.model_selection import ( StratifiedKFold, cross_val_predict, cross_validate, train_test_split,)from sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import OneHotEncoder, StandardScalerfrom sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressorfrom threadpoolctl import threadpool_limitsfrom 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),])Quick lookup
Section titled “Quick lookup”| 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"): |
The three families
Section titled “The three families”| 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 models with error variance and error correlation :
More models lower the second term; only diversity (lower ) lowers the first.
Bagging, out-of-bag and random forests
Section titled “Bagging, out-of-bag and random forests”| Fact | Value |
|---|---|
| share of distinct rows in a bootstrap sample | |
| out-of-bag rows per model | about 36.8% |
| OOB predictions per row with models | about |
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}")bagging OOB R² 0.864 | test RMSE 106,163forest OOB R² 0.874 | test RMSE 97,135Boosting
Section titled “Boosting”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 = meanfor _ 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_mgbr = 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))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 , stump weight (2 classes, learning rate 1), misclassified rows’ weights × , 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}")hgb trees used 91 | test ROC-AUC 0.830xgb trees used 68 | test ROC-AUC 0.836lgbm trees used 45 | test ROC-AUC 0.837Voting and stacking
Section titled “Voting and stacking”| 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))soft voting ROC-AUC 0.834stacking ROC-AUC 0.837meta 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_))TrueFair comparison recipe
Section titled “Fair comparison recipe”cv = StratifiedKFold(5, shuffle=True, random_state=42) # one splitter for allscores = {}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 foldprint(f"lgbm wins {(gain > 0).sum()} of 5 folds, mean gain {gain.mean():.3f}")tree 0.804 ± 0.005lgbm 0.847 ± 0.010lgbm wins 5 of 5 folds, mean gain 0.043- One splitter object, passed to every model.
- Every preprocessing step inside a pipeline.
- Report mean ± standard deviation.
- Check the paired fold differences before you call a winner.
- Weigh fit and prediction time; prefer the simpler model when the gain is within the noise.
- Read the test set once, for the chosen model.
When to use which
Section titled “When to use which”| 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 |
Gotchas
Section titled “Gotchas”RandomForestRegressor()defaults tomax_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).
HistGradientBoostingturns on early stopping automatically only above 10,000 rows (early_stopping="auto"). Set it explicitly on small data.- LightGBM ignores
subsampleunlesssubsample_freq≥ 1, and logs to the terminal unlessverbose=-1. - LightGBM 4.7 deprecates
eval_setinfit; useeval_Xandeval_y. - XGBoost 3 takes
early_stopping_roundsandeval_metricin the constructor, not infit. - 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. HistGradientBoostinguses all cores through OpenMP; on small tables,threadpool_limits(limits=1)after importing scikit-learn can be much faster. Withoutwith, the limit holds for the whole process and also caps BLAS.HistGradientBoostingearly stopping does not roll back:n_iter_includes the lastn_iter_no_changetrees 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.