পাঠ ২৪ · ৪৫-এর মধ্যে · মডিউল ৩

XGBoost — Kaggle জেতার অস্ত্র

XGBoost in depth — second-order boosting
৯ মিনিট পড়া মাঝারি · Intermediate xgboost library

এই পাঠে যা শিখবেন

  • XGBoost-এর regularized objective — গণিতিক formulation
  • Second-order Taylor expansion — gradient + hessian
  • Closed-form optimal leaf weight ও gain calculation
  • Sparsity-aware split finding — missing data automatic
  • Production hyperparameters — max_depth, eta, regularization

১ · XGBoost কেন আলাদা

Vanilla GBM idea ১৯৯৯ থেকেই। XGBoost (Chen, ২০১৪)-এর contribution চারটি দিকে:

  • Mathematical: first-order → second-order Taylor expansion।
  • Regularization: objective-এ leaf count + leaf weight L2।
  • Engineering: sparsity-aware, cache-aware, parallel।
  • Practical: early stopping, custom loss, missing data।

ফল — বহু Kaggle competition (KDDCup ২০১৫, Higgs Boson ২০১৪) winning solutions।

২ · Regularized Objective

Standard GBM:

$$\mathcal{O} = \sum_{i=1}^{n} L(y_i, \hat{y}_i)$$

XGBoost যোগ করে regularization term:

$$\mathcal{O} = \sum_{i} L(y_i, \hat{y}_i) + \sum_{t} \Omega(h_t)$$

যেখানে:

$$\Omega(h) = \gamma T + \frac{1}{2} \lambda \sum_{j=1}^{T} w_j^2$$

  • $T$ — tree-এর leaf-এর সংখ্যা।
  • $w_j$ — leaf $j$-এর prediction weight।
  • $\gamma$ — leaf-count penalty (sparsity)।
  • $\lambda$ — leaf-weight L2 penalty (smoothness)।

Both terms — overfitting fight। $\gamma$ tree size control, $\lambda$ extreme weight prevent।

৩ · Second-order Taylor Expansion

Iteration $t$-এ — $\hat{y}^{(t)} = \hat{y}^{(t-1)} + h_t(x)$। Loss-এর Taylor expansion:

$$L(y, \hat{y}^{(t-1)} + h_t) \approx L(y, \hat{y}^{(t-1)}) + g_i \cdot h_t(x_i) + \frac{1}{2} H_i \cdot h_t(x_i)^2$$

যেখানে:

  • $g_i = \partial_{\hat{y}} L(y_i, \hat{y}^{(t-1)})$ — first-order gradient।
  • $H_i = \partial^2_{\hat{y}} L(y_i, \hat{y}^{(t-1)})$ — second-order hessian।

Constant terms drop করে — iteration $t$-এর objective:

$$\tilde{\mathcal{O}}^{(t)} = \sum_i \left[g_i h_t(x_i) + \frac{1}{2} H_i h_t(x_i)^2\right] + \Omega(h_t)$$

৪ · Optimal Leaf Weight — closed form

Tree structure fixed ধরে — leaf $j$-তে যেসব samples (call it $I_j$):

$$\tilde{\mathcal{O}}^{(t)} = \sum_{j=1}^{T} \left[\left(\sum_{i \in I_j} g_i\right) w_j + \frac{1}{2} \left(\sum_{i \in I_j} H_i + \lambda\right) w_j^2\right] + \gamma T$$

$w_j$-এর সাপেক্ষে minimize — quadratic-এর minimum:

$$w_j^* = -\frac{G_j}{H_j + \lambda}, \quad G_j = \sum_{i \in I_j} g_i, \quad H_j = \sum_{i \in I_j} H_i$$

এ থেকে নিদিষ্ট tree structure-এর objective:

$$\tilde{\mathcal{O}}^*(T) = -\frac{1}{2} \sum_{j=1}^{T} \frac{G_j^2}{H_j + \lambda} + \gamma T$$

Newton's method analog

$w^* = -G/(H+\lambda)$ — Newton update। GBM (first-order) — শুধু $-\eta G$। XGBoost — adaptive step size, faster convergence, better stability।

