Model Calibration in Python: The Metric Decides the Method

Measure how five model families miscalibrate, then fix it three ways. On 200 calibration rows ECE and log loss pick different methods, and only one of them is right.

Cover Image for Model Calibration in Python: The Metric Decides the Method

Suppose a fraud classifier assigns a transaction a probability of 0.9, and your rule sends anything above 0.8 for review. That decision treats the score as a probability, so transactions given similar scores should turn out to be fraudulent about nine times in ten. A model can rank suspicious transactions well while being much too confident about them. Accuracy and AUC do not measure that agreement. Model calibration checks it directly when a threshold or cost calculation uses the probabilities themselves.

We fit repairs and check whether the probabilities can support decisions. Dividing the MLP's logits by 3.43 corrects its overconfidence; the forest is too timid. With 200 calibration rows, ECE prefers isotonic regression despite Platt's 41% lower log loss. Isotonic puts a fifth of predictions at a boundary. Reliability diagrams expose the disagreement.

Let's Build It

Forest cover type, reduced to the largest class against the rest, is the same binary problem Niculescu-Mizil and Caruana used in 2005, so the directions measured here are comparable to theirs. Three disjoint splits: the model trains on the first, the calibrator fits on the second, and every number reported comes off the third.

N_TRAIN, N_CAL, N_TEST = 5000, 2000, 20000

def load(seed=0):
    d = fetch_covtype()
    X, y = d.data, (d.target == 2).astype(int)
    idx = np.random.default_rng(seed).permutation(len(y))[: N_TRAIN + N_CAL + N_TEST]
    tr, ca, te = idx[:N_TRAIN], idx[N_TRAIN : N_TRAIN + N_CAL], idx[N_TRAIN + N_CAL :]
    scaler = StandardScaler().fit(X[tr])
    return tuple((scaler.transform(X[i]), y[i]) for i in (tr, ca, te))

(Xtr, ytr), (Xca, yca), (Xte, yte) = load()

Calibration is measured by one table: sort the predictions into bins, and in each bin compare the average prediction with the fraction that turned out positive.

def reliability(p, y, bins=15):
    """Per-bin (mean predicted probability, observed fraction, count)."""
    edges = np.linspace(0, 1, bins + 1)
    edges[0], edges[-1] = -np.inf, np.inf
    rows = [(p[m].mean(), y[m].mean(), m.sum())
            for lo, hi in zip(edges[:-1], edges[1:])
            if (m := (p > lo) & (p <= hi)).sum()]
    return np.array(rows)

def ece(p, y, bins=15):
    """Expected calibration error: the diagram's gaps, weighted by bin size."""
    r = reliability(p, y, bins)
    return float((r[:, 2] / r[:, 2].sum() * np.abs(r[:, 1] - r[:, 0])).sum())

Fit five families and look at all five diagrams at once.

FAMILIES = {
    "logistic regression": LogisticRegression(max_iter=1000),
    "random forest": RandomForestClassifier(n_estimators=200, random_state=0, n_jobs=-1),
    "gradient boosting": GradientBoostingClassifier(random_state=0),
    "small MLP": MLPClassifier((64, 32), max_iter=400, random_state=0),
    "SVM (RBF)": SVC(random_state=0),
}

for name, model in FAMILIES.items():
    model.fit(Xtr, ytr)
    pc, pt = scores(model, name, [Xca, Xte])
    print(f"{name:<22} accuracy {((pt >= 0.5) == yte).mean():.4f}   "
          f"AUC {roc_auc_score(yte, pt):.4f}   ECE {ece(pt, yte):.4f}")

# logistic regression    accuracy 0.7549   AUC 0.8271   ECE 0.0283
# random forest          accuracy 0.8187   AUC 0.8960   ECE 0.0505
# gradient boosting      accuracy 0.7823   AUC 0.8626   ECE 0.0282
# small MLP              accuracy 0.7968   AUC 0.8713   ECE 0.1183
# SVM (RBF)              accuracy 0.7713   AUC 0.8470   ECE 0.1200

Reliability diagrams for five model families on 20,000 held-out rows, with the prediction histogram under each

Read the accuracy column against the ECE column. The random forest is the most accurate model here and the third worst calibrated; logistic regression is the least accurate and among the best calibrated. Ranking models by accuracy and ranking them by calibration produce different orders, which is the first thing worth knowing: these are two axes, not one.

