Chapter 22 of 42 · ~26 min read & lab+70 XP
Chapter 22 · Machine Learning

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.

What Is It?

Imbalance handling (class weights, SMOTE), probability calibration (Platt/Isotonic), and cost-sensitive thresholds align model outputs with rare events and asymmetric business costs.

Why Is It Required?

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.

Everyday Analogy: Setting airport security sensitivity higher than a spam filter because missing one threat is far costlier than checking an extra bag.
Why ML Engineers & Data Scientists Actually Need This

Real-world ML is almost ALWAYS imbalanced — and business value depends on calibrated probabilities, not 0.50 cutoffs!

ML / AI Engineer

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 Scientist

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.

Interview & Debug Edge

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?'

Step 0 · Test Your Gut Before Any Math!

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?

What You Will Master in This Chapter
  • 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)
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 4
p̂Say aloud:“Predicted probability”
Plain-English Meaning
Model's confidence that y = 1
Everyday Example
Predicted probability
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

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

Everyday Story First (Zero Math Yet!)

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!

Class Imbalance (99% Majority vs 1% Minority): Safe vs. Leaked ResamplingWRONG: SMOTE Before CV Split (Data Leakage!)Full Data → SMOTESplit Train / ValSynthetic clones of Val fraud appear in Train!Fake CV F1 = 0.96 → Production F1 = 0.41RIGHT: Split First → SMOTE / class_weight in TrainStratified SplitTrain Fold: SMOTEVal Fold: Raw 99:1Val fold preserves real-world 1% prior!Honest PR-AUC + Calibrated Probabilities
Class imbalance fixes compared: SMOTE/oversampling MUST happen strictly inside each training CV fold — never before splitting!

The Modern Production Playbook for Imbalanced Data

  1. First choice (Zero distortion): Train on the natural distribution with proper loss (Log-Loss) + PR-AUC evaluation, then tune the decision threshold τ\tau!
  2. Second choice: Use class_weight='balanced' or Focal Loss −(1−pt)γlog⁡(pt)-(1 - p_t)^\gamma \log(p_t) to focus gradients on hard minority examples.
  3. Third choice (SMOTE / Undersampling): Wrap inside imblearn.pipeline.Pipeline so resampling runs strictly inside each CV training fold — and remember to recalibrate probabilities afterward!
Pause & Check · Quick Intuition Pulse

Why does running SMOTE before train_test_split inflate validation F1?

2. Probability Calibration: Reliability Diagrams, Brier Score & Temperature Scaling

Everyday Story First (Zero Math Yet!)

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.

Reliability Diagram: Predicted Probability vs. Observed Positive FrequencyMean Predicted Probability (p̂)Actual Positive FractionPerfectly Calibrated (ECE = 0)Overconfident (Deep NN / Boosted)How to Fix Calibration (on Holdout):• Platt Scaling: sigmoid(a·z + b)• Isotonic Regression: non-parametric• Temperature Scaling: softmax(z / T)
Reliability diagram: a perfectly calibrated model sits on the diagonal y = x; overconfident models (like uncalibrated trees/NNs) form an S-curve.

Measuring & Fixing Calibration (Always on a Held-Out Calibration Split!)

  • Brier Score: BS=1n∑i=1n(p^i−yi)2\text{BS} = \frac{1}{n}\sum_{i=1}^n (\hat{p}_i - y_i)^2 (MSE on probabilities — rewards both sharp ranking AND calibration).
  • Platt Scaling (Sigmoid): Fits 2 parameters (a,b)(a, b) via p^cal=σ(az+b)\hat{p}_{\text{cal}} = \sigma(a z + b). Best for small calibration sets and SVMs.
  • Isotonic Regression: Fits a non-parametric monotonic step function. Needs larger calibration sets (n>1,000n > 1{,}000) or it overfits!
  • Temperature Scaling: Fits 1 scalar T>0T > 0 via softmax(z/T)\text{softmax}(z / T). Standard in deep learning & LLMs because it preserves top-1 accuracy and ROC-AUC!
Interactive Mini-Lab • Temperature Scaling

Tune Temperature T to Calibrate an Overconfident Model

