Calibration Curve in Python: Check and Fix Predicted Probabilities

Plot a calibration curve in Python with scikit-learn's CalibrationDisplay, see which models give trustworthy probabilities, and fix the ones that don't with CalibratedClassifierCV.

To check whether a classifier's probabilities can be trusted, plot a calibration curve with CalibrationDisplay.from_estimator(model, X_test, y_test) in scikit-learn. It groups predictions into bins and plots the actual fraction of positives against the mean predicted probability in each bin. A well-calibrated model hugs the diagonal: of the cases it scores near 0.8, about 80% turn out positive. The code below targets scikit-learn 1.9.

Quick Example

This fits three models on a synthetic balanced classification problem and draws their calibration curves on one set of axes. It runs without downloads.

import matplotlib.pyplot as plt
from sklearn.calibration import CalibrationDisplay
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss, roc_auc_score
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB

X, y = make_classification(n_samples=30000, n_features=20, n_informative=5,
                           n_redundant=0, n_repeated=10, class_sep=0.6,
                           flip_y=0, random_state=8)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5,
                                                    random_state=8)

models = {
    "Logistic regression": (LogisticRegression(max_iter=1000), "#0f766e"),
    "Random forest": (RandomForestClassifier(n_estimators=200, random_state=8,
                                             n_jobs=-1), "#b45309"),
    "Gaussian naive Bayes": (GaussianNB(), "#7c3aed"),
}

fig, ax = plt.subplots(figsize=(6.2, 6))
for name, (model, color) in models.items():
    model.fit(X_train, y_train)
    CalibrationDisplay.from_estimator(model, X_test, y_test, n_bins=10,
                                      name=name, ax=ax, color=color, lw=2,
                                      marker="o")
ax.set(title="Calibration curves", xlabel="Mean predicted probability",
       ylabel="Fraction of positives")
ax.legend(loc="upper left")

for name, (model, _) in models.items():
    p = model.predict_proba(X_test)[:, 1]
    print(name, "brier", round(brier_score_loss(y_test, p), 4),
          "auc", round(roc_auc_score(y_test, p), 4))

Calibration curves for logistic regression, random forest and Gaussian naive Bayes; logistic regression is near the diagonal, the random forest is S-shaped around it, and naive Bayes sits well above it at low probabilities and below it at high ones

The dotted diagonal is perfect calibration. A curve above it means the model's predictions are too low: the events happen more often than it says. A curve below it means they are too high. Here:

  • Logistic regression stays close to the diagonal (the largest gap in any bin is 0.06). This is typical, because it is trained to minimize log loss, which rewards honest probabilities.
  • Random forest is S-shaped. Cases it scores around 0.15 are positive only 4% of the time, and cases it scores around 0.85 are positive 96% of the time. The forest is underconfident, since averaging many trees pulls scores toward the middle.
  • Gaussian naive Bayes is off by the most: cases scored near 0.03 are positive 10% of the time, and cases scored around 0.75 are positive only 63% of the time. Naive Bayes treats correlated features as independent evidence, and with 10 repeated columns in this data it counts the same signal repeatedly. That pushes scores toward 0 and 1 more than the data supports.

Why Calibration and Ranking Are Different Questions

The random forest has by far the best AUC here (0.985, against 0.873 for logistic regression and 0.866 for naive Bayes) and also the lowest Brier score of the three (0.051), yet its probabilities are visibly off. AUC only asks whether positives get higher scores than negatives. A model can rank perfectly and still report 0.15 for something that happens 4% of the time.

Calibration matters whenever the probability itself is used: expected-value decisions ("act if P(churn) × value > cost"), risk scores shown to people, or combining model outputs. If you only rank or pick a top-k, it matters much less. See the ROC curve post for the ranking view.

Read the Histogram Beside the Curve

Each point on a calibration curve is a bin, and some bins hold far more predictions than others. Plot the distribution of predicted probabilities next to the curve to see which parts of it matter.

fig, axes = plt.subplots(1, 3, figsize=(11, 3.4), sharey=True)
for ax, (name, (model, color)) in zip(axes, models.items()):
    p = model.predict_proba(X_test)[:, 1]
    ax.hist(p, bins=20, range=(0, 1), color=color)
    ax.set(title=name, xlabel="Predicted probability")
axes[0].set_ylabel("Count")
fig.tight_layout()

Histograms of predicted probabilities for three models; the random forest and naive Bayes pile up at 0 and 1 while logistic regression is spread more evenly

Half of the random forest's predictions (50%) land below 0.05 or above 0.95, so its wobbly middle bins describe relatively few cases. Logistic regression spreads its predictions across the range, so every bin on its curve carries weight.

Fix It with CalibratedClassifierCV

CalibratedClassifierCV wraps a model and learns a mapping from its raw scores to better probabilities. It has two methods:

  • method="sigmoid" (the default) fits a logistic curve to the scores. This is Platt scaling. It has two parameters, so it works with little data, but it assumes the distortion is S-shaped.
  • method="isotonic" fits a free-form increasing step function. It can fix any monotonic distortion but needs more data (a common rule of thumb is thousands of samples) and can overfit on small sets.
from sklearn.calibration import CalibratedClassifierCV

variants = {
    "Random forest (raw)": (RandomForestClassifier(n_estimators=200, random_state=8,
                                                   n_jobs=-1), "#b45309"),
    "Sigmoid (Platt)": (CalibratedClassifierCV(
        RandomForestClassifier(n_estimators=200, random_state=8, n_jobs=-1),
        method="sigmoid", cv=5), "#2563eb"),
    "Isotonic": (CalibratedClassifierCV(
        RandomForestClassifier(n_estimators=200, random_state=8, n_jobs=-1),
        method="isotonic", cv=5), "#dc2626"),
}
fig, ax = plt.subplots(figsize=(6.2, 6))
for name, (model, color) in variants.items():
    model.fit(X_train, y_train)
    CalibrationDisplay.from_estimator(model, X_test, y_test, n_bins=10,
                                      name=name, ax=ax, color=color, lw=2,
                                      marker="o")
    p = model.predict_proba(X_test)[:, 1]
    print(name, "brier", round(brier_score_loss(y_test, p), 4),
          "auc", round(roc_auc_score(y_test, p), 4))
ax.set(title="Random forest before and after calibration",
       xlabel="Mean predicted probability", ylabel="Fraction of positives")
ax.legend(loc="upper left")

Calibration curves for a random forest raw, with sigmoid calibration and with isotonic calibration; the isotonic curve follows the diagonal most closely

On this data, isotonic calibration pulls the random forest's S-shape onto the diagonal almost completely, while the sigmoid version over-corrects in places, because the forest's distortion isn't a clean S. The Brier score improves from 0.0513 to 0.0483 (isotonic) and 0.0488 (sigmoid). AUC barely moves (0.9849 raw, 0.9845 isotonic, 0.9846 sigmoid), because calibration is a monotonic remapping that mostly keeps the ranking. These are results from a single split of one synthetic dataset, so treat the gap between sigmoid and isotonic as illustrative.

Two details:

  • CalibratedClassifierCV takes an unfitted estimator and uses cv=5 to fit the calibrator on predictions the model didn't train on. That is why it is passed a fresh RandomForestClassifier. To calibrate an already-fitted model on a separate held-out set, wrap it in FrozenEstimator from sklearn.frozen: CalibratedClassifierCV(FrozenEstimator(fitted_model)).fit(X_calib, y_calib). That is the replacement for the old cv="prefit" option.
  • Evaluate on data that neither the model nor the calibrator saw, as above.

Measure Calibration with the Brier Score

A curve is something you look at. brier_score_loss(y_true, y_prob) gives one number: the mean squared difference between the predicted probability and the 0/1 outcome. Lower is better, and 0 is perfect. It combines calibration and ranking, so it can fall because of either. Compare Brier scores for the same data and the same task, and read it next to the curve and AUC rather than alone.

Choosing Bins: uniform vs quantile

CalibrationDisplay.from_estimator defaults to n_bins=5 and strategy="uniform" (equal-width bins on 0 to 1). Two things to know:

  • Use n_bins=10 on test sets of a few thousand rows or more. Fewer bins hide structure, and more bins make each point noisy.
  • strategy="quantile" puts the same number of predictions in every bin. It is the better choice for a model that piles up at the extremes, like the random forest here: with uniform bins, the middle holds few points and the extremes hold thousands, while quantile bins give every point equal support. The bin positions then bunch near 0 and 1 and spread out in the middle.

Practical Tips

  • Imbalanced data: on rare events most predictions sit near 0, so most uniform bins hold only a handful of predictions. Use strategy="quantile" and look at the PR curve too: Precision-Recall Curve in Python.
  • Small test sets make noisy curves. A bin with 30 samples has a standard error of about 9 percentage points near 0.5. Don't read much into a wiggle.
  • Recalibrate when the data shifts. A model calibrated on last year's traffic can drift. Re-check the curve on recent data.
  • Don't calibrate what you only rank. It adds a step and a failure point for no gain.

Similar Topics