Those figures come from one split. Every table below reports the mean over three, because a single seed is not enough to carry a claim.

What Just Happened?

The reliability diagram

The dashed diagonal is what calibration means. A point at (0.7,0.7)(0.7, 0.7) says that among the rows the model scored near 0.7, about 70% were positive. Above the diagonal the model understated; below, it overstated. ECE collapses that picture into one number by averaging the vertical gaps, weighted by how many rows fall in each bin:

ECE=∑m=1M∣Bm∣n ∣ yˉm−pˉm ∣\mathrm{ECE} = \sum_{m=1}^{M} \frac{|B_m|}{n} \, \bigl| \, \bar{y}_m - \bar{p}_m \, \bigr|

Note what the absolute value throws away. A model that is too confident and a model that is too timid can post the same ECE, and the repair for one is the opposite of the repair for the other.

The direction, in one number

To recover the direction, refit the labels against the model's own log-odds and read the coefficient:

y∼σ(a⋅logit(p)+b)y \sim \sigma\bigl(a \cdot \mathrm{logit}(p) + b\bigr)
def calibration_slope(p, y):
    return float(LogisticRegression(max_iter=1000)
                 .fit(logit(p).reshape(-1, 1), y).coef_[0, 0])

A perfectly calibrated model gives a=1a = 1. Below 1, the scores are spread too wide and need pulling in, which is overconfidence. Above 1, they are bunched too close to the base rate and need pushing out. The slope is stable across seeds to within 0.08 on every family here, so it is a measurement rather than an impression.

Five families, five shapes

familyaccuracyAUCECEslopereading
logistic regression0.75210.82520.02570.93close to honest
random forest0.81840.89540.05331.37too timid
gradient boosting0.78190.86100.02701.17too timid
small MLP0.79750.87210.11730.29far too confident
SVM (RBF)0.77160.84510.11441.92far too timid

Three-seed means on 20,000 held-out rows.

Logistic regression is well behaved because it optimises log loss on a linear logit, so honest probabilities are what its objective asks for. The random forest is timid for a structural reason: its output is the fraction of trees voting positive, and getting all 200 trees to agree is rare, so the extremes are never reached.

Gradient boosting lands on the same side, at 1.17, and that is worth pausing on because the folklore says the opposite. Boosted trees are widely described as overconfident. Niculescu-Mizil and Caruana measured them as pushed away from 0 and 1, giving the characteristic sigmoid reliability curve, and that is what turns up here too. If you carry one piece of received wisdom into a calibration audit, carry the habit of measuring instead.

The MLP at 0.29 is the textbook modern-network failure Guo et al. described in 2017: trained to near-zero training loss, it learns to be certain. The histogram under its panel shows the damage, with almost every prediction piled against 0 or 1.

The SVM is a different problem. An SVM has no probability to return, only a signed distance to the decision boundary, so something has to invent one. Squashing that distance onto [0,1][0, 1] is the laziest available choice and it earns a slope of 1.92: the resulting numbers are not probabilities and never were.

def scores(model, name, Xs):
    if name == "SVM (RBF)":
        d = [model.decision_function(X) for X in Xs]
        lo, hi = d[0].min(), d[0].max()
        return [np.clip((di - lo) / (hi - lo), 0, 1) for di in d]
    return [model.predict_proba(X)[:, 1] for X in Xs]

Three Repairs

Platt, temperature and isotonic

Each of these fits a one-dimensional function from the model's score to a probability, on held-out data, and each is short enough to read in one go.

def platt(pc, yc, pt):
    """One logistic regression on the score. Strictly monotone, two parameters."""
    return (LogisticRegression().fit(pc.reshape(-1, 1), yc)
            .predict_proba(pt.reshape(-1, 1))[:, 1])

def isotonic(pc, yc, pt):
    """The best non-decreasing step function. Weakly monotone, unbounded flexibility."""
    return IsotonicRegression(out_of_bounds="clip").fit(pc, yc).predict(pt)

def temperature(pc, yc, pt, grid=np.linspace(0.05, 10, 800)):
    """Divide the logit by one number, picked by log loss on held-out data."""
    zc, zt = logit(pc), logit(pt)
    def nll(T):
        q = np.clip(1 / (1 + np.exp(-zc / T)), 1e-15, 1 - 1e-15)
        return -np.mean(yc * np.log(q) + (1 - yc) * np.log(1 - q))
    T = float(grid[np.argmin([nll(t) for t in grid])])
    return 1 / (1 + np.exp(-zt / T)), T