৫ · Split Finding — Gain

একটি node-কে split করলে — left ($I_L$) ও right ($I_R$) child। Gain:

$$\text{Gain} = \frac{1}{2}\left[\frac{G_L^2}{H_L + \lambda} + \frac{G_R^2}{H_R + \lambda} - \frac{(G_L + G_R)^2}{H_L + H_R + \lambda}\right] - \gamma$$

$\gamma$ subtract — split worth-এর threshold। Negative gain হলে — split rejected।

Algorithm: প্রতি feature ও threshold-এ Gain calculate, সর্বোচ্চ Gain-এর split বাছা। Histogram-based approximation — feature values discretize করে fast।

৬ · Sparsity-aware Split Finding

Missing values, sparse features (one-hot)-এ XGBoost elegant:

  • প্রতি split-এ — non-missing samples-এ best split বাছা।
  • Missing samples-এর জন্য — left না right বাছা যেদিকে gain বেশি।
  • "Default direction" tree-এ store।
  • Test-এ missing → default direction।

No imputation, no surrogate — automatic, learned।

XGBoost — second-order objective + regularization ১. F_(t-1)(x) previous prediction init: log(p/(1-p)) ২. Compute g, H g_i = ∂L/∂F H_i = ∂²L/∂F² per-sample 1st & 2nd order ৩. Build tree (Gain max) Gain = ½(G_L²/H_L + G_R²/H_R − G²/H) − γ split if Gain > 0 ৪. Optimal leaf weights w_j* = −G_j / (H_j + λ) closed form — Newton step ৫. F_t = F_(t-1) + η · h_t η = 0.05-0.1 (shrinkage) repeat for M iterations / early-stop Engineering: histogram split, sparsity-aware, parallel column-block, GPU support Math + engineering = production-grade boosting
XGBoost-এর core — second-order optimization + regularization + heavy engineering। Each iteration: gradient + hessian → optimal tree → weights → shrinkage update।

৭ · Python — XGBoost API

Python · xgboost
import xgboost as xgb
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split

X, y = load_breast_cancer(return_X_y=True)
Xt, Xv, yt, yv = train_test_split(X, y, test_size=0.3, random_state=0)

model = xgb.XGBClassifier(
    n_estimators=2000,
    learning_rate=0.05,
    max_depth=4,
    min_child_weight=3,
    subsample=0.8,
    colsample_bytree=0.8,
    reg_lambda=1.0,           # L2 on leaf weights
    reg_alpha=0.0,            # L1
    gamma=0.1,                # min split gain
    objective='binary:logistic',
    eval_metric='logloss',
    early_stopping_rounds=50,
    random_state=0,
    n_jobs=-1
)

model.fit(Xt, yt, eval_set=[(Xv, yv)], verbose=False)

print(f"Best iteration:    {model.best_iteration}")
print(f"Train acc:         {model.score(Xt, yt):.4f}")
print(f"Val acc:           {model.score(Xv, yv):.4f}")

    
early_stopping_rounds=50 — validation score ৫০ rounds উন্নতি না হলে stop। best_iteration-এ-এর model production deploy। সাধারণত breast cancer-এ ৯৭-৯৮% val accuracy।

৮ · Hyperparameter — কী tune করবেন

Param Range Effect
learning_rate 0.01-0.3 Step size, smaller better, more trees দরকার
n_estimators 100-5000 Iterations; early stopping দিয়ে control
max_depth 3-10 Tree complexity; বেশি → overfit
min_child_weight 1-10 Leaf-এ minimum hessian sum
subsample 0.5-1.0 Row sampling — stochastic GBM
colsample_bytree 0.5-1.0 Column sampling — RF-like decorrelation
gamma 0-5 Min gain — prune aggressive
reg_lambda 0-10 L2 leaf weight regularization

৯ · কোথায় XGBoost dominant — কোথায় না

Dominant:

  • Tabular data (Kaggle, finance, healthcare records)।
  • Mid-size data (১০K-১০M samples)।
  • Mixed feature types।
  • Missing data prevalent।
  • Custom loss functions।

