Knowledge / Artificial Intelligence and Data Science / Ensemble methods and gradient boosting

Ensemble methods and gradient boosting

Artificial Intelligence and Data Science (B.E./B.Tech) · Machine learning · free study notes for exams, placements and interviews

In short

An ensemble combines many models so that their collective prediction is better than any single one of them: bagging averages independently trained models to cut variance, boosting adds models in sequence so each one corrects the errors of the ones before it, and stacking learns how to blend different model families. Gradient boosting is the dominant form of boosting - it fits each new tree to the negative gradient (for squared loss, the residual) of a differentiable loss, and its implementations XGBoost, LightGBM and CatBoost win most tabular-data competitions and power real credit, fraud and ranking systems. The topic is examined in GATE DA (Data Science and AI) and in university ML papers as bagging-vs-boosting comparisons, AdaBoost weight updates and gradient-boosting derivations. In Indian hiring it appears constantly in data-science rounds at banks, NBFCs, fintechs, e-commerce and analytics firms, because credit scoring and fraud detection on tabular data are still solved with gradient-boosted trees rather than deep networks.

Explained

Why ensembles work

Bagging, pasting, random forests and out-of-bag error

  1. Bootstrap: draw n samples with replacement from n training rows. Each bootstrap contains about 63.2% distinct rows, because P(a given row is never picked) = (1 − 1/n)n → 1/e ≈ 0.368.
  2. Train one unpruned, high-variance base learner per bootstrap, in parallel.
  3. Aggregate: average for regression, majority vote (hard) or averaged probability (soft) for classification.
  4. Pasting is the same idea with sampling *without* replacement; random subspace samples features; random patches samples both.
  5. Out-of-bag (OOB) estimate: predict each row using only the ~36.8% of trees that never saw it - a free validation score, close to k-fold CV, so bagging can be tuned without a held-out set.
  6. Random forest adds feature subsampling at each split (typically √p features for classification, p/3 for regression) to decorrelate trees further. Extra Trees also randomises the split threshold, giving still lower variance and higher bias.
  7. Bagging mainly reduces variance and barely changes bias; it cannot fix an underfitting base learner.

Boosting: AdaBoost and the forward-stagewise view

Gradient boosting: the algorithm and its derivation outline

XGBoost, LightGBM, CatBoost - the modern libraries

Stacking, blending and voting

Interpretation, limits and practice

Key points

Formulas and examples

Variance of an average of M models Var = ρσ² + (1 − ρ)σ²/M — σ² = variance of one model's error, ρ = average pairwise correlation. ρ = 0 → σ²/M; ρ = 1 → σ². Shows why decorrelation matters more than count.
Bootstrap out-of-bag fraction P(row not in a bag) = (1 − 1/n)n → 1/e ≈ 0.3679; in-bag unique ≈ 63.21%.
AdaBoost err_m = Σᵢ wᵢ·1[yᵢ ≠ h_m(xᵢ)] / Σᵢ wᵢ; α_m = ½·ln((1 − err_m)/err_m); wᵢ ← wᵢ·e−α_m yᵢ h_m(xᵢ) / Z; F(x) = sign(Σ_m α_m h_m(x)) — y, h ∈ {−1, +1}, dimensionless.
Gradient boosting step rᵢm = −[∂L(yᵢ, F(xᵢ))/∂F(xᵢ)]_{F = F_{m−1}}; γ_{jm} = arg min_γ Σ_{i ∈ R_{jm}} L(yᵢ, F_{m−1}(xᵢ) + γ); F_m(x) = F_{m−1}(x) + ν Σ_j γ_{jm} 1[x ∈ R_{jm}] — ν ∈ (0,1] shrinkage, R_{jm} = leaf j of tree m.
Squared loss L = ½(y − F)² → r = y − F. Log loss L = −[y ln p + (1−y) ln(1−p)], p = σ(F) = 1/(1 + e−F) → r = y − p.
XGBoost tree objective Obj = Σᵢ [gᵢ f(xᵢ) + ½ hᵢ f(xᵢ)²] + γT + ½ λ Σ_j w_j²; w_j* = −G_j/(H_j + λ); Obj* = −½ Σ_j G_j²/(H_j + λ) + γT — G_j = Σ gᵢ, H_j = Σ hᵢ over leaf j, T = number of leaves.
XGBoost split gain Gain = ½[ G_L²/(H_L+λ) + G_R²/(H_R+λ) − (G_L+G_R)²/(H_L+H_R+λ) ] − γ — split only if Gain > 0.
Log-odds to probability F₀ = ln(p/(1 − p)); p = 1/(1 + e−F).

Example 1 - AdaBoost round, by hand. 10 rows, equal weights wᵢ = 0.1. A stump misclassifies 3 rows.

Example 2 - gradient boosting regression with squared loss, two rounds. y = (10, 12, 20, 22) for four flats' prices (₹ lakh); one feature "area", learning rate ν = 0.5; each tree is a stump splitting small-area rows {1,2} from large {3,4}.

Example 3 - XGBoost leaf weight and split gain. A node holds 4 rows with gᵢ = (−0.5, −0.4, 0.3, 0.6), hᵢ = (0.25, 0.24, 0.21, 0.24); λ = 1, γ = 0.2. Candidate split: rows 1-2 left, 3-4 right.

Example 4 - learning-rate / tree-count trade-off and early stopping. A fraud model on 2,00,000 UPI transactions, validation AUC:

learning_ratebest n_estimators (early stop)Validation AUCTrain time
0.31200.9181×
0.14200.9313×
0.059000.9347×
0.014,8000.93435×

Example 5 - majority vote versus a single model. 5 independent classifiers, each accuracy p = 0.70. Majority = at least 3 correct.

Bagging / Random forestBoosting (GBM, XGBoost)Stacking
TrainingParallel, independentSequential, dependentLevel-0 parallel, level-1 after
Base learnerDeep, low-bias high-varianceShallow, weak (stumps-depth 8)Any mix of families
Mainly reducesVarianceBias (then variance via shrinkage)Both, via learned weights
WeightingEqualLearned α / gradient stepsMeta-model coefficients
Overfits with more membersRarelyYes - needs early stoppingYes, if folds leak
Noise/outlier robustnessHighLow (chases hard rows)Medium
Free validationOOB scoreNo (needs validation set)Out-of-fold predictions
Typical accuracy on tabularGoodBestMarginally best, costly
# scikit-learn and XGBoost, as asked in practical exams
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, StackingClassifier
from sklearn.linear_model import LogisticRegression
import xgboost as xgb

rf = RandomForestClassifier(n_estimators=500, max_features='sqrt',
                            oob_score=True, n_jobs=-1, random_state=42).fit(X_tr, y_tr)
print(rf.oob_score_)                      # free validation estimate

clf = xgb.XGBClassifier(n_estimators=3000, learning_rate=0.05, max_depth=5,
                        subsample=0.8, colsample_bytree=0.8,
                        reg_lambda=1.0, min_child_weight=5,
                        eval_metric='auc', early_stopping_rounds=50)
clf.fit(X_tr, y_tr, eval_set=[(X_val, y_val)], verbose=False)
print(clf.best_iteration)                 # M chosen by early stopping

stack = StackingClassifier(estimators=[('rf', rf), ('gb', GradientBoostingClassifier())],
                           final_estimator=LogisticRegression(), cv=5)  # cv=5 -> out-of-fold, no leakage

Where it is used

Interview questions

Common mistakes

Related topics

Open in the Knowledge reader →Find jobs →