Applied to the worst offender, all three pull the curve back towards the diagonal, and they differ in how much freedom they had to do it.

The small MLP before recalibration and after Platt, temperature and isotonic

Temperature scaling is the one to watch, because it has a single parameter. Sweeping it turns the reliability curve through the diagonal and out the other side, while accuracy sits still:

Animation of the reliability curve rotating as temperature sweeps from 0.4 to 8, with a flat accuracy line alongside

The fitted value is T=3.43T = 3.43, and the raw model's calibration slope is 0.290, whose reciprocal is 3.45. Those are the same fact twice, agreeing to within 1%: T=1/aT = 1/a. Temperature scaling and the slope instrument are the same one-parameter model, one used to describe the damage and the other to undo it.

The ranking never moves

# family                   AUC raw     Platt  temperature   isotonic
# logistic regression      0.82521   0.82521      0.82521    0.82413
# random forest            0.89542   0.89542      0.89542    0.89322
# gradient boosting        0.86096   0.86096      0.86096    0.85965
# small MLP                0.87214   0.87214      0.87199    0.86974
# SVM (RBF)                0.84514   0.84514      0.84514    0.84331

Platt scaling reproduces the raw AUC to every digit printed, on every family. It is a strictly increasing function of the score, so it cannot reorder two rows, and AUC depends on nothing but that order. Temperature does the same in four cases out of five; the MLP loses 0.00015 only because so many of its outputs sit at exactly 0 or 1 that clipping them before taking the logit ties them together.

Isotonic regression is the exception, and it loses AUC every time. A non-decreasing step function is only weakly monotone: rows that used to be ordered get flattened onto the same step, and every tie it creates costs a little discrimination. The loss is small here, around 0.002, but it is systematic rather than noise.

The practical reading: if a recalibration method changes your AUC by much, it is not recalibrating, it is refitting.

The Metric That Picks the Method

Two metrics, two answers

Isotonic regression won on ECE in the table above, for every family. The standard advice is that it needs a lot of calibration data and overfits without it, so the obvious experiment is to shrink the calibration set and watch it fail.

It does not fail, as far as ECE can tell.

Three panels: ECE, log loss, and the share of saturated predictions, against calibration set size

calibration rowsECE isotonicECE PlattECE pickslog loss isotoniclog loss Plattlog loss picks
500.10770.0832Platt2.07950.4830Platt
1000.08370.0834Platt1.10020.4821Platt
2000.05330.0629isotonic0.80690.4733Platt
5000.02870.0542isotonic0.53260.4695Platt
10000.02260.0460isotonic0.52290.4668Platt
20000.01980.0509isotonic0.46700.4663Platt, by 0.0007

Three-seed means, small MLP.

From 200 rows upward the two metrics name different winners. At 200 rows ECE puts isotonic 15% ahead while log loss puts it 70% behind. At 500 rows ECE has isotonic almost twice as good and log loss still has Platt in front. They are computed on the same predictions, on the same 20,000 rows, at the same moment.

Underneath those means the individual runs are starker. Log loss picks Platt scaling in 17 of the 18 seed-by-size runs, the one exception being a single seed at 2,000 rows where the two are level. ECE picks Platt in some runs and isotonic in others below 500 rows, flipping with the seed, and then picks isotonic unanimously at 500 rows and above. One of these metrics is making a stable judgement and the other is not.

The failure ECE cannot see

The third panel of that figure is the answer. Isotonic regression fitted on 200 rows sends 21.3% of its test predictions to exactly 0 or exactly 1. On 50 rows it is 46.8%.

That is what a step function does when it runs out of data: the first step starts at 0 and the last one ends at 1, and with few rows those two steps swallow much of the range. The model is now claiming certainty about a fifth of the rows it sees, and it is wrong about some of them.

ECE cannot register this. Its per-bin term is ∣yˉm−pˉm∣|\bar{y}_m - \bar{p}_m|, which is bounded by 1 no matter how badly wrong an individual prediction is, and a confident error contributes at most the same as a diffident one. Log loss is unbounded on exactly this failure, which is why it moves by a factor of four while ECE moves by nothing. The gap between the two metrics is a direct measurement of how much confident wrongness the model is producing.

This matters beyond the metric. A probability of exactly 0 is not a small probability, it is an assertion, and anything downstream that takes a logarithm, a log-odds or a reciprocal will fail on it rather than degrade.