Suboptimal:

  • Image / audio / text — DL win।
  • Very high cardinality categorical — CatBoost better।
  • Extreme scale data (১০০M+) — LightGBM faster।
  • Real-time micro-second inference — too slow।
  • Online learning — re-training expensive।
XGBoost mature library — extensively tested। Production-এ first choice tabular-এ। কিন্তু "default-এ চালালেই কাজ" না — careful tuning expected।

ভাবনার প্রশ্ন

প্রতিটি প্রশ্ন নিজে কিছুক্ষণ ভাবুন — তারপর "→ উত্তর" চাপুন।

প্র ০১ Second-order Taylor expansion XGBoost-কে কেন এত better করে — প্রথম-order GBM-এর চেয়ে? Hessian-এর সরাসরি impact কী?

XGBoost-এর mathematical heart — second-order optimization। Practical impact বহুমুখী।

First-order vs second-order:

(১) GBM (first-order):

  • $F_{t+1} = F_t - \eta \nabla L$।
  • Linear approximation।
  • Step size $\eta$ — fixed, manual।
  • Slow convergence in curved regions।

(২) XGBoost (second-order):

  • $\Delta F = -G/(H+\lambda)$।
  • Quadratic approximation।
  • Step size — adaptive, automatic।
  • Newton's method analog।

Hessian-এর role:

  • Loss curvature — কত fast bend।
  • Flat region (low H) — large step OK।
  • Sharp region (high H) — small step careful।
  • Adaptive step — overshoot prevent।

Impact-1: Faster convergence:

  • Newton's method — quadratic convergence।
  • Gradient descent — linear convergence।
  • Practice — 30-50% fewer iterations।
  • Less computation, better accuracy।

Impact-2: Better split finding:

  • Gain formula — Hessian-aware।
  • Sample weight per Hessian — different importance।
  • Important samples — more precise splits।
  • Decision boundary sharper।

Impact-3: Loss-agnostic framework:

  • Custom loss — provide gradient + hessian।
  • Same engine works।
  • Quantile regression, Tweedie, Poisson — extensions easy।

Impact-4: Numerical stability:

  • $\lambda$ in denominator — divide-by-zero prevention।
  • Regularization built-in।
  • Production reliable।

Hessian for common losses:

  • Squared loss: $g = \hat{y} - y$, $H = 1$ (constant)।
  • Log loss: $g = p - y$, $H = p(1-p)$।
  • Multi-class: diagonal Hessian per class।

Constant Hessian implication:

  • Squared loss-এ $H = 1$ — XGBoost reduces to GBM-like।
  • $w^* = -G/(n+\lambda)$ — mean residual / regularized।
  • Slight improvement over GBM-এর mean।

Variable Hessian implication (log loss):

  • $H = p(1-p)$ — boundary near uncertain samples max।
  • Confident samples — low Hessian — discounted।
  • Boundary samples — high Hessian — leverage বেশি।
  • Decision boundary refinement smoother।

Trade-offs:

  • Hessian computation — extra compute (negligible)।
  • Hessian storage — memory cost।
  • Custom loss — Hessian derivation harder।

When second-order doesn't help:

  • Highly non-convex loss।
  • Hessian unstable (extreme values)।
  • $\lambda$ misspecified।

Connection to other methods:

  • L-BFGS — quasi-Newton for parameter optimization।
  • Natural Gradient — Fisher information-based।
  • K-FAC, Shampoo — modern NN second-order।
  • Common theme: curvature-aware updates।

Empirical evidence:

  • Chen & Guestrin (২০১৬) paper benchmarks।
  • Higgs Boson — 30% faster, 2% better accuracy।
  • YearPredictMSD — 20% improvement।
  • Consistent gains across domains।

মূল উপলব্ধি: Second-order — convex optimization-এর gold standard। XGBoost — boosting-এ first principled application। Math + engineering = dominance।

প্র ০২ XGBoost engineering tricks — sparsity-aware, histogram, parallel column-block — কেন practical performance এত boost করে?

