Jaber Notes · 8 of 16
Ensemble Methods
Bagging, random forests, AdaBoost, GBM, XGBoost, LightGBM, stacking.
Why combining models wins: the bias-variance view of bagging, random-forest feature randomization, AdaBoost's weight-update derivation, GBM as functional gradient descent, and the XGBoost/LightGBM tricks that dominate tabular ML.
Visual reference
Bias–variance tradeoff
Ensembles combine multiple weak learners into a strong one. This is the dominant approach in tabular ML competitions.
Table of contents
- Why ensembles work (theory)
- Bagging
- Random forest
- AdaBoost (derivation)
- Gradient boosting machines (GBM)
- XGBoost, LightGBM, CatBoost (modern GBDT)
- Stacking and blending
- Practical comparison and when to use what
1. Why ensembles work (theory)
1.1 Bias-variance view
Averaging reduces variance without increasing bias:
Let be models trained on different samples, each with expected prediction and variance . If the models are uncorrelated, the variance of their average:
Variance decreases by factor . Bias stays the same ( = for unbiased models).
In reality, models are correlated (same training distribution). If pairwise correlation is :
Floor is . To benefit from ensembling: maximize diversity (low ).
1.2 Wisdom of crowds
If each of classifiers is right with probability and errors are independent, majority vote is right with probability:
2. Bagging (Bootstrap Aggregating)
2.1 Algorithm (Breiman, 1996)
- For :
a. Draw a bootstrap sample of size by sampling with replacement from . b. Train a model on .
- Aggregate:
- Regression: .
- Classification: majority vote or average probabilities.
2.2 Out-of-bag (OOB) error
Each bootstrap sample includes ~63.2% of training points (). The remaining ~36.8% are out-of-bag (OOB).
Evaluate model on its OOB samples → free estimate of generalization without a separate validation set.
2.3 Pasting
Bagging without replacement (draw subsamples of size < n). Less variance reduction but more diversity per model.
3. Random Forest
3.1 Additional randomization over Bagging
Random forests (Breiman, 2001) = bagging of decision trees + random feature subsets at each split:
- At each node, choose the best split among a random subset of features (not all ).
- Default: for classification, for regression.
This reduces correlation among trees (key insight): trees trained on different features diverge more.
3.2 Why random features reduce correlation
Two trees grown on the same bootstrap without feature randomization will tend to split on the same strong features at the top → highly correlated → limited variance reduction.
With feature randomization: each tree sees different feature subsets → different splits → lower correlation → better ensemble.
3.3 Feature importance
Split-based importance (MDI — Mean Decrease in Impurity): sum of impurity reduction from splits on feature across all trees, weighted by sample count.
Permutation importance: permute values of feature in OOB samples; measure drop in accuracy. More reliable (MDI is biased toward high-cardinality features).
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance
rf = RandomForestClassifier(n_estimators=200, max_features='sqrt', oob_score=True)
rf.fit(X_train, y_train)
print("OOB score:", rf.oob_score_)
print("MDI importances:", rf.feature_importances_)
perm = permutation_importance(rf, X_val, y_val, n_repeats=10)
print("Permutation importances:", perm.importances_mean)3.4 Hyperparameters
| Param | Effect | Typical range |
|---|---|---|
n_estimators | More = better but diminishing returns | 100–1000 |
max_features | Reduce → less correlation, more bias | 'sqrt', 'log2', float |
max_depth | Limit depth of each tree | None (fully grown) or 5–20 |
min_samples_leaf | Smooth predictions | 1–20 |
bootstrap | OOB estimation | True |
4. AdaBoost (derivation)
4.1 Intuition
Boosting: train models sequentially, each one focusing on the mistakes of the previous.
AdaBoost (Freund & Schapire, 1997): maintain a weight distribution over samples; harder examples get higher weight.
4.2 Algorithm (binary, )
Initialize: for all .
For :
- Train weak learner on weighted distribution .
- Compute weighted error:
- Compute model weight (log odds of being correct):
Note: iff (better than random). Larger for more accurate learners.
- Update sample weights (increase weight of misclassified):
If correctly classified: → weight multiplied by . If misclassified: → weight multiplied by .
- Normalize: .
Final prediction:
4.3 AdaBoost minimizes exponential loss
It can be shown that AdaBoost is forward stagewise additive modeling with the exponential loss :
Minimizing this greedily → exactly the AdaBoost update. The exponential loss is sensitive to outliers (upweights them exponentially) — this is a weakness.
4.4 Training error bound
where is the "edge" (how much better than random). If each weak learner is slightly better than random (), error decays exponentially to zero.
5. Gradient Boosting Machines (GBM)
5.1 Key insight (Friedman, 2001)
Generalize boosting to arbitrary differentiable loss functions by framing it as gradient descent in function space.
Setup: train an ensemble additively:
where are weak learners (shallow trees) and are step sizes (learning rate).
5.2 Gradient in function space
At step , we want to minimize .
Functional gradient descent: the direction that decreases loss fastest is the negative functional gradient:
These are called pseudo-residuals. Fit the next tree to predict these pseudo-residuals (regression tree, even for classification).
5.3 GBM algorithm
Initialize: .
For :
- Compute pseudo-residuals: .
- Fit regression tree to .
- Find optimal leaf output values (line search or closed form per leaf).
- Update: , with shrinkage .
5.4 Loss functions and their pseudo-residuals
| Loss | Pseudo-residual | Use case | |
|---|---|---|---|
| Squared error | Regression | ||
| Absolute error | Robust regression | ||
| Huber | Hybrid MSE/MAE | Smooth threshold | Regression with outliers |
| Log-loss (deviance) | Binary classification | ||
| Multinomial deviance | Multiclass |
5.5 Regularization in GBM
- Shrinkage (learning rate ): smaller → more trees needed but better generalization. Typical: 0.01–0.1.
- Subsampling (stochastic GBM): build each tree on a random subsample of data (e.g., 50%–80%). Reduces correlation between trees, speeds up training.
- Tree constraints:
max_depth(3–8 typical),min_samples_leaf. - L1/L2 regularization on leaf weights (XGBoost feature).
6. XGBoost, LightGBM, CatBoost (modern GBDT)
6.1 XGBoost (Chen & Guestrin, 2016)
Second-order approximation of the loss: use both gradient (first order) and Hessian (second order) for more accurate leaf updates.
For tree structure with leaf outputs , the regularized objective at step :
where , , = number of leaves, = leaf count penalty, = L2 on leaf weights.
Optimal leaf output for leaf : , where , .
Split gain:
Key features:
- Weighted quantile sketch for approximate split finding (scalable).
- Column block data structure (efficient access).
- Missing value handling: learn default direction for missing values.
- Regularization:
alpha(L1),lambda(L2),gamma(min gain).
6.2 LightGBM
Innovations for speed on large datasets:
- Gradient-based One-Side Sampling (GOSS): keep instances with large gradients (they contribute more), randomly sample instances with small gradients (with upweighting).
- Exclusive Feature Bundling (EFB): bundle mutually exclusive sparse features (e.g., OHE columns) into one dense feature.
- Leaf-wise growth: grow the leaf that reduces loss the most (vs. level-wise in XGBoost). Faster convergence but can overfit — limit via
min_child_samples,num_leaves. - Result: 10–20× faster than XGBoost on large datasets.
6.3 CatBoost
Innovations for categorical features:
- Target statistics for categoricals with an ordered (time-based) scheme to prevent leakage within the training set.
- Oblivious trees: all nodes at the same depth use the same split. Faster prediction, regularization effect.
- Symmetric quantile binning.
6.4 Hyperparameter guide
| Parameter | XGBoost | LightGBM | Effect |
|---|---|---|---|
| Depth | max_depth | num_leaves | Complexity |
| LR | learning_rate | learning_rate | Step size |
| Regularization | alpha, lambda | reg_alpha, reg_lambda | Leaf penalty |
| Subsampling | subsample | bagging_fraction | Data sampling |
| Feature sampling | colsample_bytree | feature_fraction | Feature sampling |
| Min leaf | min_child_weight | min_child_samples | Leaf size |
import xgboost as xgb
model = xgb.XGBClassifier(
n_estimators=500, learning_rate=0.05, max_depth=6,
subsample=0.8, colsample_bytree=0.8, gamma=0,
reg_alpha=0.1, reg_lambda=1.0,
eval_metric='logloss', early_stopping_rounds=20,
random_state=42
)
model.fit(X_train, y_train, eval_set=[(X_val, y_val)], verbose=100)
import lightgbm as lgb
model = lgb.LGBMClassifier(
n_estimators=1000, learning_rate=0.02, num_leaves=63,
feature_fraction=0.8, bagging_fraction=0.8, bagging_freq=5,
reg_alpha=0.1, reg_lambda=0.1,
min_child_samples=20, random_state=42
)
model.fit(X_train, y_train,
eval_set=[(X_val, y_val)],
callbacks=[lgb.early_stopping(50, verbose=False)])7. Stacking and blending
7.1 Stacking (stacked generalization)
Train a meta-learner on the predictions of base models:
- Split training data into folds.
- For each fold, train all base models on other folds, predict on this fold.
- Collect out-of-fold predictions as meta-features.
- Train a meta-learner (often logistic regression or LightGBM) on these meta-features.
- At test time: predict with all base models, feed to meta-learner.
Prevents leakage: base model's predictions on training data are always made on data it hasn't seen.
from sklearn.ensemble import StackingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
estimators = [
('rf', RandomForestClassifier(n_estimators=100, random_state=0)),
('gbm', GradientBoostingClassifier(n_estimators=100, random_state=0)),
]
meta_model = LogisticRegression()
stacker = StackingClassifier(estimators=estimators, final_estimator=meta_model, cv=5)7.2 Blending
Simpler variant: use a holdout (not CV) to generate meta-features. Less data-efficient but faster.
7.3 Why stacking works
Different model classes have different biases. A meta-learner can learn which base model is better in which region of feature space, combining their strengths.
8. Practical comparison and when to use what
| Method | Bias | Variance | Speed | When |
|---|---|---|---|---|
| Single tree | High | High | Fast | Baseline / interpretability |
| Bagging | Same as base | Lower | Moderate | Base = high-variance (trees) |
| Random Forest | Slightly higher | Low | Moderate | Good default for tabular data |
| AdaBoost | Lower | Slightly higher | Moderate | Interpretable boosting |
| GBM | Low | Low | Slower | Strong performance |
| XGBoost/LightGBM | Low | Low | Fast (LGB faster) | Default for tabular ML |
| Stacking | Lowest | Low | Most expensive | Competitions, maximum accuracy |
Rule of thumb for tabular data:
- Start with LightGBM or XGBoost.
- Tune hyperparameters (especially learning_rate, num_leaves/max_depth, subsampling).
- Use early stopping with validation set.
- Add stacking as final step if marginal gains matter.
*File: notes/08_ensemble_methods.md — next: notes/09_unsupervised_learning.md*