Teaching Gradient Boosting: XGBoost, LightGBM, CatBoost
Gradient boosting builds an ensemble of weak learners (typically shallow decision trees) sequentially. Each new tree predicts the residuals (errors) of the previous ensemble, fitting via gradient descent on a loss function (e.g., MSE for regression, log-loss for classification). The final prediction is a weighted sum: ( \hat{y} = \sum_{m=1}^M \eta \cdot h_m(x) ), where ( h_m ) is the m-th tree, ( \eta ) is shrinkage (learning rate), and M is the number of trees.
Key libraries:
- XGBoost: Exact greedy splitting, handles missing values, fast on CPU/GPU.
- LightGBM: Histogram-based (faster, leaf-wise growth), native categoricals.
- CatBoost: Symmetric trees, ordered boosting (reduces overfitting), excellent for categoricals.
Now, the topics:
1. Bias–Variance Trade-offs
- Bias: Error from overly simplistic models (underfitting).
- Variance: Error from sensitivity to training data (overfitting).
- Boosting starts with high-bias shallow trees (low variance) and adds trees to reduce bias iteratively.
- Trade-off: More/deeper trees → lower bias, higher variance. Monitor via train/validation CV error curves.
- High bias: Stalled learning curve.
- High variance: Train error low, val error diverges.
- Tune: Early stopping (e.g.,
early_stopping_rounds=50).
2. Shrinkage (Learning Rate, η)
- Scales each tree's contribution: Small η (0.01–0.1) → more trees needed, smoother fits, less overfitting.
- Analogy: Tiny steps prevent overshooting the minimum.
- Default: XGBoost/LightGBM ~0.1; pair with
n_estimators=100–1000 and early stopping.
3. Depth/Leaf Settings
Control tree complexity:
| Param | XGBoost | LightGBM | CatBoost | Effect |
|---|
| Depth | max_depth=6 | N/A | depth=6 | Deeper → lower bias, higher variance. Default 6 shallow. |
| Leaves | N/A | num_leaves=31 (2^depth) | N/A | Leaf-wise growth (LightGBM) risks overfitting; cap <2^depth. |
| Min samples | min_child_weight=1 | min_data_in_leaf=20 | min_data_in_leaf=1 | Higher → smoother, less overfitting. |
| Subsampling | subsample=0.8 (rows), colsample_bytree=0.8 (cols) | Same | Same | Stochasticity reduces variance. |
Start shallow, grid search.
4. Categorical Handling
No need for one-hot (sparsity explosion):
- XGBoost: One-hot or label encode +
enable_categorical=True (v1.5+).
- LightGBM:
categorical_feature=[list], optimal split on categories (histogram bins).
- CatBoost: Native; uses ordered target statistics (permutation-resistant encoding) to avoid leakage/overfitting. Best for high-cardinality cats.
5. Monotonic Constraints
Force feature directions (e.g., "higher income → higher purchase prob"):
- XGBoost:
monotone_constraints=(1,-1,0,...) (1=+, -1=-, 0=none).
- LightGBM:
monotone_constraints="1,-1,0".
- CatBoost:
monotone_constraints="Feature1>=,Feature2<=".
- Use domain knowledge; improves interpretability/calibration.
6. Regularization
Penalizes complexity in tree loss: ( \Omega = \gamma T + \frac{1}{2} \lambda |w|^2 + \alpha |w|_1 )
reg_alpha (L1): Sparsity (zeroes weights/features).
reg_lambda (L2): Smoothness (default 1).
- Global:
gamma (split penalty), subsampling.
- LightGBM/CatBoost similar; CatBoost adds prior for imbalance.
7. Class Imbalance
Boosting favors majority; fixes:
- Weights: XGBoost
scale_pos_weight = neg/pos ratio; LightGBM class_weight='balanced'.
- Focal loss (CatBoost/LightGBM): Downweights easy examples.
- Oversample (SMOTE) + undersample, or
is_unbalance=True.
- Eval metric:
eval_metric='aucpr' (precision-recall AUC).
8. Calibration
Raw probs often overconfident (variance-induced).
- Post-hoc:
CalibratedClassifierCV(base_estimator=XGBClassifier(), method='sigmoid').
- In-library: XGBoost
booster='gblinear' (better calibrated); LightGBM class_weight.
- Plot reliability diagrams; aim for diagonal.
9. Feature Importance
Post-fit diagnostics:
| Type | Meaning | Best For |
|---|
| Gain (split improvement) | Total gain from splits on feature. | Predictive power. |
| Cover (samples affected) | # samples routed through splits. | Population impact. |
| Frequency (# splits) | How often used. | Simple ranking. |
| SHAP (external) | Marginal contributions. | Interpretability. |
Access: model.feature_importances_ or plot_importance().
Tiny Worked Example: Binary Classification
Dataset: Synthetic 2D imbalanced data (100 samples, 10% positive class). Predict y from x1 (monotonic +), x2 (cat: 'A','B'), x3 (noise).
import numpy as np
import xgboost as xgb
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
import pandas as pd
# Tiny data: x1 monotonic+, x2 cat ('A'<50%, 'B'>80%), x3 noise, imbalance 10%
np.random.seed(42)
n = 100
X = pd.DataFrame({
'x1': np.random.randn(n), # Monotonic +
'x2': np.random.choice(['A', 'B'], n, p=[0.6, 0.4]), # Categorical
'x3': np.random.randn(n) # Noise
})
y = (X['x1'] > 0.5) | (X['x2'] == 'B') # ~10% positive
y = y.astype(int)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, stratify=y)
# XGBoost: Shallow (bias-variance), shrinkage, cat/monotonic/regs/imbalance
params = {
'objective': 'binary:logistic',
'learning_rate': 0.1, # Shrinkage
'max_depth': 2, # Shallow: bias↓ variance↑ controlled
'min_child_weight': 5, # Reg: min leaves
'reg_alpha': 0.1, 'reg_lambda': 1, # L1/L2
'scale_pos_weight': 9, # Imbalance (90/10)
'monotone_constraints': (1, 0, 0), # x1 +, others free
'enable_categorical': True,
'eval_metric': 'aucpr', # Imbalance metric
'seed': 42
}
dtrain = xgb.DMatrix(X_train, label=y_train, enable_categorical=True)
dtest = xgb.DMatrix(X_test, label=y_test, enable_categorical=True)
model = xgb.train(params, dtrain, num_boost_round=50, evals=[(dtrain, 'train'), (dtest, 'test')],
early_stopping_rounds=10, verbose_eval=False)
# Predict & eval
preds = model.predict(dtest)
print(f"Test AUC-PR: {roc_auc_score(y_test, preds):.3f}") # ~0.85 typically
# Importance (gain)
importance = model.get_score(importance_type='gain')
print("Feature Importances (gain):", importance) # x1/x2 high, x3 low
# For LightGBM: Replace with lgb.Dataset, params['num_leaves']=4, categorical_feature=['x2']
# CatBoost: CatBoostClassifier(cat_features=['x2'], monotone_constraints='MonoIncreasing:x1'
Output (example run):
Test AUC-PR: 0.852
Feature Importances (gain): {'x1': 12.3, 'x2': 8.7, 'x3': 0.1}
Key Learnings from Example:
- Shallow depth + shrinkage + early stop → good bias-variance (val AUC stable).
- Monotonic on x1 enforces logic.
- Cat handled natively.
- Imbalance fixed → high AUC-PR.
- Gain shows x1/x2 drive predictions.
Pro Tips: Always CV (xgb.cv), tune with Optuna/Hyperopt, ensemble libraries (e.g., blend XGBoost+LightGBM). Scale to GPU for big data! Questions?