XGBoost — algorithm + system co-design। Engineering equally critical।

(১) Sparsity-aware split finding:

  • Real-world data — sparse (one-hot, missing)।
  • Naive: zero treat as value — incorrect।
  • XGBoost: missing/zero default direction learn।
  • Best gain choice — automatic।
  • Memory savings — sparse storage।
  • 50× speedup on sparse data।

(২) Histogram-based split:

  • Original: প্রতি unique value-এ split try।
  • Continuous feature — millions split candidates।
  • Histogram: feature values bucket (256 default)।
  • Per-bucket gradient sum precompute।
  • Split candidates — bucket boundary।
  • Approximate but fast (10-100×)।

(৩) Column-block parallel:

  • Sort-based split — pre-sort columns।
  • Each column — independent block।
  • Multi-thread — parallel split search।
  • Reuse across iterations।
  • Linear scaling with cores।

(৪) Cache-aware access:

  • Modern CPU cache hierarchy।
  • Sequential access — fast।
  • Random access — slow।
  • Block size tuned to cache।
  • Cache miss minimize।

(৫) Out-of-core learning:

  • Data > RAM scenarios।
  • Block sharding to disk।
  • Streaming reads।
  • Sparsity-aware compression।
  • 10-100GB datasets feasible।

(৬) Approximate split finding:

  • Local — within node।
  • Global — once, used everywhere।
  • Speed-accuracy tradeoff।

(৭) GPU support:

  • 2017+ — full GPU acceleration।
  • Histogram on GPU।
  • 10-50× speedup।
  • Multi-GPU distributed।

Comparison with competitors:

  • LightGBM: additional histogram tricks (GOSS, EFB)।
  • CatBoost: ordered boosting (different angle)।
  • sklearn HistGBM: XGBoost-inspired।

Real-world impact:

  • Higgs ১১M samples — 30 minutes (XGBoost) vs hours (sklearn GBM)।
  • KDDCup ২০১৫ winner — XGBoost critical।
  • Production billions samples — feasible।

মূল উপলব্ধি: "Engineering matters as much as math" — Tianqi Chen's philosophy। Modern ML — system + algorithm co-design।

প্র ০৩ XGBoost-এর ৬-৭টি hyperparameter। Bayesian optimization vs manual tuning vs random search — production-এ কোন approach? Common pitfalls কী?

XGBoost tuning — production ML-এর recurring challenge। Strategy choice critical।

Hyperparameter landscape:

  • ৬-৮টি critical knobs।
  • Continuous + discrete mix।
  • Interactions exist (max_depth × learning_rate)।
  • Search space ১০⁶+।

(১) Manual tuning:

Approach:

  • Start with defaults।
  • One-at-a-time vary।
  • Domain expert intuition।
  • Iterative refinement।

Pros:

  • Fast (few experiments)।
  • Interpretable progress।
  • Debug-friendly।

Cons:

  • Subjective।
  • Local optimum trap।
  • Missing interactions।
  • Inconsistent across people।

(২) Grid Search:

Approach: All combinations exhaustive।

Pros: Reproducible, complete coverage।

Cons: Curse of dimensionality (5 params × 5 values = 3125 runs)।

(৩) Random Search:

Approach: Random combinations sample।

Pros: Bergstra & Bengio — comparable to grid in less time।

Cons: No learning from history।

(৪) Bayesian Optimization:

Approach:

  • Surrogate model (GP) — performance predict।
  • Acquisition function — next point pick।
  • History from previous runs।
  • Sequential exploration-exploitation।

Pros:

  • Sample-efficient — fewer runs।
  • Handles continuous gracefully।
  • Theoretically grounded।

Cons:

  • Sequential — slow for parallel hardware।
  • Setup complexity।
  • GP hyperparameter own।

(৫) Hyperband / BOHB:

Approach: Multi-fidelity — bad early kill, good train more।

Pros: 10-100× speedup over random।

Cons: Implementation complexity।

(৬) Population Based Training (PBT):

Approach: Genetic-like, online during training।

