Sub topic 5
Reading a reliability diagram
This chapter assumes you know binary classification, train/test splits, and basic scikit-learn and NumPy. You should also know that a model's predict_proba output is a number between 0 and 1. The previous chapters defined calibration: among all cases where a model predicts 0.8, about 80% should be positive. Here you will learn to check that claim visually.
What a reliability diagram shows
A reliability diagram (also called a calibration curve) plots predicted probability against observed frequency. You build it in four steps:
- Collect predicted probabilities for a set of held-out examples.
- Group the examples into bins by predicted probability.
- In each bin, compute the mean predicted probability and the fraction of examples that are actually positive.
- Plot one point per bin: mean predicted probability on the x axis, observed fraction positive on the y axis.
A perfectly calibrated model puts every point on the diagonal, where y equals x. Points below the diagonal mean the model is overconfident in that range, because it predicts more positives than occur. Points above the diagonal mean the model is underconfident there.
Always build the diagram on data the model did not train on. On training data, flexible models such as deep trees or boosted ensembles look better calibrated than they are.
Computing the points
scikit-learn provides calibration_curve. It returns the observed fractions first and the mean predictions second, in that order.
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.calibration import calibration_curve
X, y = make_classification(
n_samples=20000, n_features=20, n_informative=5, n_redundant=10, random_state=0
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.5, random_state=0
)
model = GaussianNB().fit(X_train, y_train)
p = model.predict_proba(X_test)[:, 1]
frac_pos, mean_pred = calibration_curve(y_test, p, n_bins=10, strategy="quantile")
for m, f in zip(mean_pred, frac_pos):
print(f"mean predicted {m:.2f} -> observed fraction positive {f:.2f}")Naive Bayes is a good model for this demonstration. It assumes features are independent, but this dataset has 10 redundant features that are linear combinations of the informative ones. The model counts the same evidence several times, so it pushes probabilities toward 0 and 1. The output shows low predictions that are too low and high predictions that are too high relative to what actually happens. The curve then has the characteristic S shape described below.
Drawing the plot
If matplotlib is installed, you can draw the diagram from the same values. Continue from the code above:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(5, 5))
ax.plot([0, 1], [0, 1], linestyle="--", color="gray", label="Perfectly calibrated")
ax.plot(mean_pred, frac_pos, marker="o", label="GaussianNB")
ax.set_xlabel("Mean predicted probability")
ax.set_ylabel("Observed fraction positive")
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.legend()
plt.show()Keep both axes on the same 0 to 1 range and draw the plot square. A stretched axis makes small gaps look large, or the reverse.
Common shapes
The shape of the curve tells you what kind of miscalibration you have.
| Shape of the curve | Meaning | Typical sources |
|---|---|---|
| Close to the diagonal | Probabilities are about right | Logistic regression with enough data, well-regularized models |
| S shape (below the diagonal on the right side, above it on the left) | Overconfident: probabilities too extreme | Naive Bayes, neural networks trained long, boosted trees with many rounds |
| Inverted S shape (above the diagonal on the right, below it on the left) | Underconfident: probabilities pushed toward the middle | Random forests, bagging, SVMs with Platt-style outputs, boosting with exponential loss |
| Entirely above or below the diagonal | Systematically too low or too high | Class prior changed between training and deployment |
Overconfident versus underconfident is the key distinction, and a later chapter on temperature scaling uses it directly. Overconfidence needs the scores shrunk toward 0.5, and underconfidence needs them stretched.
Binning choices
The diagram depends on how you form bins. There are two strategies in calibration_curve.
strategy="uniform"makes equal-width bins, such as 0.0 to 0.1, 0.1 to 0.2, and so on.strategy="quantile"makes bins with equal numbers of examples.
Uniform bins are easy to read, because the x axis positions are predictable. Their weakness is that many models put most predictions near 0 or 1. Then a handful of middle bins hold few examples, and the high-density bins at the edges hide detail inside one wide interval. Quantile bins give each point the same amount of data, so each point has a similar noise level. Their weakness is that the bin edges depend on the data, so two models or two datasets get different bins and are harder to compare point by point.
The number of bins is a trade-off between bias and variance:
- Few bins average over wide ranges. A curve can look calibrated while hiding errors that cancel within a bin.
- Many bins give each point few examples. The observed fraction then bounces around from sampling noise alone.
With 10,000 test examples, 10 to 20 bins is a reasonable start. With 500 examples, use 5 or fewer, or the points will mostly show noise.
Reading noise correctly
Each point is an estimate of a proportion, so it has a standard error of roughly sqrt(q(1 - q) / n), where q is the observed fraction and n is the bin size. A bin with 50 examples and q = 0.5 has a standard error near 0.07. A point 0.05 away from the diagonal in that bin is not evidence of miscalibration.
Check this before drawing conclusions:
- Count the examples in each bin. Print them next to the points, or add a histogram of predictions below the curve.
- Add error bars, or at least compute the standard error for the bins that look off.
- Look for a pattern across neighboring bins. A consistent drift in one direction means more than one stray point.
A histogram of predicted probabilities is a useful companion to the curve. It shows where the model actually places its predictions, and so which parts of the curve matter. A sharp model has most mass near 0 and 1. A model with most mass near the base rate gives little decision-making information, even if its curve is perfect.
import numpy as np
counts, edges = np.histogram(p, bins=10, range=(0, 1))
for lo, hi, c in zip(edges[:-1], edges[1:], counts):
print(f"[{lo:.1f}, {hi:.1f}): {c} examples")Limits of the diagram
A reliability diagram is a diagnostic, and it does not tell you everything.
- It measures only calibration. A model that predicts the base rate for every example is calibrated and useless. The diagonal says nothing about whether the model separates positives from negatives.
- Binning discards information. Two models with identical curves can have different Brier scores, because the curve ignores how predictions are spread within each bin.
- It covers one class in binary problems. For multiclass models you must decide whether to plot the top predicted class's confidence or one curve per class. A later chapter covers this.
- It reflects one dataset. A curve built on a test set that differs from production data tells you about the test set.
For these reasons, pair the diagram with a numeric score. The next chapter introduces log loss and Brier score for that purpose.
Exercises
Exercise
A reliability diagram for a classifier shows a point at mean predicted probability 0.90 and observed fraction positive 0.72. The bin contains 2,000 examples. What does this tell you about the model in that range, and how confident can you be in the conclusion?
Show answer
The model is overconfident there: it predicts 90% but only 72% of cases are positive, so the point lies below the diagonal. With 2,000 examples the standard error is about sqrt(0.72 × 0.28 / 2000) ≈ 0.01, so a gap of 0.18 is far larger than sampling noise and is real miscalibration.
Exercise
You have 400 test examples and plot a reliability diagram with 20 uniform bins. Several points scatter widely above and below the diagonal. Give two changes that would make the diagram more trustworthy, and say why each helps.
Show answer
Reduce the number of bins (for example to 5), or switch to quantile bins. Both give each bin more examples, which lowers the standard error of each observed fraction. You could also add error bars or a histogram of bin counts so that noisy bins are visible as such.
Exercise
A model's reliability curve lies exactly on the diagonal, but its predictions are all between 0.48 and 0.52 on a dataset with a 50% positive rate. Is the model useful? Why or why not?
Show answer
It is calibrated but nearly useless for discrimination. Every prediction is close to the base rate, so the model cannot separate likely positives from likely negatives. The diagonal shows calibration only, so you also need AUC or a scoring rule to judge usefulness.