Probability Calibration
After this lesson, you will be able to:
- Explain why a classifier saying 'I'm 90% sure' often does NOT mean it is right 90% of the time, and identify which models (SVM, Random Forest, Naive Bayes) are systematically miscalibrated and why
- Diagnose calibration with reliability diagrams, Brier score, and Expected Calibration Error (ECE), and know which metric tells you what
- Apply Platt scaling (sigmoid) and isotonic regression via sklearn's CalibratedClassifierCV to fix miscalibrated models, and pick the right method based on dataset size
- Avoid the leakage trap of calibrating on training data, design held-out or cross-validated calibration workflows, and monitor calibration drift in production
Before you start
Don't worry if this feels new — most ML courses skip calibration entirely, even though it is the difference between a research demo and a production-grade model.
#War Story: 80% Sure, 45% Right
predict_proba output was used to size position limits: more confidence → larger position. Their risk engine logged every prediction and the realized outcome.| Model said | Bonds in this bucket | Actual default rate |
|---|---|---|
| 10% | 412 | 8% |
| 30% | 285 | 24% |
| 50% | 198 | 41% |
| 70% | 154 | 49% |
| 80% | 91 | 45% |
| 90% | 47 | 52% |
CalibratedClassifierCV(method='isotonic', cv=5) wrapper and 15 minutes of compute fixed it. The new model's 80% bucket actually defaulted 81% of the time. Same accuracy. Same AUC. Honest probabilities. The difference between research and production is exactly this: calibration.#What "Calibrated" Actually Means
#Why Models Are Miscalibrated
Different models break calibration in different ways:
- Naive Bayes is over-confident because the conditional independence assumption breaks: when features are correlated, the probabilities multiply too aggressively, pushing outputs toward 0 or 1.
- SVMs do not produce probabilities at all — they output unbounded decision-function scores. Any "probability" you read off
predict_probais a sigmoid hack. - Random Forests average bagged tree votes. Because individual trees rarely vote 0.0 or 1.0 unanimously, RF predictions stay clustered in the middle (under-confident at the extremes, over-confident in the middle band).
- Boosted trees (XGBoost, LightGBM) with default learning rates and many rounds become over-confident as boosting drives margin upward without regularizing probabilities.
- Logistic regression trained with maximum likelihood on a well-specified problem is, by construction, calibrated. This is the "free lunch" of LR.
#Measuring Calibration
#The Reliability Diagram
The visual workhorse. You bin predictions by predicted probability, then plot the mean predicted probability on the x-axis vs. the empirical positive rate on the y-axis. A perfectly calibrated model traces the y = x diagonal.
Drag the threshold and switch base classifiers — the reliability curve shows you the exact shape of the miscalibration, and you can apply Platt scaling or isotonic regression and watch the curve snap toward the diagonal in real time.
Why does a bin average mean something? A model is calibrated when, among all cases where it says p, the fraction that are positive is p. The average of the 0/1 labels in a bin is the estimate of that fraction, which is why the code below plots the fraction of positives. The formula above is the top-label version used by Guo et al. 2017, where accuracy is the fraction of correct predictions; for the positive class, acc is the fraction of positives in the bin.
#Brier Score: The Quantitative Workhorse
The Brier score is just the mean squared error of predicted probabilities vs. true labels. Lower is better; 0 is perfect.
The code comment above says the Brier score decomposes into reliability, resolution and uncertainty. Open the derivation to see why: it uses only the fact that labels are 0 or 1.
#Expected Calibration Error (ECE)
Your random forest achieves 92% accuracy and 0.94 ROC-AUC, but the Brier score is 0.18 (relatively high). What is most likely going on?
A linear SVM trained on a binary classification task outputs values like `-1.7`, `+0.4`, `+2.3` from its decision function. Why are those numbers not probabilities?
#Two Calibration Methods
#Platt Scaling (Sigmoid Calibration)
f(x).Why a sigmoid of a straight-line score? Open the derivation to see that it is exactly the shape Bayes' theorem produces when the scores of the two classes are bell curves with the same spread.
#Isotonic Regression (Non-parametric Calibration)
Fit a piecewise-constant, monotonic function from raw scores to calibrated probabilities. More flexible than Platt but data-hungry.
The fit is found by the pool adjacent violators algorithm: walk up the sorted scores, and whenever a block's average label is higher than the next block's, merge the two and replace both by their pooled average. The result is the monotone step function with the smallest squared error. The algorithm is stated here, not derived.
#Decision Rule
- Use Platt scaling when calibration samples are scarce (<1000) or when miscalibration is a clean sigmoid distortion (typical of SVMs).
- Use isotonic regression when you have ample data (≥1000 calibration samples) and the miscalibration is non-sigmoid (typical of Random Forests, gradient-boosted trees, and modern neural networks).
- Skip calibration for properly trained logistic regression on a well-specified problem — it is already calibrated, and adding a second stage can only add variance.
You're calibrating two models: (A) an SVM with 600 training rows of a clinical dataset, and (B) a 500-tree gradient-boosted classifier with 100k rows of e-commerce click data. Which calibration method should you choose for each?
Expected Calibration Error (ECE) over 10 bins is 0.04. What does that number actually represent?
#Hands-On: Calibrating a Random Forest
Tests: Verify that the calibrated Brier scores are lower than the uncalibrated baseline. Check that ECE drops for both Platt and isotonic methods. Confirm the reliability gap shrinks after calibration.
#Reliability Diagrams in Action
#Concrete before/after: Random Forest under isotonic calibration
CalibratedClassifierCV(method='isotonic', cv=5):| Mean predicted prob | Empirical positive rate (raw RF) | Empirical positive rate (isotonic) |
|---|---|---|
| 0.10 | 0.18 | 0.11 |
| 0.30 | 0.42 | 0.31 |
| 0.50 | 0.61 | 0.50 |
| 0.70 | 0.65 | 0.69 |
| 0.90 | 0.71 | 0.88 |
Let's reproduce that same before-vs-after experiment live. Train a Random Forest, compute Brier and ECE, then overlay the raw, Platt-scaled and isotonic calibration curves on a single reliability diagram.
#Multi-Class Calibration
CalibratedClassifierCV calibrates each class one-vs-rest, then renormalizes. This is not perfect. It can produce probabilities that do not sum exactly to 1 before renormalization, but it works well in practice. For deep learning, temperature scaling (a single scalar parameter dividing logits before softmax) is the dominant modern technique because it preserves the argmax (so accuracy is unchanged) while fixing over-confidence.Why does temperature scaling leave accuracy alone yet change the confidence? Open the derivation to see both facts, and why the single parameter T is easy to fit.
Slide T and watch the confidence move while the accuracy stays fixed, then press Fit T to land on the bottom of the NLL valley.
#Common Mistakes
#Production Calibration
#Key Takeaways
- Calibration is whether stated confidence matches empirical accuracy. When a calibrated model says 0.7, it should be right 70% of the time; this is independent from accuracy and must be measured separately
- Most classifiers are NOT calibrated by default. Naive Bayes pushes to extremes, SVMs need a sigmoid hack, Random Forests cluster in the middle, boosted trees over-confident, modern deep nets often over-confident; only well-trained logistic regression is calibrated for free
- Brier score, ECE, and reliability diagrams are the diagnostic trio. Brier captures calibration plus discrimination, ECE isolates calibration alone, the reliability diagram shows you where the miscalibration lives across the probability range
- Platt scaling for small data and sigmoid distortions, isotonic for large data and complex shapes — sklearn's
CalibratedClassifierCV(method='sigmoid' or 'isotonic', cv=5)is the one-line fix for nearly every classifier - Calibration drifts in production. Monitor ECE alongside accuracy, recalibrate on schedule, and segment by subgroup to catch hidden miscalibration that global metrics mask
#Quick Check
A Random Forest has accuracy 0.91 and ROC-AUC 0.95, but Brier score 0.16 (high). What is the most likely diagnosis?
#The Bridge Forward
Calibration is one of the last three checks before a model ships:
- Model Evaluation told you whether the model is right. Calibration tells you whether the model knows whether it's right.
- Model Interpretation explains why a prediction was made, but only if the prediction itself is honest. SHAP on an uncalibrated model attributes a distorted probability, which is misleading.
- Hyperparameter Tuning maximizes a metric (often AUC) that says nothing about calibration. Tune for discrimination, then calibrate. Don't expect tuning to fix calibration; it won't.