Pros: No retrain, schedule discover।

Cons: Compute-heavy।

Production recommendation:

  • (১) Manual + sensible defaults: baseline ২ hours।
  • (২) Random Search: ৫০-১০০ runs broad coverage।
  • (৩) Bayesian (Optuna): ১০০-৫০০ runs refinement।
  • (৪) Final manual sanity check।

Tools:

  • Optuna: Bayesian, easy use, popular।
  • Hyperopt: classic Bayesian।
  • Ray Tune: distributed, flexible।
  • scikit-optimize: simple, sklearn-like।

Pitfall-1: Validation contamination:

  • Same validation hyperparameter selection।
  • Over-fit to validation।
  • Solution: nested CV, separate test set।

Pitfall-2: Tuning before features:

  • Wasted effort if features change।
  • Solution: feature engineering first, then tune।

Pitfall-3: Ignoring early stopping:

  • $n\_estimators$ tune — wasteful।
  • Solution: early stopping always।

Pitfall-4: Single seed:

  • Variance across seeds — noisy comparison।
  • Solution: multi-seed averaging।

Pitfall-5: Local optimum:

  • Manual tuning — myopic।
  • Solution: global search method।

Pitfall-6: Compute budget mismatch:

  • Too few runs — wrong answer।
  • Too many — wasted compute।
  • Solution: convergence monitoring।

Pitfall-7: Default search space:

  • Generic ranges — domain miss।
  • Solution: domain prior knowledge integrate।

Practical workflow:

import optuna
def objective(trial):
    params = {
        'max_depth': trial.suggest_int('max_depth', 3, 10),
        'learning_rate': trial.suggest_float('learning_rate', 0.01, 0.3, log=True),
        'subsample': trial.suggest_float('subsample', 0.6, 1.0),
        'colsample_bytree': trial.suggest_float('colsample_bytree', 0.6, 1.0),
        'reg_lambda': trial.suggest_float('reg_lambda', 0.01, 10, log=True),
        'min_child_weight': trial.suggest_int('min_child_weight', 1, 10),
    }
    model = xgb.XGBClassifier(n_estimators=2000, **params,
                              early_stopping_rounds=50, random_state=0)
    model.fit(Xt, yt, eval_set=[(Xv, yv)], verbose=False)
    return model.best_score

study = optuna.create_study(direction='maximize')
study.optimize(objective, n_trials=200)
print(study.best_params)

Bangladesh production:

  • Compute budget often limited।
  • Quick win: defaults + early stopping।
  • Long-term: Optuna pipeline।
  • Track all experiments (MLflow)।

মূল উপলব্ধি: Tuning — art + science। Automated Bayesian optimization gold standard। Manual baseline + automated refinement — production sweet spot।

প্র ০৪ "XGBoost Kaggle dominate" — ২০১৪-২০১৮ সত্য। ২০২৪+-এ landscape কী? LightGBM, CatBoost, deep tabular models-এর সাথে XGBoost-এর position?

XGBoost dominance peak ২০১৬-২০১৮। Modern landscape diverse, nuanced।

২০১৪-২০১৮ — XGBoost age:

  • ২০১৫-এ Kaggle competitions ৬০%+ XGBoost-based।
  • "Just XGBoost it" meme।
  • Ensemble of XGBoost variants।
  • Higgs Boson, KDDCup wins।

২০১৭+ — LightGBM challenger:

  • Microsoft (২০১৭) — Histogram speedup further।
  • GOSS — gradient sampling।
  • EFB — exclusive feature bundling।
  • Leaf-wise growth।
  • 10× faster, similar accuracy।
  • Big data শক্তি।

২০১৮+ — CatBoost specialist:

  • Yandex (২০১৭) — categorical native।
  • Ordered boosting — leak-free।
  • Symmetric trees — fast inference।
  • Categorical-heavy data — winner।

২০১৯+ — Deep tabular:

  • TabNet (Google ২০২০) — attention-based।
  • NODE (Yandex) — neural oblivious decision ensemble।
  • SAINT — self-attention।
  • FT-Transformer — feature tokenization।
  • TabPFN (২০২৩) — meta-learning prior।

