Sub topic 14
Handling imbalanced classes
This chapter assumes you can train an XGBClassifier, you know log loss, AUC and precision/recall, and you have read the chapters on gradients and hessians.
Why imbalance hurts
Suppose 5% of rows are positive. A model that always predicts the negative class scores 95% accuracy and finds no positives. Boosting has a related problem. Each tree is fit to gradients summed over rows, so the abundant class dominates those sums. Early trees mostly learn to separate the majority class, and the rare class gets little attention.
Imbalance is a problem when the rare class is the one you care about, such as fraud or disease. There are two separate things to fix: how you measure the model, and how the training loss weighs each class.
Step 1: pick a better metric
Accuracy hides the problem. Use a metric that focuses on the rare class:
aucpris the area under the precision-recall curve. It is usually more informative than ROC AUC when positives are rare.aucstill ranks well, but it can look good even when precision is poor.loglossis useful if you need calibrated probabilities.
Set this with eval_metric. Early stopping uses the last metric you list, so the choice also controls when training stops.
Step 2: weight the positive class
scale_pos_weight multiplies the gradient and hessian of every positive row. The usual starting value is the number of negatives divided by the number of positives. Compute it on the training split only.
from sklearn.datasets import make_classification
from sklearn.metrics import average_precision_score
from sklearn.model_selection import train_test_split
from xgboost import XGBClassifier
X, y = make_classification(
n_samples=5000, n_features=20, weights=[0.95, 0.05], random_state=0
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0
)
spw = (y_train == 0).sum() / (y_train == 1).sum()
model = XGBClassifier(
n_estimators=200, learning_rate=0.1, max_depth=4,
scale_pos_weight=spw, eval_metric="aucpr",
)
model.fit(X_train, y_train)
proba = model.predict_proba(X_test)[:, 1]
print(round(spw, 1), average_precision_score(y_test, proba))Use stratify=y when splitting, as above. Otherwise a validation set may contain very few positives, and its metric becomes noisy.
Step 3: choose the decision threshold
predict uses a 0.5 cutoff. With imbalanced data, 0.5 is rarely the best choice. Take the probabilities from predict_proba and choose a threshold from the precision-recall trade-off. Do this on validation data, based on what a missed positive costs compared with a false alarm.
Options and when to use them
| Approach | Effect | Main risk |
|---|---|---|
| `scale_pos_weight` | Raises the weight of positives in gradients | Distorts probabilities |
| `sample_weight` in `fit` | Per-row control, also works for multiclass | You must design the weights |
| `max_delta_step` (1 to 10) | Limits each tree's step, stabilizing very skewed logistic training | Slower convergence |
| Threshold tuning | Changes the precision/recall balance without retraining | Needs a representative validation set |
| Resampling | Changes the class ratio in the data | Oversampling can duplicate noise |
Try the metric and the threshold first, because they cost nothing. Add scale_pos_weight if recall on the rare class is still poor.
Exercise
A fraud dataset has 9,900 legitimate and 100 fraudulent training rows. What starting value would you use for scaleposweight, and why is accuracy a poor metric here?
Show answer
Use 9900 / 100 = 99. A model that predicts "legitimate" every time reaches 99% accuracy while catching no fraud. A metric such as aucpr, or precision and recall at a chosen threshold, shows how well the fraud class is found.