Class Imbalance, Probability Calibration & Cost-Sensitive Learning
Why SMOTE before CV is a silent disaster, how Platt & Isotonic calibration fix overconfident probabilities, and how to derive the Bayes-optimal decision threshold.
Imbalance handling (class weights, SMOTE), probability calibration (Platt/Isotonic), and cost-sensitive thresholds align model outputs with rare events and asymmetric business costs.
In fraud, cancer screening, or churn, missing a rare positive can cost 100x more than a false alarm—and raw tree/SVM scores are often poorly calibrated.
Real-world ML is almost ALWAYS imbalanced — and business value depends on calibrated probabilities, not 0.50 cutoffs!
In ad-click bidding (pCTR), fraud blocking, and sepsis alerts, downstream systems multiply your predicted probability by dollar value (EV = p̂ · Value). An uncalibrated tree or neural net causes catastrophic over-bidding or alert fatigue!
Data scientists who blindly apply SMOTE before train/test split report 0.96 F1 in notebooks and ship 0.40 F1 in production. Knowing when to tune thresholds + calibrate beats blind oversampling every time.
Senior ML loops LOVE asking: 'Your fraud model has 0.94 ROC-AUC, 1% fraud rate, and FN costs $500 while FP costs $10 — what threshold do you ship and what happens to probabilities if you oversample?'
Suppose you oversample the 1% fraud class to 50% so your logistic regression trains on a 50/50 dataset. What happens to its predicted probabilities p̂ on real production traffic?
- Prevent SMOTE / oversampling leakage by resampling strictly inside each training fold
- Compare class_weight='balanced', Focal Loss, and threshold tuning against resampling
- Diagnose uncalibrated probabilities with Reliability Diagrams, Brier Score, and ECE
- Apply Platt Scaling, Isotonic Regression, and Temperature Scaling without hurting ROC-AUC
- Compute the exact Bayes-optimal decision threshold τ* = C_FP / (C_FP + C_FN)
Imagine a weather app that says '80% chance of rain' on 100 days, and it only rains on 30 of them. Even if its ranking (ROC-AUC) is great, you CANNOT trust its numbers to decide whether to cancel an outdoor wedding! Calibration makes probabilities mean what they say, and Cost-Sensitive Thresholding turns calibrated probabilities into optimal business actions.
1. Resampling (SMOTE / Undersampling) vs. Class Weights & Leakage
When 99.5% of transactions are legit, naive accuracy is useless. Many beginners reach for SMOTE (Synthetic Minority Oversampling Technique), which interpolates new fake fraud points between real fraud neighbors. The #1 deadly trap? Running SMOTE before splitting into train and validation — putting near-identical synthetic clones of validation fraud inside your training set!
The Modern Production Playbook for Imbalanced Data
- First choice (Zero distortion): Train on the natural distribution with proper loss (Log-Loss) + PR-AUC evaluation, then tune the decision threshold !
- Second choice: Use
class_weight='balanced'or Focal Loss to focus gradients on hard minority examples. - Third choice (SMOTE / Undersampling): Wrap inside
imblearn.pipeline.Pipelineso resampling runs strictly inside each CV training fold — and remember to recalibrate probabilities afterward!
Why does running SMOTE before train_test_split inflate validation F1?
2. Probability Calibration: Reliability Diagrams, Brier Score & Temperature Scaling
A model is calibrated when among all predictions of p̂ = 0.70, roughly 70% are actually positive. Logistic Regression is naturally well-calibrated, whereas SVMs, Naive Bayes, Random Forests, and deep neural networks are notoriously miscalibrated! Drag the Temperature slider below to calibrate an overconfident model live.
Measuring & Fixing Calibration (Always on a Held-Out Calibration Split!)
- Brier Score: (MSE on probabilities — rewards both sharp ranking AND calibration).
- Platt Scaling (Sigmoid): Fits 2 parameters via . Best for small calibration sets and SVMs.
- Isotonic Regression: Fits a non-parametric monotonic step function. Needs larger calibration sets () or it overfits!
- Temperature Scaling: Fits 1 scalar via . Standard in deep learning & LLMs because it preserves top-1 accuracy and ROC-AUC!
Tune Temperature T to Calibrate an Overconfident Model
Notice: dividing logits by T ≈ 1.80 snaps every bin onto the true frequency (ECE → 0.5%) while keeping ROC-AUC 100% unchanged because division by positive T preserves rank order!
3. Cost-Sensitive Learning & The Bayes-Optimal Threshold τ*
Suppose missing a fraudulent wire costs $500 (C_FN = 500), while sending an SMS verification challenge costs $10 (C_FP = 10). Should you wait until p̂ ≥ 0.50 to send an SMS? Of course not! Even a 3% chance of fraud has an expected loss of 0.03 × $500 = $15 > $10!
Deriving the Exact Bayes-Optimal Threshold
Flag as Positive whenever the expected cost of predicting Negative exceeds the expected cost of predicting Positive: This formula ONLY works if is a calibrated probability!
Click each term to see how asymmetric business costs shift your threshold
Cost of crying wolf (e.g., $10 SMS or manual review when transaction was legit).
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
No! Both are strictly monotonic transformations of the logit score, so the relative ranking of every pair of examples is 100% unchanged — ROC-AUC stays identical while Brier Score and Log-Loss improve dramatically.
Fraud Business-Loss & Bayes-Optimal Threshold Simulator (10,000 Txns)
Ad Tech (pCTR / Bidding)
Bid price = pCTR × Conversion Value. Even a 10% calibration drift wastes millions in ad spend.
Credit & Fraud Risk
Asymmetric costs (FN = $1,000 chargeback, FP = $5 alert) drive τ* down to 0.005–0.05.
Clinical Triage
Calibrated sepsis risk scores let ICU doctors prioritize limited beds accurately.
from sklearn.calibration import CalibratedClassifierCV
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.metrics import brier_score_loss
# 1. Fit base model on natural imbalanced data, then calibrate via CV
base = GradientBoostingClassifier(random_state=42)
cal_clf = CalibratedClassifierCV(base, method="isotonic", cv=5)
cal_clf.fit(X_train, y_train)
probs = cal_clf.predict_proba(X_test)[:, 1]
print("Calibrated Brier Score:", round(brier_score_loss(y_test, probs), 4))
# 2. Apply Bayes-optimal cost-sensitive threshold
C_FP, C_FN = 10.0, 500.0
tau_star = C_FP / (C_FP + C_FN) # 0.0196
y_pred = (probs >= tau_star).astype(int)