Probability Calibration: Can You Trust the 0.8? Reliability Curves, Platt and Isotonic
When a model says 0.85, does it rain 85 times in 100? On Rain in Australia a Naive Bayes model says 0.85 and it rains 47 times. A reliability curve shows the gap, Platt and isotonic close it (ECE 0.117 to 0.039 and 0.005), and fitting the fix on training rows makes a forest worse.
What you will learn
- Draw a reliability curve and compute ECE to see if a model's scores mean what they say
- Calibrate scores with Platt scaling and isotonic regression on a separate calibration split
- Show that calibration changes the numbers but barely the ranking (AUC)
- Explain why the calibrator must never be fitted on the training rows
Before you start
- ROC Curve, AUC and Choosing a Classification Threshold
- Naive Bayes Classifier
- Train-Test Split and Data Leakage
A model gives you a score, and the score often drives a decision. So here's the question: when a model says 0.8, does it really happen eight times in ten? In this article we draw a reliability curve to find out, then fix a bad one in two ways, Platt and isotonic.
A forecaster who says 80%
Think of a weather forecaster. Every time she says 80%, we look at those days. Out of ten, it rains on eight. That's an honest 80%, and you can plan around it.
Another forecaster also says 80%, but it rains on only five days in ten. Same words, but you can't plan around them.
A model that gives a score is a forecaster too. Eight days in ten is calibrated. Five in ten is not.
Three parts, one job each
The data is Rain in Australia, predicting RainTomorrow. Two small helpers load it and split it into three parts:
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
def load_rain(path="weatherAUS.csv"):
df = pd.read_csv(path).dropna(subset=["RainTomorrow"])
y = (df["RainTomorrow"] == "Yes").astype(int)
X = df.drop(columns=["RISK_MM"]).select_dtypes("number")
return X, y
def three_way_split(X, y, seed=42):
"""60% to train, 20% to calibrate, 20% to test."""
X_train, X_rest, y_train, y_rest = train_test_split(
X, y, test_size=0.4, stratify=y, random_state=seed)
X_cal, X_test, y_cal, y_test = train_test_split(
X_rest, y_rest, test_size=0.5, stratify=y_rest, random_state=seed)
return X_train, X_cal, X_test, y_train, y_cal, y_test
train 85315 cal 28439 test 28439
142,193 days with 16 number columns, and it rains on about 22 days in 100. The model learns from train. The calibrators learn from cal, which the model never sees. Test is only for scoring. (RISK_MM is dropped because it leaks the answer; see Train-Test Split and Data Leakage.)
The model ranks the days well
from sklearn.impute import SimpleImputer
from sklearn.metrics import roc_auc_score
from sklearn.naive_bayes import GaussianNB
from sklearn.pipeline import make_pipeline
X, y = load_rain()
X_train, X_cal, X_test, y_train, y_cal, y_test = three_way_split(X, y)
model = make_pipeline(SimpleImputer(strategy="median"), GaussianNB())
model.fit(X_train, y_train)
p_cal = model.predict_proba(X_cal)[:, 1]
p_test = model.predict_proba(X_test)[:, 1]
print(f"AUC on test {roc_auc_score(y_test, p_test):.3f}")
AUC on test 0.828
Naive Bayes behind a median imputer. An AUC of 0.828 means a rainy day scores above a dry day in about 83 pairs out of 100 (more on AUC). So the ranking is fine. But does a score of 0.85 really mean 85 in 100?
The reliability curve and ECE
Group the calibration days by score into ten bins, and in each bin compare the average score with the share of days it really rained:
def reliability(y, p, bins=10):
"""Per bin: days, average score, share that really rained."""
y = np.asarray(y)
idx = np.minimum((p * bins).astype(int), bins - 1)
rows = []
for b in range(bins):
m = idx == b
if m.any():
rows.append((int(m.sum()), p[m].mean(), y[m].mean()))
return rows
def ece(y, p, bins=10):
"""Average gap between score and outcome, weighted by days."""
rows = reliability(y, p, bins)
total = sum(n for n, _, _ in rows)
return sum(n * abs(said - rained) for n, said, rained in rows) / total
for days, said, rained in reliability(y_cal, p_cal):
print(f"said {said:.2f} rained {rained:.2f} ({days} days)")
print(f"ECE on cal {ece(y_cal, p_cal):.3f}")
said 0.02 rained 0.08 (17585 days)
said 0.14 rained 0.23 (1781 days)
said 0.25 rained 0.28 (1022 days)
said 0.35 rained 0.31 (786 days)
said 0.45 rained 0.34 (686 days)
said 0.55 rained 0.37 (588 days)
said 0.65 rained 0.46 (610 days)
said 0.75 rained 0.46 (659 days)
said 0.85 rained 0.47 (872 days)
said 0.98 rained 0.67 (3850 days)
ECE on cal 0.119
Each line is one dot on the reliability curve. Days scored near 0.85 had rain on only 47 in 100. The model said 85 and it rained 47. That's a big gap.
ECE (expected calibration error) turns the curve into one number: the average gap between "said" and "rained", weighted by how many days sit in each bin. Here it's 0.119. A perfectly calibrated model scores 0.
Fix 1: Platt scaling, a sigmoid
Platt fits a plain logistic regression on the score, using the calibration part:
from sklearn.linear_model import LogisticRegression
# Platt: a sigmoid fitted on the scores
platt = LogisticRegression().fit(p_cal.reshape(-1, 1), y_cal)
The result is a sigmoid with just two numbers: a = 3.09 and b = -2.30. A score of 0.90 rides up that curve and comes out as 0.62. Two numbers, one smooth bend.
Fix 2: isotonic regression, a staircase
from sklearn.isotonic import IsotonicRegression
# isotonic: a staircase that only goes up
iso = IsotonicRegression(out_of_bounds="clip").fit(p_cal, y_cal)
print(f"score 0.90 becomes {platt.predict_proba([[0.9]])[0, 1]:.2f}"
f" (Platt), {iso.predict([0.9])[0]:.2f} (isotonic)")
score 0.90 becomes 0.62 (Platt), 0.53 (isotonic)
No formula this time, just steps: a staircase that only goes up, with 58 different step heights, following the dots. The same 0.90 becomes 0.53. Isotonic lets the data pick the shape; its one rule is that the curve never goes down.
Only now: score all three on the test part
p_platt = platt.predict_proba(p_test.reshape(-1, 1))[:, 1]
p_iso = iso.predict(p_test)
scored = (("raw", p_test), ("platt", p_platt), ("isotonic", p_iso))
for name, p in scored:
print(f"{name:<9} ECE {ece(y_test, p):.3f}"
f" AUC {roc_auc_score(y_test, p):.3f}")
raw ECE 0.117 AUC 0.828
platt ECE 0.039 AUC 0.828
isotonic ECE 0.005 AUC 0.827
The raw curve mostly sits below the diagonal. Platt pulls it much closer (ECE 0.039), and isotonic sits right on the diagonal (0.005). Meanwhile the AUC barely moves: 0.828, 0.828, 0.827. Calibration changes the numbers, not the order.
Fit the fix on rows the model never saw
We've been following one rule: the calibrator learns from the calibration part. Let's break it on purpose, with a random forest, and fit isotonic on the training rows instead. These are the two key lines inside the loop of wrong_way.py, where fit_iso is the same IsotonicRegression(out_of_bounds="clip") fit, and the results are averaged over ten splits:
right = fit_iso(p_cal, y_cal)
wrong = fit_iso(p_train, y_train)
naive bayes: test ECE raw 0.120, fitted on cal 0.007, fitted on train 0.006
fitted on train was worse than raw in 0 of 10 splits
forest: test ECE raw 0.015, fitted on cal 0.005, fitted on train 0.136
fitted on train was worse than raw in 10 of 10 splits
Fitted on cal, the forest's ECE drops from 0.015 to 0.005. Fitted on train, it jumps to 0.136, far worse than doing nothing, and worse than raw on all ten splits. A forest has already seen its training rows, so they're the wrong place to learn the fix. Naive Bayes barely notices, but don't count on that.
Does it hold on other splits?
One split isn't enough, so seeds.py repeats the check on ten splits for both models:
naive bayes: ECE raw 0.120 Platt 0.043 isotonic 0.007
better than raw, of 10 splits: Platt 10, isotonic 10
forest: ECE raw 0.015 Platt 0.023 isotonic 0.005
better than raw, of 10 splits: Platt 0, isotonic 10
For Naive Bayes, both fixes beat raw on all ten splits. The forest is different: it's already close (0.015). Isotonic still helps on all ten, but Platt never beat raw on any of them. So calibrate when the curve says so, and check before you assume.
Common mistakes
- Reading a good AUC as good probabilities. AUC 0.828 and a score of 0.85 that rains 47% of the time live happily together.
- Fitting the calibrator on the training rows. It made the forest's ECE nine times worse than raw.
- Calibrating and scoring on the same rows. Keep three parts: train, calibrate, test.
- Calibrating by habit. Platt made an already-good forest worse. Look at the curve first.
Recap
| Tool | What it does | Test ECE here |
|---|---|---|
| Reliability curve | said vs happened, per score bin | |
| ECE | average gap, weighted by days | raw 0.117 |
| Platt | sigmoid with two numbers (a, b) | 0.039 |
| Isotonic | staircase that only goes up | 0.005 |
| AUC | ranking, barely changed by calibration | 0.828 / 0.828 / 0.827 |
Try it yourself
Add HistGradientBoostingClassifier to the models in seeds.py. Does it need calibrating? Check the curve before you decide.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →The Cost of Being Wrong: Baselines, a Price per Mistake and the Cheapest Threshold
Next →Slice Evaluation and Fairness Checks: Score the Model Group by Group
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.