The practical rule is short. Choose the recalibration method on a proper scoring rule, log loss or Brier, and use ECE afterwards to describe what you got. ECE is a good description and a bad objective.

ECE's own free parameter

ECE also has a knob, and nothing tells you where to set it. The usual complaint is that the bin count changes the answer. Measured, that complaint is right in a more awkward way than it is usually stated.

ECE against the number of bins, for a badly calibrated model and a well calibrated one

On the badly calibrated MLP, sweeping from 5 bins to 500 moves the reported ECE by a factor of 1.08. The error is big enough that any binning finds it. On a Platt-calibrated logistic regression, the same sweep moves it by a factor of 3.31, from 0.016 to 0.054. Switching to equal-mass bins changes nothing worth having: 3.47 instead of 3.31.

The sensitivity appears exactly where you would rely on the number. Nobody needs a calibration metric to tell them that a slope-0.29 model is broken; you need one to decide whether the recalibrated model is good enough to ship, and that is the regime where the bin count is doing a third of the talking. The reason is straightforward: once the true gaps are near zero, each bin's estimated gap is mostly sampling noise, and ECE takes the absolute value of it before averaging, so noise cannot cancel and more bins mean a bigger number.

Report the bin count alongside any ECE you quote, and never compare two ECE figures computed with different ones.

Going Deeper

The Brier score and its three terms

The Brier score is the mean squared error of a probability, and it is a proper scoring rule, so it cannot be gamed by hedging. Murphy's 1973 decomposition splits it into three pieces:

BS=∑m∣Bm∣n(pˉm−yˉm)2⏟reliability  −  ∑m∣Bm∣n(yˉm−yˉ)2⏟resolution  +  yˉ(1−yˉ)⏟uncertainty\mathrm{BS} = \underbrace{\textstyle\sum_m \tfrac{|B_m|}{n}(\bar{p}_m - \bar{y}_m)^2}_{\text{reliability}} \; - \; \underbrace{\textstyle\sum_m \tfrac{|B_m|}{n}(\bar{y}_m - \bar{y})^2}_{\text{resolution}} \; + \; \underbrace{\bar{y}(1 - \bar{y})}_{\text{uncertainty}}

Reliability and resolution for each family, before and after isotonic recalibration

Uncertainty is 0.2499 for every model, because it is a property of the labels. Resolution is what the model knows, and recalibration leaves it alone: the random forest holds 0.120 before and after, the SVM 0.091 before and after. Reliability is the miscalibration, and it is the only term that moves, collapsing from 0.0153 to 0.0007 on the MLP and from 0.0157 to 0.0005 on the SVM.

That is the separation of axes stated arithmetically. It also explains why the Brier score is a poor calibration detector despite being a proper score: reliability is under a tenth of it, so fixing the calibration entirely improves the MLP's Brier by about 9%, which is easy to mistake for noise.

Temperature as Platt without the intercept

Look back at the recalibration table and one entry is out of line. On logistic regression, temperature scaling makes calibration worse: ECE 0.0257 raw against 0.0335 after.

Temperature scaling divides the logit by TT and adds nothing. Platt scaling fits both a slope and an intercept. So temperature can correct scores that are spread too wide or too narrow, and it cannot correct scores that are shifted. Logistic regression's slope is already 0.93, near enough to 1 that there is no spread to fix, and the one parameter available gets spent making things worse.

The rule that falls out: temperature scaling for a network whose failure is confidence, Platt when there is also an offset, and check the slope first to know which you have.

The held-out rule

Everything above depends on the calibrator being fitted on rows the model has never trained on. It is easy to state and easy to skip, and skipping it does not produce a warning. It produces a perfect reliability diagram.

A random forest calibrated in-sample: perfect on its own rows, three times worse than doing nothing on held-out rows

Fit isotonic regression on the random forest's own training rows and score it on those same rows, and the diagram lies exactly on the diagonal, ECE 0.0000. The forest has near-perfect predictions on data it memorised, so the calibrator learns a step function that maps them straight onto the labels.

Take that same calibrator to held-out data and test ECE is 0.1506, against 0.0505 for doing nothing at all, with log loss at 4.4708 against 0.4168. Calibrating on training data is ten times worse on log loss than leaving the model alone, and it looks perfect while you do it.

Fitted on the held-out split instead, the same method reaches test ECE 0.0175. Same forest, same calibrator, different rows. Those figures are the single split drawn above; the three-seed means are 0.1502 in-sample, 0.0157 held-out and 0.0533 for doing nothing.