ECE: 9.3%Brier: 0.0110
Bin 1
p̂ 4%
y 14%
Δ 10.1%
Bin 2
p̂ 17%
y 30%
Δ 13.2%
Bin 3
p̂ 50%
y 50%
Δ 0.0%
Bin 4
p̂ 83%
y 70%
Δ 13.2%
Bin 5
p̂ 96%
y 86%
Δ 10.1%

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 τ*

Everyday Story First (Zero Math Yet!)

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!

Cost-Sensitive Decisions: Why 0.50 Is Almost Never OptimalTN (Correct)$0FP (False Alarm)C_FP = $10FN (Missed Fraud)C_FN = $500TP (Caught!)$0Bayes-Optimal Threshold Formulaτ* = C_FP / (C_FP + C_FN)τ* = 10 / (10 + 500) = 0.0196 (2%!)Flag any transaction with P(fraud | x) ≥ 2%!
Bayes-optimal threshold τ* = C_FP / (C_FP + C_FN) shifts dramatically below 0.50 whenever False Negatives cost far more than False Positives.

Deriving the Exact Bayes-Optimal Threshold

Flag as Positive whenever the expected cost of predicting Negative exceeds the expected cost of predicting Positive: p⋅CFN≥(1−p)⋅CFP  ⟹  τ∗=CFPCFP+CFNp \cdot C_{\text{FN}} \ge (1 - p) \cdot C_{\text{FP}} \quad\implies\quad \tau^* = \frac{C_{\text{FP}}}{C_{\text{FP}} + C_{\text{FN}}} This formula ONLY works if pp is a calibrated probability!

Formula Anatomy · Click Any Colored Piece to Decode It
Bayes-Optimal Decision Cutoff: τ* = C_FP / (C_FP + C_FN)

Click each term to see how asymmetric business costs shift your threshold

False Positive Cost

Cost of crying wolf (e.g., $10 SMS or manual review when transaction was legit).

Put it together with real numbers: If C_FP = $10 and C_FN = $500, then τ* = 10 / 510 = 0.0196 — flag any transaction with ≥ 2% fraud probability!
“Wait, I'm Confused...” · Teacher Office Hours Q&A

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.

Interactive Visual Lab
Lab Challenge: In the Fraud Business-Loss Simulator below, slide C_FN to $1,000 and C_FP to $15, then click 'Snap to Bayes Optimal' to see how much business loss drops compared to τ = 0.50!
Flagship Deep Lab • Cost-Sensitive Decisions

Fraud Business-Loss & Bayes-Optimal Threshold Simulator (10,000 Txns)

Total Business Loss
$51,650
FN: 94 | FP: 310
Bayes Optimal τ*
0.029
C_FP / (C_FP + C_FN)
Recall (Fraud Caught)
53.0%
TP: 106
Precision (Alert Quality)
25.5%
TN: 9490
Intuition Takeaway: Keep validation folds strictly imbalanced, calibrate probabilities on held-out logits (Platt / Isotonic / Temperature), and ship the Bayes-optimal cutoff τ* = C_FP / (C_FP + C_FN) instead of 0.50.
Where This Powers Real ML, Deep Learning & Generative AI

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.

Production NumPy & PyTorch Code Patterns
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)
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Using SMOTE before K-Fold CV.
Best Practice: Always place SMOTE inside an imblearn Pipeline so validation folds remain untouched and un-leaked.
Trap #2: Assuming high ROC-AUC means calibrated probabilities.
Best Practice: ROC-AUC only measures ranking; divide all probs by 10 and ROC-AUC is unchanged while Brier Score explodes.
Trap #3: Calibrating on the training set instead of a held-out calibration split.
Best Practice: Models are overfit on train data; always fit Platt/Isotonic/Temperature on CV out-of-fold or held-out validation logits.
Chapter Mastery Check (+70 XP)
Score: 0 / 5
1Where must SMOTE be executed inside a K-Fold cross-validation loop?
2Which calibration method fits a single scalar T > 0 to divide logits without changing top-1 accuracy?
3Which metric directly penalizes both poor ranking AND poor probability calibration?
4When does Isotonic Regression tend to overfit compared to Platt Scaling?
5What happens to predicted probabilities if you 10× oversample the minority class without correction?

Apply What You Learned — Solve Matching Coding Problems