DataSpanner

How to Calibrate Your Classifier’s Probabilities in Scikit-learn

By Dataspanner Editorial · · 9 min read · Analytics

How to Calibrate Your Classifier’s Probabilities in Scikit-learn — Analytics cover illustration

Introduction

When a machine‑learning model tells you “there’s a 0.87 chance that this customer will churn,” you usually treat that number as a reliable confidence level. In practice, many classifiers—especially those that are not explicitly probabilistic—produce scores that look convincing but are systematically off. A model that consistently says “0.9” while only 60 % of those cases actually belong to the positive class is mis‑calibrated.

Calibration is the process of adjusting those raw probabilities so that they reflect real‑world frequencies. It does not change the ranking ability of a model (its ROC‑AUC stays the same); it merely aligns the numeric confidence with observed outcomes.

In this guide you will walk through a complete, end‑to‑end workflow using Scikit‑learn:

  1. Prepare a realistic dataset and split it into train, calibration, and test slices.
  2. Train two classic classifiers that tend to mis‑behave in opposite ways.
  3. Diagnose the mis‑calibration with a reliability diagram and the Brier score.
  4. Apply Platt scaling and isotonic regression to correct the probabilities.
  5. Verify that calibration improves the scores without harming ranking performance.

All of this is illustrated with clean, commented Python code, an ASCII architecture sketch, and a few practical notes from Dataspanner’s production experience.


Why Calibration Matters

Think of a weather app that always reports a 30 % chance of rain, but in reality it rains on 70 % of those days. Users would either ignore the app (because it under‑estimates risk) or be constantly surprised (because it over‑estimates). Calibration is the same idea for classifiers: the numeric output should be a trustworthy estimate of the true probability.

A well‑calibrated model lets you:

  • Set optimal decision thresholds – you can pick a cut‑off that balances precision, recall, and business cost because the probability values are meaningful.
  • Combine multiple models – ensemble methods often rely on probability inputs; mis‑calibrated sources can skew the final vote.
  • Explain to stakeholders – a business user can trust “there’s a 78 % chance of default” because the model’s confidence matches historical data.

Accuracy and ROC‑AUC are useful for assessing ranking, but they give no insight into whether “0.8” really means “80 %”. A model can achieve perfect ROC‑AUC while being completely over‑confident (predicting 0.99 for all positives). Calibration closes that gap.


Setting Up a Minimal Reproducible Playground

Below is a self‑contained script that follows the three‑way split recommended by Scikit‑learn’s calibration guide. The split protects the calibration step from “data leakage” – the calibrator should never see the test set, nor should it be trained on the same data that produced the raw probabilities.

# --------------------------------------------------------------
# calibrate_classifier.py
# --------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
from sklearn.calibration import (
    CalibratedClassifierCV,
    CalibrationDisplay,
)
from sklearn.datasets import fetch_covtype
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import (
    brier_score_loss,
    log_loss,
    roc_auc_score,
)
from sklearn.frozen import FrozenEstimator   # for pre‑fitted calibrators

RANDOM_STATE = 42

# ---- 1. Load and simplify the data ---------------------------------
# The Covertype dataset contains 7 forest cover types.
# We reduce it to a binary problem: "Spruce/Fir" (class 1) vs the rest.
X, y = fetch_covtype(return_X_y=True)
y = (y == 1).astype(int)                     # 1 = target class, 0 = everything else

# Use a subset to keep training fast while preserving the lesson.
rng = np.random.default_rng(RANDOM_STATE)
subset = rng.choice(len(X), size=100_000, replace=False)
X, y = X[subset], y[subset]

print(f"Dataset size: {X.shape[0]:,} rows, {X.shape[1]:,} features")
print(f"Positive class share: {y.mean():.3f}")

# ---- 2. Three‑way split: train / calibration / test -----------------
# 50 % train, 20 % calibration, 30 % test (stratified to keep class balance)
X_train, X_rest, y_train, y_rest = train_test_split(
    X, y,
    train_size=0.5,
    stratify=y,
    random_state=RANDOM_STATE,
)

X_cal, X_test, y_cal, y_test = train_test_split(
    X_rest, y_rest,
    train_size=0.4,          # 0.4 of the remaining 50 % = 20 % of total
    stratify=y_rest,
    random_state=RANDOM_STATE,
)

print(f"Train / Calibration / Test: {len(X_train):,} / {len(X_cal):,} / {len(X_test):,}")
# --------------------------------------------------------------