Resampling for imbalance

Calibration and class imbalance collide in a specific way. Make the positive class 5% of the data and fix it by oversampling to 50/50, which is one of the standard moves from SMOTE and class weights, and watch what happens to a logistic regression:

model and treatmentmean predictionECEAUC
logistic regression, natural 5%0.05090.01180.7918
logistic regression, oversampled to 50/500.32550.27580.7879
random forest, natural 5%0.05100.00600.8161
random forest, oversampled to 50/500.06720.01750.8215

Three-seed means; the true positive rate is 0.0500 in every row.

The logistic regression now predicts 0.33 on average for an event that happens 5% of the time, and its ECE is 23 times worse. Its AUC is unchanged, so the resampling bought no discrimination at all and cost every probability in the model.

The damage is exactly predictable, which is the useful part. Resampling to 50/50 shifts the log-odds by log⁡ ⁣((0.5/0.5)/(π/(1−π)))\log\!\bigl((0.5/0.5) \big/ (\pi/(1-\pi))\bigr) for a training base rate π\pi, which at π=0.05\pi = 0.05 is log⁡19=2.94\log 19 = 2.94. The measured intercept moves from -3.35 to -0.73, a shift of 2.62, close to the prediction and not equal to it because the other coefficients refit too. Subtract 2.94 from the logit and the mean prediction returns to 0.0524 with ECE 0.0149.

The random forest barely moves, at 0.0672 against a base rate of 0.05, because it reports a vote fraction rather than a log-odds. Applying the same correction to the forest makes it worse, ECE 0.0452 against 0.0175. A correction derived for one model's output is not a general fix, and this is one of the few places where knowing what the number is changes what you are allowed to do to it.

Where This Comes From

Platt (1999) introduced the sigmoid fit in "Probabilistic Outputs for Support Vector Machines", for the exact problem the SVM shows above: a margin classifier with a distance and no probability. His method fits P(y=1∣f)=1/(1+exp⁡(Af+B))P(y=1 \mid f) = 1/(1 + \exp(Af + B)) on a held-out set, and he is explicit that fitting it on the training set gives a biased result.

Zadrozny and Elkan (2002) proposed isotonic regression as the non-parametric alternative in "Transforming Classifier Scores into Accurate Multiclass Probability Estimates", solved by the pool adjacent violators algorithm.

Niculescu-Mizil and Caruana (2005) ran the comparison that most of this post reproduces, in "Predicting Good Probabilities with Supervised Learning". Their central observation is that the most common distortion is a sigmoid-shaped reliability plot, produced when a method pushes its predicted probabilities away from 0 and 1. They report boosting and bagging both doing exactly that, naive Bayes distorting in the opposite direction, and isotonic regression needing roughly 1,000 examples before it overtakes Platt scaling. The runs here do not reach that crossover at all: at 2,000 calibration rows the two are level on log loss, 0.4670 against 0.4663, with the sigmoid still marginally ahead. The qualitative finding, that isotonic needs far more data than Platt scaling, holds and then some.

Guo, Pleiss, Sun and Weinberger (2017) revisited the question for deep networks in "On Calibration of Modern Neural Networks". Their finding is that modern architectures are worse calibrated than the shallow networks of a decade earlier despite being more accurate, and that temperature scaling, one parameter, fixes most of it. Their ECE is defined on max⁡(p,1−p)\max(p, 1-p) against accuracy rather than on the positive-class probability used here, which generalises to multi-class. That produces different numbers from the ones here, with the same reading.

Murphy (1973) gave the decomposition in "A New Vector Partition of the Probability Score", out of weather forecasting, which is where most of the vocabulary here was invented.

Naeini, Cooper and Hauskrecht (2015) introduced the binned ECE estimator now in general use, in "Obtaining Well Calibrated Probabilities Using Bayesian Binning", along with a Bayesian averaging over binning schemes intended to address the bin-count sensitivity measured above.

Interactive Tools

  • Classification Metrics Calculator: work through precision, recall and F1, every one of which depends on the ordering of scores rather than their values, which is why none of them detects miscalibration.
  • Overfitting Explorer: the same held-out discipline that makes a calibration set valid, shown on the model itself.
  • Distribution Explorer: the shapes behind the reliability diagram, including the beta distributions that describe a bin's observed frequency.

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions