Sub topic 14
Handling imbalanced classes
This chapter covers what goes wrong when one class is rare and how to fix it in XGBoost. It assumes you can train an XGBClassifier, that you know log loss, AUC and precision/recall, and that you remember how gradients and hessians drive the splits (earlier chapters).
Why imbalance hurts boosting
Suppose 5% of rows are positive. A model that always predicts "negative" scores 95% accuracy and is useless. Boosting has a related problem. Each tree is fit to gradients and hessians summed over the rows in a leaf. Majority-class rows contribute most of the sum, so early trees mostly learn to separate the common class and pay little attention to the rare one.
There are two separate questions, and mixing them up causes most errors:
- Ranking quality. Does the model give positives higher scores than negatives? AUC and PR-AUC measure this.
- Probability quality. Are the predicted probabilities calibrated, meaning a score of 0.3 really corresponds to about 30% positives? Log loss measures this, along with calibration curves.
Reweighting the rare class often improves the first and damages the second. Pick the approach based on which one you need.
Choose metrics first
Accuracy is misleading here. Use these instead:
| Metric | What it tells you | Use when |
|---|---|---|
| `aucpr` | Area under the precision-recall curve | Positives are rare and you care about finding them |
| `auc` | Ranking quality across all thresholds | Classes are moderately imbalanced |
| `logloss` | Probability quality | You need trustworthy probabilities |
| F1, recall at a precision target | Quality at one chosen threshold | A decision rule is fixed |
ROC-AUC can look excellent on very imbalanced data because the huge number of negatives keeps the false positive rate small. PR-AUC reacts more strongly to false positives among the few predicted positives, so it is usually the better early-stopping metric for rare-event problems.
Always split with stratify=y so the validation and test sets keep the same class ratio as the training set. With very few positives, an unstratified split can leave a fold with almost none.
Weighting the rare class with scale_pos_weight
scale_pos_weight multiplies the gradient and hessian of every positive row by a constant. The usual starting value is the ratio of negatives to positives. With a 95/5 split this is about 19, which makes the total weight of the two classes equal.
from sklearn.datasets import make_classification
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)
model.save_model("model.json")
loaded = XGBClassifier()
loaded.load_model("model.json")
print(loaded.predict_proba(X_test)[:3])Compute the ratio on the training data only. Using the full dataset leaks a small amount of information about the test split.
The full ratio is a starting point, not a rule. A common refinement is to try values between 1 and the full ratio, such as 1, the square root of the ratio, and the ratio itself, then compare PR-AUC on a validation set.
Per-row weights
scale_pos_weight applies only to binary classification. For multiclass problems, or when some rows matter more than others, pass sample_weight to fit. This gives each row its own weight in the gradient sums.
from sklearn.utils.class_weight import compute_sample_weight
weights = compute_sample_weight(class_weight="balanced", y=y_train)
model = XGBClassifier(n_estimators=200, learning_rate=0.1, max_depth=4)
model.fit(X_train, y_train, sample_weight=weights)The "balanced" option weights each class inversely to its frequency, which works for any number of classes. Do not combine sample_weight="balanced" and scale_pos_weight in the same model. Both inflate the positives, so the effect is applied twice.
When you use weights, early stopping and evaluation need care. By default the validation set in eval_set is unweighted. If you want the validation metric to reflect the same weighting, pass sample_weight_eval_set. Decide deliberately, because an unweighted validation metric reflects real-world performance while a weighted one reflects the rebalanced objective.
Limiting the damage with max_delta_step
With heavy imbalance, a leaf containing mostly positives can get a very large weight, and a very small hessian makes the update unstable. In logistic regression, XGBoost's documentation recommends setting max_delta_step to a small positive value such as 1 to 10. This caps how far one tree can move a leaf output and helps convergence.
model = XGBClassifier(
n_estimators=300, learning_rate=0.1, max_depth=4,
scale_pos_weight=spw, max_delta_step=1, eval_metric="aucpr",
)Also consider raising min_child_weight. It sets the minimum hessian sum a leaf needs. For logistic loss the hessian is p(1 - p), which is small when predictions are confident, so a leaf with few rare-class rows can easily fall below the limit. If the model never splits on the rare class, lower min_child_weight rather than raising it.
Thresholds and probabilities
After weighting, predict still cuts at 0.5, which no longer matches the shifted probabilities. Choose a threshold on a validation set instead of trusting the default.
import numpy as np
from sklearn.metrics import precision_recall_curve
proba = loaded.predict_proba(X_test)[:, 1]
precision, recall, thresholds = precision_recall_curve(y_test, proba)
f1 = 2 * precision[:-1] * recall[:-1] / (precision[:-1] + recall[:-1] + 1e-12)
best = thresholds[np.argmax(f1)]
print(best, f1.max())This example picks the threshold on the test set only to keep it short. In real work, choose it on a validation set and report the final score on a separate test set. Otherwise the reported F1 is optimistic.
If you need calibrated probabilities after weighting, wrap the model with scikit-learn's CalibratedClassifierCV or fit an isotonic or Platt calibrator on held-out data. An alternative is to train without weights, since an unweighted model optimizing log loss is already well calibrated, and only move the threshold.
Common errors
- Reporting accuracy. A 95% score may mean the model predicts one class.
- Weighting and then reading probabilities literally. A score of 0.5 after weighting does not mean a 50% chance.
- Double weighting. Using
scale_pos_weighttogether with balancedsample_weight. - Tuning the threshold on the test set. The final score becomes optimistic.
- Unstratified splits. Folds can contain too few positives to evaluate.
- Using ROC-AUC alone. It can hide poor precision on rare classes.
Choosing an approach
- Fix the metric (PR-AUC for rare positives) and use stratified splits.
- Train a baseline with no weighting and record the score.
- Add
scale_pos_weight, trying several values, with early stopping on the chosen metric. - Add
max_delta_stepif training is unstable. - Tune the threshold on a validation set, and calibrate if probabilities are used downstream.
Exercise
A binary dataset has 9,500 negatives and 500 positives in the training set. What starting value would you use for scaleposweight, and why can the resulting predict_proba values no longer be read as true probabilities?
Show answer
Use 9500 / 500 = 19. This makes the total gradient and hessian weight of the positives equal to that of the negatives. Because each positive row counts 19 times, the model behaves as if positives were far more common than they are, so its scores are shifted upward. A score of 0.5 no longer means a 50% chance. Use the scores for ranking, tune the threshold on a validation set, or calibrate them on held-out data.
Exercise
You trained with scaleposweight and early stopping on logloss, and the model stops very early with poor recall. Which change would you try first?
Show answer
Switch the early-stopping metric to aucpr (or auc). Log loss on the validation set is dominated by the majority class and is hurt by the shifted probabilities from weighting, so it can stop training before the model has learned to rank the rare class well. Also check that the validation set is stratified.