Explanation of the split

  • Train – the model learns its parameters.
  • Calibration – a dedicated slice where the calibrator learns how to remap raw scores. Because a model is usually over‑confident on its own training data, using a separate calibration set prevents “self‑cheating”.
  • Test – untouched until the final evaluation; it provides an unbiased view of the calibrated probabilities.

Building Two Classic, Mis‑calibrated Classifiers

Logistic regression often starts out calibrated, but other algorithms have characteristic distortion patterns. We will train two that tend to behave oppositely:

Model Typical Calibration Behaviour
Gaussian Naïve Bayes Pushes probabilities toward the extremes (0 or 1).
Random Forest Tends to stay away from the extremes, producing a “flattened” distribution.
# ---- 3. Train the raw models ---------------------------------------
models = {
    "GaussianNB": GaussianNB(),
    "RandomForest": RandomForestClassifier(
        n_estimators=200,
        n_jobs=-1,
        random_state=RANDOM_STATE,
    ),
}

# Fit each model on the *training* data only
for name, estimator in models.items():
    estimator.fit(X_train, y_train)

# Helper to extract the probability of the positive class
raw_probs = {
    name: est.predict_proba(X_test)[:, 1]
    for name, est in models.items()
}

Diagnosing the Calibration Gap

3.1 A Quick “Does 0.9 Mean 90 %?” Check

def ninety_test(name, prob, y_true, low=0.85, high=0.95):
    """Count how many samples in [low, high) are actually positive."""
    mask = (prob >= low) & (prob < high)
    if mask.sum() == 0:
        print(f"{name:12} No samples in [{low}, {high})")
        return
    actual = y_true[mask].mean()
    print(
        f"{name:12} In [{low},{high}) → {actual:.1%} "
        f"({mask.sum()} samples)"
    )

Running ninety_test on the raw probabilities reveals that the Random Forest often reports a 0.9 score but only a fraction of those cases are truly positive, while GaussianNB may under‑promise.

3.2 Scoring Summary

def print_scores(y_true, prob_dict):
    print(f"{'Model':>12} {'LogLoss':>10} {'ROC‑AUC':>9} {'Brier':>9}")
    for name, prob in prob_dict.items():
        print(
            f"{name:>12} {log_loss(y_true, prob):>10.4f} "
            f"{roc_auc_score(y_true, prob):>9.4f} "
            f"{brier_score_loss(y_true, prob):>9.4f}"
        )

Log loss penalises confident mistakes, ROC‑AUC measures ranking, and the Brier score (mean squared error between predicted probability and true label) directly quantifies calibration error—lower is better.

3.3 Reliability Diagram (Calibration Curve)

def reliability_plot(y_true, prob_dict, title):
    fig, (ax_curve, ax_hist) = plt.subplots(
        2, 1, figsize=(7, 9),
        gridspec_kw={"height_ratios": [3, 1]}, sharex=True
    )

    for i, (name, prob) in enumerate(prob_dict.items()):
        CalibrationDisplay.from_predictions(
            y_true, prob,
            n_bins=10,
            name=name,
            ax=ax_curve,
            ref_line=(i == 0)          # draw diagonal only for the first curve
        )
        # Histogram of raw predictions (under the curve)
        ax_hist.hist(prob, bins=10, range=(0, 1),
                     histtype="step", label=name)

    ax_curve.set_title(title)
    ax_curve.set_xlabel("")
    ax_hist.set_xlabel("Mean predicted probability")
    ax_hist.set_ylabel("Count")
    ax_hist.legend(loc="upper center")
    plt.tight_layout()
    plt.show()

The diagram visually tells you whether the model’s confidence matches reality. Points on the diagonal indicate perfect calibration; systematic deviation shows over‑ or under‑confidence.

When you run the three helpers on raw_probs, you will see a clear mismatch: the Random Forest’s curve will sit above the diagonal for low scores (over‑confident) and below for high scores, while GaussianNB may show the opposite pattern.


Calibrating the Models

Scikit‑learn provides two built‑in calibrators that work on top of any classifier:

  • Platt scaling – fits a logistic regression model to the raw scores. It assumes a smooth, sigmoid‑shaped distortion.
  • Isotonic regression – fits a piecewise‑constant, non‑decreasing function. It can correct arbitrary monotonic distortions but may over‑fit on small calibration sets.

Both are wrapped in CalibratedClassifierCV. The cv argument is set to "prefit" (or CalibratedClassifierCV(..., cv=None, method='prefit') in newer versions) to indicate that the base model is already trained and we only need to fit the calibrator on the calibration slice.

