Class imbalance & calibration
When positives are rare, fix the metric and the threshold before the data; when decisions use the probability itself (auctions, expected loss), calibrate it so a score of 0.02 really means 2%.
Analogy: A forecaster is calibrated if it rains on ~30% of the days she says "30%". Ranking days by rain risk is easy; promising the real odds is what lets you decide whether to carry an umbrella.
How it works
- Judge with PR-AUC, not accuracy, and set the threshold by the cost of false positives vs false negatives.
- Upweight positives with class weights or downsample negatives; SMOTE rarely helps strong learners.
- Weighting, resampling, boosting and deep nets distort probabilities; calibrate on an unsampled holdout.
- Platt fits small data, isotonic needs ≳1,000 samples; check a reliability diagram, since AUC can't see miscalibration.
- After downsampling negatives at rate w, map back with q = p / (p + (1 − p)/w).
Check yourself
Answer to mark it learned; your answers aren't scored.
You add scale_pos_weight = neg/pos to your fraud GBDT. PR-AUC improves, but the rule p × amount > review cost now sends 5× more transactions to manual review. Nothing else changed. What's the cause and the fix?
Go deeper
Full explanation
Imbalance. At 0.1–1% positives (fraud, clicks, abuse), a model can lower its loss by leaning to "negative", and accuracy hides it. Levers, cheapest first:
- Threshold by cost: flag when
p > c_FP / (c_FP + c_FN). Needs calibratedp. - Class weights (
scale_pos_weight,class_weight): upweight positives in the loss, no data dropped. - Resampling: downsample negatives (cheap, standard in ads); oversampling or SMOTE rarely helps strong learners.
- Focal loss: down-weights easy examples so rare, hard ones dominate.
- Judge with PR-AUC, not accuracy (Precision, recall, F1, ROC-AUC).
Calibration means predicted probabilities match observed frequencies: of items scored 0.2, ~20% are positive. Weighting, resampling, boosting and deep nets distort it. Fix it on an unsampled holdout:
- Platt scaling: logistic regression on the score; 2 parameters, good for small data.
- Isotonic regression: monotone step function; more flexible, needs ≳1,000 samples.
- Temperature scaling for neural nets.
Measure with a reliability diagram (predicted vs observed rate per bin), ECE or log loss; AUC can't see miscalibration.
Why ads and fraud care: auctions rank by bid × pCTR, fraud compares p × amount with review cost, and pCTR × pCVR only works if both are calibrated. After downsampling negatives at rate w, map back with q = p / (p + (1 − p)/w).
Code Weight, calibrate, measure ECE, decide by cost
import numpy as np
from sklearn.calibration import CalibratedClassifierCV, calibration_curve
from sklearn.metrics import average_precision_score, brier_score_loss
from xgboost import XGBClassifier
# Fraud, ~0.5% positives. Upweighting positives helps ranking but inflates p.
neg, pos = np.bincount(y_tr)
xgb = XGBClassifier(n_estimators=400, learning_rate=0.05, max_depth=6,
scale_pos_weight=neg / pos) # common starting point; tune it
# Learn the score -> probability map on held-out folds (isotonic: needs > ~1k rows)
model = CalibratedClassifierCV(xgb, method="isotonic", cv=5).fit(X_tr, y_tr)
p = model.predict_proba(X_te)[:, 1]
print(f"PR-AUC {average_precision_score(y_te, p):.3f} Brier {brier_score_loss(y_te, p):.5f}")
def ece(y, p, bins=10):
# Equal-mass bins: with rare events, equal-width bins put almost everything in bin 0
edges = np.quantile(p, np.linspace(0, 1, bins + 1))
idx = np.clip(np.searchsorted(edges, p, side="right") - 1, 0, bins - 1)
return sum((idx == b).mean() * abs(p[idx == b].mean() - y[idx == b].mean())
for b in range(bins) if (idx == b).any())
obs, pred = calibration_curve(y_te, p, n_bins=10, strategy="quantile") # reliability diagram
print("ECE:", ece(y_te, p))
# Decide on expected value, not 0.5: review when expected fraud loss beats review cost
REVIEW_COST = 5.0
review = p * amount_te > REVIEW_COST
# Trained on negatives downsampled at rate w? Undo the prior shift before calibrating
def undo_downsampling(p, w):
return p / (p + (1 - p) / w)Real example
An ads team keeps all clicks but only 5% of non-clicks, shrinking a 1%-CTR dataset ~17×. The model learns odds 20× too high and predicts ~0.17 for an average ad. Fed raw into the auction, bid × pCTR would overstate every ad's value ~17× against reserve prices and organic content. Mapping back with q = p / (p + (1 − p)/w) turns 0.17 into ~0.010; a final isotonic fit on a fresh, unsampled day brings the calibration ratio (predicted ÷ observed clicks) from 1.12 to 1.01.
Trade-offs +3 · −4
+ You gain
- Threshold tuning and class weights are nearly free and often enough.
- Calibrated scores compose: multiply pCTR × pCVR, compare with costs, feed auctions and pacing.
- Downsampling negatives to 5% shrinks a 1%-CTR dataset ~17×, with a closed-form correction.
− You pay
- Every reweighting or resampling trick distorts probabilities, so you must recalibrate.
- Isotonic overfits small calibration sets; Platt can't fix non-sigmoid distortions.
- Calibration drifts when base rates shift (seasonality, new markets), so it needs monitoring and refits.
- Oversampling or SMOTE rarely helps strong learners and can invent unrealistic examples.
Use it when
Rare-event problems (fraud, abuse, CTR, churn), and any system that acts on the probability itself: auctions, expected-value decisions, combining models, risk scores shown to people.
Avoid it when
Calibration for pure ranking where only order matters: it leaves AUC and NDCG unchanged. Resampling on mildly imbalanced data (~10–40% positives) buys little.
Numbers to know 5
- Cost threshold (Elkan, 2001): t = c_FP / (c_FP + c_FN); a $5 review vs a $100 missed fraud gives t ≈ 0.048.
- Downsampling correction (He et al., Facebook, 2014): q = p / (p + (1 − p)/w), with w the negative sampling rate.
- Focal loss (Lin et al., 2017): γ = 2, α = 0.25 worked best for RetinaNet; γ = 0 is plain cross-entropy.
- scikit-learn: isotonic matches or beats sigmoid (Platt) with more than ~1,000 calibration samples.
- Facebook's calibration metric: average predicted CTR ÷ observed CTR; target ≈ 1.0.
Common pitfalls 4
- Calibrating on downsampled or reweighted training data instead of an unsampled, recent holdout.
- Judging calibration by AUC, which ignores monotone transforms. Use reliability diagrams, ECE, log loss or Brier.
- Equal-width ECE bins on rare events: nearly everything lands in the first bin. Use equal-mass bins and check per segment.
- Shipping 0.5 as the threshold, or tuning it on the test set.
Interview questions 3
Answer out loud first, then reveal.
You're building fraud detection with 0.2% positives. How do you handle the imbalance?Show answer
I treat it as a metric and threshold problem before a data problem. I evaluate with PR-AUC and precision at a recall target, never accuracy. I train a GBDT, maybe with moderate class weights or negative downsampling for speed, and skip SMOTE as a first move. Then I calibrate on a recent, unsampled holdout and set the threshold by cost: review when expected loss, p times amount, exceeds the review cost. The failure mode I watch is label delay: chargebacks arrive weeks later, so the newest data looks cleaner than it is.
Why does an ads system need calibrated pCTR, when AUC only cares about order?Show answer
Because the auction uses the value, not just the order. Ads are ranked and priced by bid times pCTR across advertisers, often multiplied by a pCVR from another model, and budget pacing and advertiser ROI depend on the actual numbers. If one campaign's pCTR is 30% high, it wins auctions it shouldn't and pays the wrong price. AUC is blind to this because monotone transforms leave it unchanged. So I track log loss plus a calibration ratio, predicted over observed clicks near 1.0, per segment, and recalibrate after any sampling change.
Platt scaling or isotonic regression?Show answer
Platt fits a sigmoid on the score: two parameters, data-efficient, but it only fixes sigmoid-shaped distortion, typical of SVMs and boosted trees. Isotonic fits any monotone step function, so it fixes arbitrary distortion but overfits small sets; scikit-learn suggests it above ~1,000 calibration samples. With rare positives, what matters is positives per bin, not total rows. For neural nets I start with temperature scaling. Either way I calibrate on data the model didn't train on, from the most recent period.