২০২৪ benchmark realities:

(১) Kaggle 2023 winners:

  • ৪০% LightGBM।
  • ৩০% XGBoost।
  • ২০% CatBoost।
  • ১০% deep tabular (mainly hybrids)।
  • "GBDT family" still dominant।

(২) Production landscape:

  • FAANG — XGBoost/LightGBM mainstream।
  • Russia (Yandex, Sber) — CatBoost preferred।
  • Startups — practical: any GBDT।
  • Research — deep tabular emerging।

(৩) Performance comparison:

  • Small data (<10K): XGBoost wins।
  • Mid (10K-1M): LightGBM wins (speed)।
  • Categorical-heavy: CatBoost wins।
  • Large (1M+): LightGBM / GPU XGBoost।
  • Specialty cases: Deep tabular spot strength।

XGBoost current strengths:

  • Maturity: 10-year battle-tested।
  • Documentation: extensive।
  • Bug-free: stable production।
  • Cross-platform: Python, R, Java, Scala।
  • Distributed: Spark/Flink integration।
  • Educational: reference implementation।

XGBoost current weaknesses:

  • Speed: LightGBM ahead।
  • Categorical: CatBoost ahead।
  • Memory: heavy compared to LightGBM।
  • GPU efficiency: RAPIDS RF often faster।

Deep tabular reality check:

  • Benchmark — Grinsztajn et al. (২০২২)।
  • ৪৫টি tabular dataset।
  • GBDT consistently competitive বা better।
  • Deep tabular — specific niches।
  • Reasons: tree-friendly geometry, robustness, sample efficiency।

When to use what:

  • XGBoost: default, mature pipeline, mid-data।
  • LightGBM: speed critical, big data।
  • CatBoost: categorical-heavy, less tuning।
  • TabPFN: very small data (<1000)।
  • TabNet/SAINT: interpretability + tabular DL preferred।

Future trends:

  • (১) Foundation models for tabular।
  • (২) Multi-modal (tabular + text + image)।
  • (৩) AutoML standard।
  • (৪) Hardware acceleration (TPU)।
  • (৫) Causal inference integration।

Bangladesh context:

  • Data sizes typical small-medium।
  • Skill availability — XGBoost most documented।
  • Production deployment — XGBoost mature।
  • Future: LightGBM growing share।

মূল উপলব্ধি: XGBoost still excellent, but landscape diverse। Tabular ML mature field — multiple tools each strength। Choose by use case, not hype।

অনুশীলন

  1. হিসাব করুন: Squared loss-এ — $g_i = \hat{y}_i - y_i$, $H_i = 1$। একটি leaf-এ ৫টি samples, $G = -2$, $H = 5$, $\lambda = 1$। $w^*$ ও objective contribution কত?
    • $w^* = -G/(H+\lambda) = -(-2)/(5+1) = 0.333$।
    • Objective contribution = $-\frac{1}{2} G^2/(H+\lambda) = -\frac{1}{2} \cdot 4/6 = -0.333$।
    • Negative — loss decrease।
  2. xgboost: Feature importance (gain) এবং SHAP values plot করুন।
    import xgboost as xgb
    import shap
    
    model = xgb.XGBClassifier(...).fit(X, y)
    xgb.plot_importance(model, importance_type='gain')
    
    explainer = shap.TreeExplainer(model)
    shap_values = explainer.shap_values(X)
    shap.summary_plot(shap_values, X)
  3. চিন্তা: $\lambda$ বাড়ালে কী হয় — leaf weight, tree size, generalization-এ?

    $\lambda$ বাড়ালে — denominator বড় → weight magnitude কম (smoother)। Gain কম → split rejection বেশি → tree ছোট। Generalization improve, কিন্তু excessive $\lambda$ → underfit।

আরও পড়ুন

কোড রানার কাজ না করলে? Google Colab ব্যবহার করুন।
পূর্ববর্তী পাঠ
পাঠ ২৩ · Gradient Boosting