# ---- 4. Calibrate each model ---------------------------------------
from sklearn.calibration import CalibratedClassifierCV

# Store calibrated versions
calibrated = {}

for name, raw_model in models.items():
    # Choose a calibrator – you can switch between 'sigmoid' (Platt) and 'isotonic'
    calibrated[name + "_Platt"] = CalibratedClassifierCV(
        raw_model,
        method='sigmoid',          # Platt scaling
        cv='prefit',               # use the already‑fitted raw model
    ).fit(X_cal, y_cal)

    calibrated[name + "_Isotonic"] = CalibratedClassifierCV(
        raw_model,
        method='isotonic',
        cv='prefit',
    ).fit(X_cal, y_cal)

Why a separate calibration set?
If you were to fit the calibrator on the training data, the model would have already “seen” those examples and would produce probabilities that are too tight around the training labels. A dedicated calibration slice mimics the real‑world distribution without contaminating the final test evaluation.


Evaluating the Calibrated Probabilities

After calibration, we repeat the same diagnostics. The expectation is that the reliability curves move toward the diagonal while the ROC‑AUC remains unchanged (calibration does not alter ranking).

# ---- 5. Collect calibrated probabilities ----------------------------
calibrated_probs = {}
for name, calibrated_model in calibrated.items():
    calibrated_probs[name] = calibrated_model.predict_proba(X_test)[:, 1]

# ---- 6. Print scores side‑by‑side ------------------------------------
print("\n=== CALIBRATED SCORES ===")
print_scores(y_test, calibrated_probs)

# ---- 7. Plot reliability diagrams ------------------------------------
reliability_plot(calibrated_probs, "Reliability diagram: calibrated models")

Running the script typically shows a dramatic reduction in the Brier score for both calibrators, and the curves hugging the diagonal much more closely than the raw versions.


Dataspanner's Perspective

6.1 Real‑World Architecture Trade‑offs

At Dataspanner we often see two opposing pressures when dealing with probabilistic models:

Concern Typical Dataspanner Approach
Latency Calibration adds a lightweight post‑processing step (a few matrix multiplications for Platt, or a simple lookup table for isotonic). In production pipelines this overhead is negligible compared to feature extraction and model inference.
Data Volume Large‑scale training runs (millions of rows) make it feasible to carve out a permanent calibration slice. We treat the calibration set as a monitoring dataset that is refreshed quarterly, similar to our data‑quality dashboards.
Model Drift Because calibration is model‑specific, we keep a separate calibrator service that can be versioned independently. This mirrors our feature‑store philosophy where embeddings and retrieval models are decoupled from serving logic.
Cost Platt scaling is cheap (single logistic regression). Isotonic regression can produce many breakpoints; we limit the number of bins (e.g., max_iter=1000) and prune rarely used bins to keep the serving footprint small.

6.2 When NOT to Calibrate

  • Pure ranking tasks – If the downstream system only cares about ordering (e.g., recommendation lists) and not about the numeric confidence, calibration may add unnecessary complexity.
  • Very small calibration sets – Isotonic regression can over‑fit; Platt scaling is more robust but still benefits from a few thousand examples.
  • Real‑time constraints with limited compute – If inference must happen on a tiny edge device, the extra parameters of isotonic regression may be prohibitive; a simple Platt scaler (or even a static scaling factor) may be sufficient.

6.3 Cost & Ops Reality

  • Storage – Calibration parameters are tiny (a few dozen floats). We store them in our model registry metadata catalog or directly alongside serialized model artifacts in MLflow / S3.
  • Compute Overhead – Evaluating calibration curves at inference time requires negligible CPU compute compared to raw model inference.

Frequently Asked Questions

What is the difference between Platt scaling and Isotonic regression?

Platt scaling fits a logistic regression model to raw scores assuming a smooth sigmoid distortion, making it effective even on smaller validation sets. Isotonic regression fits a non-parametric piecewise constant function that corrects arbitrary monotonic distortions but requires larger calibration datasets to avoid overfitting.

Does probability calibration change model accuracy or ROC-AUC?

No. Because probability calibration applies a strictly monotonic transformation to predictions, the relative ranking of instances is preserved. ROC-AUC and ranking accuracy remain unchanged, while Brier score and log-loss improve substantially.

When should you avoid calibrating probabilities?

Avoid calibration when dealing with pure ranking tasks (such as search ranking or product recommendation where raw ordering matters rather than probabilistic confidence) or when your held-out calibration set contains fewer than several hundred samples.


Source context: Original announcement / coverage