Skip to content

Calibration: are the risks right?

A model can rank people perfectly and still give the wrong probabilities. Check the mean, the slope and the curve, in that order, on data the model didn't see.

Applied ~13 min10 steps

What runs in CodeSplash

You will be able to

  • Tell calibration from discrimination using the same model's two versions
  • Read O/E, the calibration intercept and slope, and the ICI
  • Explain why good calibration on the fitting data means little

Read first

01

Right order, wrong numbers

Read

CalibrationCalibrationWhether predicted probabilities match observed frequencies — of cases given 30%, about 30% should be positive. asks: when a model says 30%, does the event happen about 30% of the time?

Take two columns from one logistic model of diabetes. lp_full is the model itself. p_overfit is an exaggerated copy, with every log-odds stretched and shifted. The order of the women doesn't change, so neither does the AUC: 0.855 and 0.855.

An AUC can't tell these two apart. Anyone acting on the probabilities needs to.

02

Bend the probabilities

Explore

Answer the prompt. Then raise Overconfidence and watch the curve tilt away from the diagonal while AUC stays put. Finish by bringing Calibration slope back near 1.

HExplorable · Calibration and reliability

When a model says 80%, does the event happen 80% of the time?

If you make the model more overconfident, what happens to its AUC?

How sure?
2.00

Above 1 the model is too extreme; below 1 it hedges. At 1 it is perfectly calibrated.

2000
10
BrierECECalibration slopeAUC
0.1750.0870.500.835

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

03

Predict the slope

Predict

Predict first

Regress the outcome on the exaggerated copy's log-odds with a logistic model. Its risks are too extreme. What will the coefficient, the calibration slopeCalibration slopeThe coefficient from regressing the outcome on a model's log-odds. Below 1 means the predicted risks are too extreme., be?

Above 1Exactly 1Below 1
Reveal

Below 1: 0.62. The log-odds need shrinking to match what happened.

The original gets 1.00, with intercept 0.00. Don't be impressed: a logistic model scored on its own fitting data gets those values by construction.

04

Levels of calibration

Read

Van Calster and colleagues (2016) describe calibration as a ladder:

LevelQuestionOn the cardIdeal
MeanIs the overall rate right?O/E, calibration interceptCalibration in the largeWhether predicted risks are right on average. It's measured by the observed/expected ratio or the calibration intercept.1, 0
WeakToo extreme or too timid?Calibration slope1
ModerateRight across the range?Curve, ICIIntegrated calibration indexThe average absolute gap between predicted risk and a smoothed observed rate. 0 is ideal., E50, E90, EmaxCurve on the diagonal, 0

The Brier scoreBrier scoreThe mean squared error of predicted probabilities; lower is better and it rewards calibration. sits to one side: it mixes calibration with discrimination, so it can't separate them.

05

Read the card

In the app

Here's the exaggerated copy. Look at the Calibration measures table and its Ideal column, then the risk groups and the warning.

Calibration of predicted risksRecorded · Python and R agreeRecorded 2026-11-25 · 31 values compared
R

Observed rate 33.3% vs mean predicted 34.1% (O/E 0.97); calibration intercept -0.08, slope 0.62; Brier 0.150; ICI 0.070.

Observed / expected
0.9747
Calibration intercept
−0.0840
Calibration slope
0.6250
ICI
0.0702
Brier score
0.1504
Spiegelhalter z
5.872
p
< .001

Plots

Observed vs predicted by risk groupDo predicted probabilities match observed frequencies?
View data
highlownObserved proportionMean predicted risk
0.11700.05712310.08230.0432
0.31610.1548710.22540.1790
0.62060.3529350.48570.3092
0.49820.2435360.36110.4477
0.69930.3467190.52630.5738
0.66180.3698290.51720.6853
0.79640.5300310.67740.8201
0.88390.7448800.82500.9473
Loess calibration curve (span 0.5)Do predicted probabilities match observed frequencies?
View data
Smoothed observed ratePredicted risk
−0.00030.0010
0.00070.0017
0.00210.0027
0.00350.0037
0.00590.0054
0.00620.0056
0.00640.0058
0.00690.0061
0.00750.0065
0.00780.0067
0.00790.0068
0.00830.0071
0.00930.0078
0.01060.0086
0.01140.0091
0.01180.0094
0.01330.0104
0.01410.0109
0.01500.0115
0.01590.0121
0.01820.0136
0.01900.0140
0.01960.0145
0.02030.0149
0.02090.0153
0.02350.0169
0.02410.0172
0.02540.0180
0.02750.0192
0.02790.0195
0.02910.0202
0.03140.0216
0.03250.0222
0.03500.0236
0.03560.0240
0.03630.0244
0.03800.0253
0.03960.0262
0.03990.0264
0.04290.0281
0.04410.0287
0.04510.0292
0.04900.0314
0.04990.0318
0.05040.0321
0.05320.0335
0.05550.0347
0.06050.0373
0.06570.0399
0.06990.0419
0.07250.0432
0.07720.0454
0.07940.0464
0.08270.0479
0.08560.0493
0.09300.0526
0.09480.0534
0.10010.0558
0.10100.0561
0.10300.0570

First 60 of 200 rows.

Predicted risksHow is one numeric variable distributed?
View data
Predicted risk
0.0137
0.9519
0.0264
0.9074
0.0153
0.3127
0.0202
0.8295
0.8503
0.8797
0.9914
0.6765
0.9835
0.1655
0.2089
0.0067
0.0626
0.8211
0.5981
0.0479
0.0076
0.1505
0.0202
0.0060
0.0399
0.8334
0.0172
0.6035
0.1398
0.1446
0.0856
0.2756
0.1880
0.4113
0.1544
0.5497
0.0067
0.0013
0.0676
0.1519
0.9804
0.0600
0.1952
0.0037
0.0236
0.1550
0.1635
0.1492
0.6061
0.9958
0.0250
0.0169
0.8167
0.1091
0.0368
0.3316
0.0701
0.0240
0.4405
0.8973

First 60 of 532 rows.

Assumptions

  • Enough events and non-events — 177 events and 355 non-events.
  • Predictions are probabilities — All predictions lie strictly between 0 and 1.

Calibration measures

MeasureEstimate90% CI low90% CI highIdeal
Observed / expected (O/E)0.97470.88101.0781
Calibration intercept−0.0840−0.30700.13900
Calibration slope0.62500.53220.71781
ICI (mean |smoothed − predicted|)0.0702——0
E50 / E90 / Emax0.13830.07530.14880
Brier score0.1504——0
Scaled Brier (1 − Brier / Brier of the prevalence)0.3226——1
AUC (discrimination)0.8552——1

The E50 / E90 / Emax row shows E90 with E50 and Emax in the interval columns.

Risk groups

GroupnLowest riskHighest riskMean predictedEventsObserved rate90% CI low90% CI high
12310.00100.12410.0432190.08230.05710.1170
2710.12870.24830.1790160.22540.15480.3161
3350.25020.37440.3092170.48570.35290.6206
4360.37970.49880.4477130.36110.24350.4982
5190.50160.61600.5738100.52630.34670.6993
6290.62800.74820.6853150.51720.36980.6618
7310.75380.87170.8201210.67740.53000.7964
8800.87970.99990.9473660.82500.74480.8839

Wilson intervals for the observed rate.

  • The calibration slope is well below 1: the predictions are too extreme (typical of an overfitted model).
  • Event: type = Yes. Calibration intercept from a logistic model of the outcome with the log-odds as an offset; slope from regressing the outcome on the log-odds (Wald intervals).
  • Hosmer–Lemeshow χ²(6) = 49.55, p < .001 over 8 groups; with large samples it flags trivial miscalibration.
The exact R script · R R version 4.5.1 (2025-06-13)
# Calibration of predicted risks
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method diagnostic.calibration 1.1.2 · spec 197ca4b7447c0b1d
# Dataset: s5_risk (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_cal_* (loess errors, risk groups, Spiegelhalter), cs_hosmer_lemeshow, cs_auc

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s5_risk.parquet", col_select = c("type", "p_overfit")))
n_input <- nrow(df)
df[["type"]] <- factor(df[["type"]], levels = c("No", "Yes"))  # stored level order
df <- df[stats::complete.cases(df[c("type", "p_overfit")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("type", "p_overfit"))  # infinite values stop the run (registry/errors.yaml)

# %% Predictions
yc <- "type"
pc <- "p_overfit"
y_levels <- c("No", "Yes")  # stored level order
event <- y_levels[length(y_levels)]  # default: the last level ("true")
y <- as.numeric(as.character(df[[yc]]) == event)
raw <- as.numeric(df[[pc]])
scale <- "probability"
p <- if (scale == "percent") raw / 100 else if (scale == "logit") 1 / (1 + exp(-raw)) else raw
n_outside <- sum(p < 0 | p > 1)
if (n_outside > 0) {
  cs_error("CS_E_INVALID_VALUES", column = pc, requirement = "a risk between 0 and 1 on the chosen scale (percent or log-odds otherwise)",
           count = n_outside)
}
n <- length(y)
n_events <- sum(y)
if (n_events == 0 || n_events == n) cs_error("CS_E_TOO_FEW_GROUPS", column = yc, min = 2, k = 1)  # needs events and non-events
cs_check_not_constant(raw, pc)  # one predicted risk for everyone: the calibration slope is undefined
eps <- 1e-10  # exact 0 or 1 have infinite log-odds: moved just inside
n_clipped <- sum(p < eps | p > 1 - eps)
p <- pmin(pmax(p, eps), 1 - eps)
lp <- if (scale == "logit") raw else log(p / (1 - p))
conf <- 0.9
zc <- stats::qnorm(1 - (1 - conf) / 2)
bins <- as.integer(8)
binning <- "equal"
span <- 0.5

# %% Calibration
obs_rate <- mean(y)
mean_p <- mean(p)
o <- sum(y)
e <- sum(p)
oe <- o / e
se_ln_oe <- sqrt((1 - o / n) / o)  # binomial approximation (Debray et al. 2017)
oe_low <- oe * exp(-zc * se_ln_oe)
oe_high <- oe * exp(zc * se_ln_oe)
# Logistic recalibration (converged tightly so both engines agree): intercept with the log-odds as
# an offset (calibration-in-the-large), slope from regressing the outcome on the log-odds.
ctl <- stats::glm.control(epsilon = 1e-14, maxit = 100)
fit_a <- stats::glm(y ~ 1, offset = lp, family = stats::binomial, control = ctl)
cal_a <- unname(stats::coef(fit_a)[1])
cal_a_se <- sqrt(stats::vcov(fit_a)[1, 1])
# When the log-odds separate events from non-events completely, the slope's estimate is infinite: left empty.
separated <- max(lp[y == 0]) <= min(lp[y == 1]) || max(lp[y == 1]) <= min(lp[y == 0])
if (separated) {
  cal_b <- NA_real_
  cal_b_se <- NA_real_
  warnings <- c(warnings, "The predictions separate events from non-events completely, so the calibration slope can't be estimated.")
} else {
  fit_b <- stats::glm(y ~ lp, family = stats::binomial, control = ctl)
  cal_b <- unname(stats::coef(fit_b)[2])
  cal_b_se <- sqrt(stats::vcov(fit_b)[2, 2])
}
brier <- mean((p - y)^2)
brier_scaled <- 1 - brier / (obs_rate * (1 - obs_rate))
sp <- cs_cal_spiegelhalter(y, p)
hl <- cs_hosmer_lemeshow(y, p, g = bins, external = FALSE)  # df = G (external) or G - 2
auc <- cs_auc(y, p)
groups <- cs_cal_bins(y, p, bins = bins, binning = binning, conf = conf)
smoothed <- cs_cal_can_smooth(p, span = span)
sm_err <- if (smoothed) cs_cal_smoothed_errors(y, p, span = span) else NULL

# %% Assumptions
few <- min(n_events, n - n_events) < 100
assumptions <- list(
  list(key = "sample_size", label = "Enough events and non-events", status = if (few) "warn" else "pass",
       detail = sprintf("%d events and %d non-events%s", n_events, n - n_events,
                        if (few) "; with fewer than 100 of either, the calibration curve and slope are imprecise." else ".")),
  list(key = "range", label = "Predictions are probabilities", status = if (n_clipped > 0) "warn" else "pass",
       detail = if (n_clipped > 0) sprintf("%d prediction(s) were exactly 0 or 1 and were moved 1e-10 inside.", n_clipped) else "All predictions lie strictly between 0 and 1.")
)
if (!smoothed) warnings <- c(warnings, "Too few distinct predicted risks for a loess calibration curve: the ICI is not computed; read the risk groups instead.")
if (isTRUE(cal_b < 0.8)) warnings <- c(warnings, "The calibration slope is well below 1: the predictions are too extreme (typical of an overfitted model).")

# %% Result
pct <- sprintf("%.0f%%", conf * 100)
na_if_null <- function(x) if (is.null(x)) NA else x
values <- list(
  n = n, n_events = n_events, positive_level = event, observed_rate = obs_rate, mean_predicted = mean_p,
  oe_ratio = oe, oe_low = oe_low, oe_high = oe_high,
  cal_intercept = cal_a, cal_intercept_se = cal_a_se, cal_intercept_low = cal_a - zc * cal_a_se, cal_intercept_high = cal_a + zc * cal_a_se,
  cal_slope = cal_b, cal_slope_se = cal_b_se, cal_slope_low = cal_b - zc * cal_b_se, cal_slope_high = cal_b + zc * cal_b_se,
  brier = brier, brier_scaled = brier_scaled,
  ici = if (smoothed) sm_err$ici else NA, e50 = if (smoothed) sm_err$e50 else NA,
  e90 = if (smoothed) sm_err$e90 else NA, emax = if (smoothed) sm_err$emax else NA, smoothed = smoothed,
  hl_chi2 = hl$chi2, hl_df = hl$df, hl_p = na_if_null(hl$p),
  spiegelhalter_z = sp$z, spiegelhalter_p = sp$p, auc = auc, n_clipped = n_clipped, n_groups = length(groups)
)
gv <- function(k) vapply(groups, function(g) g[[k]], numeric(1))
ord <- order(p, method = "radix")
keep <- ord[unique(round(seq(1, n, length.out = min(n, 200))))]
charts <- list(
  cs_chart("calibration", "calibration", "Observed vs predicted by risk group",
           list(predicted = cs_col("Mean predicted risk", gv("mean_p")), observed = cs_col("Observed proportion", gv("rate")),
                n = cs_col("n", gv("n")), low = cs_col("low", gv("low")), high = cs_col("high", gv("high"))))
)
if (smoothed) {
  charts[[length(charts) + 1]] <- cs_chart("smooth", "calibration", sprintf("Loess calibration curve (span %g)", span),
                                           list(predicted = cs_col("Predicted risk", p[keep]), observed = cs_col("Smoothed observed rate", sm_err$smooth[keep])))
}
charts[[length(charts) + 1]] <- cs_chart("risks", "histogram", "Predicted risks", list(x = cs_col("Predicted risk", p)))
summary <- sprintf("Observed rate %.1f%% vs mean predicted %.1f%% (O/E %.2f); calibration intercept %.2f, slope %.2f; Brier %.3f%s",
                   100 * obs_rate, 100 * mean_p, oe, cal_a, cal_b, brier, if (smoothed) sprintf("; ICI %.3f.", sm_err$ici) else ".")
cs_publish(list(
  method = "diagnostic.calibration",
  methodVersion = "1.1.2",
  title = "Calibration of predicted risks",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  statistics = list(
    list(key = "oe_ratio", label = "Observed / expected", value = oe),
    list(key = "cal_intercept", label = "Calibration intercept", value = cal_a),
    list(key = "cal_slope", label = "Calibration slope", value = values$cal_slope),
    list(key = "ici", label = "ICI", value = values$ici),
    list(key = "brier", label = "Brier score", value = brier),
    list(key = "spiegelhalter_z", label = "Spiegelhalter z", value = sp$z),
    list(key = "spiegelhalter_p", label = "p", value = sp$p, format = "p")
  ),
  tables = list(
    list(key = "measures", title = "Calibration measures",
         columns = list(list(key = "measure", label = "Measure", type = "string"), list(key = "value", label = "Estimate", type = "number"),
                        list(key = "low", label = sprintf("%s CI low", pct), type = "number"), list(key = "high", label = sprintf("%s CI high", pct), type = "number"),
                        list(key = "ideal", label = "Ideal", type = "string")),
         rows = list(
           list(measure = "Observed / expected (O/E)", value = oe, low = oe_low, high = oe_high, ideal = "1"),
           list(measure = "Calibration intercept", value = cal_a, low = values$cal_intercept_low, high = values$cal_intercept_high, ideal = "0"),
           list(measure = "Calibration slope", value = values$cal_slope, low = values$cal_slope_low, high = values$cal_slope_high, ideal = "1"),
           list(measure = "ICI (mean |smoothed − predicted|)", value = values$ici, low = NA, high = NA, ideal = "0"),
           list(measure = "E50 / E90 / Emax", value = values$e90, low = values$e50, high = values$emax, ideal = "0"),
           list(measure = "Brier score", value = brier, low = NA, high = NA, ideal = "0"),
           list(measure = "Scaled Brier (1 − Brier / Brier of the prevalence)", value = brier_scaled, low = NA, high = NA, ideal = "1"),
           list(measure = "AUC (discrimination)", value = auc, low = NA, high = NA, ideal = "1")),
         note = "The E50 / E90 / Emax row shows E90 with E50 and Emax in the interval columns."),
    list(key = "groups", title = "Risk groups",
         columns = list(list(key = "group", label = "Group", type = "integer"), list(key = "n", label = "n", type = "integer"),
                        list(key = "p_min", label = "Lowest risk", type = "number"), list(key = "p_max", label = "Highest risk", type = "number"),
                        list(key = "mean_p", label = "Mean predicted", type = "number"), list(key = "observed", label = "Events", type = "number"),
                        list(key = "rate", label = "Observed rate", type = "number"), list(key = "low", label = sprintf("%s CI low", pct), type = "number"),
                        list(key = "high", label = sprintf("%s CI high", pct), type = "number")),
         rows = groups, note = "Wilson intervals for the observed rate.")
  ),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(
    sprintf("Event: %s = %s. Calibration intercept from a logistic model of the outcome with the log-odds as an offset; slope from regressing the outcome on the log-odds (Wald intervals).", yc, event),
    sprintf("Hosmer–Lemeshow χ²(%d) = %.2f%s over %d groups; with large samples it flags trivial miscalibration.", hl$df, hl$chi2,
            if (is.null(hl$p)) "" else paste0(", ", cs_fmt_p(hl$p)), length(hl$groups))
  ),
  charts = charts,
  values = values
))
Python

Observed rate 33.3% vs mean predicted 34.1% (O/E 0.97); calibration intercept -0.08, slope 0.62; Brier 0.150; ICI 0.070.

Observed / expected
0.9747
Calibration intercept
−0.0840
Calibration slope
0.6250
ICI
0.0702
Brier score
0.1504
Spiegelhalter z
5.872
p
< .001

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Enough events and non-events — 177 events and 355 non-events.
  • Predictions are probabilities — All predictions lie strictly between 0 and 1.

Calibration measures

MeasureEstimate90% CI low90% CI highIdeal
Observed / expected (O/E)0.97470.88101.0781
Calibration intercept−0.0840−0.30700.13900
Calibration slope0.62500.53220.71781
ICI (mean |smoothed − predicted|)0.0702——0
E50 / E90 / Emax0.13830.07530.14880
Brier score0.1504——0
Scaled Brier (1 − Brier / Brier of the prevalence)0.3226——1
AUC (discrimination)0.8552——1

The E50 / E90 / Emax row shows E90 with E50 and Emax in the interval columns.

Risk groups

GroupnLowest riskHighest riskMean predictedEventsObserved rate90% CI low90% CI high
12310.00100.12410.0432190.08230.05710.1170
2710.12870.24830.1790160.22540.15480.3161
3350.25020.37440.3092170.48570.35290.6206
4360.37970.49880.4477130.36110.24350.4982
5190.50160.61600.5738100.52630.34670.6993
6290.62800.74820.6853150.51720.36980.6618
7310.75380.87170.8201210.67740.53000.7964
8800.87970.99990.9473660.82500.74480.8839

Wilson intervals for the observed rate.

  • The calibration slope is well below 1: the predictions are too extreme (typical of an overfitted model).
  • Event: type = Yes. Calibration intercept from a logistic model of the outcome with the log-odds as an offset; slope from regressing the outcome on the log-odds (Wald intervals).
  • Hosmer–Lemeshow χ²(6) = 49.55, p < .001 over 8 groups; with large samples it flags trivial miscalibration.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Calibration of predicted risks
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method diagnostic.calibration 1.1.2 · spec 197ca4b7447c0b1d
# Dataset: s5_risk (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import math

import numpy as np
import pandas as pd
import statsmodels.api as sm
from scipy import stats

import codesplash as cs
from codesplash.errors import check_not_constant
from codesplash.stats import calibration as cal  # loess curve, risk groups, Spiegelhalter (twins of codesplashr cs_cal_*)
from codesplash.stats import glm as csglm  # Hosmer–Lemeshow grouping, AUC

# %% Data
df = pd.read_parquet("tests/parity/fixtures/s5_risk.parquet", columns=["type", "p_overfit"])
n_input = len(df)
df["type"] = pd.Categorical(df["type"], categories=["No", "Yes"])  # stored level order
df = df.dropna(subset=["type", "p_overfit"])  # listwise deletion over the analysis columns
df["type"] = df["type"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["type", "p_overfit"])  # infinite values stop the run (registry/errors.yaml)

# %% Predictions
yc, pc = "type", "p_overfit"
y_levels = ["No", "Yes"]  # stored level order
event = y_levels[-1]  # default: the last level ("true")
y = (df[yc].astype(str) == event).to_numpy().astype(float)
raw = df[pc].to_numpy(dtype=float)
scale = "probability"
if scale == "percent":
    p = raw / 100.0
elif scale == "logit":
    p = 1.0 / (1.0 + np.exp(-raw))
else:
    p = raw.copy()
n_outside = int(np.sum((p < 0) | (p > 1)))
if n_outside:
    cs.cs_error("CS_E_INVALID_VALUES", column=pc, requirement="a risk between 0 and 1 on the chosen scale (percent or log-odds otherwise)",
                count=n_outside)
n, n_events = len(y), int(y.sum())
if n_events == 0 or n_events == n:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=yc, min=2, k=1)  # needs events and non-events
check_not_constant(raw, pc)  # one predicted risk for everyone: the calibration slope is undefined
eps = 1e-10  # exact 0 or 1 have infinite log-odds: moved just inside
n_clipped = int(np.sum((p < eps) | (p > 1 - eps)))
p = np.clip(p, eps, 1 - eps)
lp = raw.copy() if scale == "logit" else np.log(p / (1 - p))
conf = 0.9
zc = float(stats.norm.ppf(1 - (1 - conf) / 2))
bins, binning, span = int(8), "equal", 0.5

# %% Calibration
obs_rate, mean_p = float(y.mean()), float(p.mean())
o, e = float(y.sum()), float(p.sum())
oe = o / e
se_ln_oe = math.sqrt((1 - o / n) / o)  # binomial approximation (Debray et al. 2017)
oe_low, oe_high = oe * math.exp(-zc * se_ln_oe), oe * math.exp(zc * se_ln_oe)
# Logistic recalibration (converged tightly so both engines agree): intercept with the log-odds as
# an offset (calibration-in-the-large), slope from regressing the outcome on the log-odds.
fit_a = sm.GLM(y, np.ones((n, 1)), family=sm.families.Binomial(), offset=lp).fit(tol=1e-14, maxiter=100)
cal_a, cal_a_se = float(fit_a.params[0]), float(fit_a.bse[0])
# When the log-odds separate events from non-events completely, the slope's estimate is infinite: left empty.
separated = bool(lp[y == 0].max() <= lp[y == 1].min() or lp[y == 1].max() <= lp[y == 0].min())
if separated:
    cal_b = cal_b_se = math.nan
    warnings.append("The predictions separate events from non-events completely, so the calibration slope can't be estimated.")
else:
    fit_b = sm.GLM(y, np.column_stack([np.ones(n), lp]), family=sm.families.Binomial()).fit(tol=1e-14, maxiter=100)
    cal_b, cal_b_se = float(fit_b.params[1]), float(fit_b.bse[1])
brier = float(np.mean((p - y) ** 2))
brier_scaled = 1 - brier / (obs_rate * (1 - obs_rate))
sp = cal.spiegelhalter(y, p)
hl = csglm.hosmer_lemeshow(y, p, g=bins, external=False)  # df = G (external) or G − 2
auc = csglm.auc(y, p)
groups = cal.calibration_bins(y, p, bins=bins, binning=binning, conf=conf)
smoothed = cal.can_smooth(p, span=span)
sm_err = cal.smoothed_errors(y, p, span=span) if smoothed else None

# %% Assumptions
assumptions = [
    {"key": "sample_size", "label": "Enough events and non-events",
     "status": "pass" if min(n_events, n - n_events) >= 100 else "warn",
     "detail": f"{n_events} events and {n - n_events} non-events" + (
         "." if min(n_events, n - n_events) >= 100 else "; with fewer than 100 of either, the calibration curve and slope are imprecise.")},
    {"key": "range", "label": "Predictions are probabilities", "status": "warn" if n_clipped else "pass",
     "detail": f"{n_clipped} prediction(s) were exactly 0 or 1 and were moved 1e-10 inside." if n_clipped else "All predictions lie strictly between 0 and 1."},
]
if not smoothed:
    warnings.append("Too few distinct predicted risks for a loess calibration curve: the ICI is not computed; read the risk groups instead.")
if not separated and cal_b < 0.8:
    warnings.append("The calibration slope is well below 1: the predictions are too extreme (typical of an overfitted model).")

# %% Result
pct = f"{conf:.0%}"
values = {
    "n": n, "n_events": n_events, "positive_level": event, "observed_rate": obs_rate, "mean_predicted": mean_p,
    "oe_ratio": oe, "oe_low": oe_low, "oe_high": oe_high,
    "cal_intercept": cal_a, "cal_intercept_se": cal_a_se, "cal_intercept_low": cal_a - zc * cal_a_se, "cal_intercept_high": cal_a + zc * cal_a_se,
    "cal_slope": None if separated else cal_b, "cal_slope_se": None if separated else cal_b_se,
    "cal_slope_low": None if separated else cal_b - zc * cal_b_se, "cal_slope_high": None if separated else cal_b + zc * cal_b_se,
    "brier": brier, "brier_scaled": brier_scaled,
    "ici": sm_err["ici"] if sm_err else None, "e50": sm_err["e50"] if sm_err else None,
    "e90": sm_err["e90"] if sm_err else None, "emax": sm_err["emax"] if sm_err else None, "smoothed": smoothed,
    "hl_chi2": hl["chi2"], "hl_df": float(hl["df"]), "hl_p": hl["p"],
    "spiegelhalter_z": sp["z"], "spiegelhalter_p": sp["p"], "auc": auc, "n_clipped": n_clipped, "n_groups": len(groups),
}
order = np.argsort(p, kind="stable")
keep = order[np.unique(np.round(np.linspace(0, n - 1, min(n, 200))).astype(int))]
charts = [
    cs.chart("calibration", "calibration", "Observed vs predicted by risk group", {
        "predicted": cs.col("Mean predicted risk", [g["mean_p"] for g in groups]),
        "observed": cs.col("Observed proportion", [g["rate"] for g in groups]),
        "n": cs.col("n", [g["n"] for g in groups]),
        "low": cs.col("low", [g["low"] for g in groups]), "high": cs.col("high", [g["high"] for g in groups])}),
]
if sm_err:
    charts.append(cs.chart("smooth", "calibration", f"Loess calibration curve (span {span:g})", {
        "predicted": cs.col("Predicted risk", p[keep]), "observed": cs.col("Smoothed observed rate", sm_err["smooth"][keep])}))
charts.append(cs.chart("risks", "histogram", "Predicted risks", {"x": cs.col("Predicted risk", p)}))
summary = (f"Observed rate {obs_rate:.1%} vs mean predicted {mean_p:.1%} (O/E {oe:.2f}); calibration intercept {cal_a:.2f}, slope {'NA' if separated else f'{cal_b:.2f}'}; "
           f"Brier {brier:.3f}" + (f"; ICI {sm_err['ici']:.3f}." if sm_err else "."))
cs.publish({
    "method": "diagnostic.calibration",
    "methodVersion": "1.1.2",
    "title": "Calibration of predicted risks",
    "engine": cs.engine_info("pandas", "numpy", "statsmodels", "scipy"),
    "n": n,
    "summary": summary,
    "statistics": [
        {"key": "oe_ratio", "label": "Observed / expected", "value": oe},
        {"key": "cal_intercept", "label": "Calibration intercept", "value": cal_a},
        {"key": "cal_slope", "label": "Calibration slope", "value": values["cal_slope"]},
        {"key": "ici", "label": "ICI", "value": values["ici"]},
        {"key": "brier", "label": "Brier score", "value": brier},
        {"key": "spiegelhalter_z", "label": "Spiegelhalter z", "value": sp["z"]},
        {"key": "spiegelhalter_p", "label": "p", "value": sp["p"], "format": "p"},
    ],
    "tables": [
        {"key": "measures", "title": "Calibration measures", "columns": [
            {"key": "measure", "label": "Measure", "type": "string"}, {"key": "value", "label": "Estimate", "type": "number"},
            {"key": "low", "label": f"{pct} CI low", "type": "number"}, {"key": "high", "label": f"{pct} CI high", "type": "number"},
            {"key": "ideal", "label": "Ideal", "type": "string"}],
         "rows": [
            {"measure": "Observed / expected (O/E)", "value": oe, "low": oe_low, "high": oe_high, "ideal": "1"},
            {"measure": "Calibration intercept", "value": cal_a, "low": values["cal_intercept_low"], "high": values["cal_intercept_high"], "ideal": "0"},
            {"measure": "Calibration slope", "value": values["cal_slope"], "low": values["cal_slope_low"], "high": values["cal_slope_high"], "ideal": "1"},
            {"measure": "ICI (mean |smoothed − predicted|)", "value": values["ici"], "low": None, "high": None, "ideal": "0"},
            {"measure": "E50 / E90 / Emax", "value": values["e90"], "low": values["e50"], "high": values["emax"], "ideal": "0"},
            {"measure": "Brier score", "value": brier, "low": None, "high": None, "ideal": "0"},
            {"measure": "Scaled Brier (1 − Brier / Brier of the prevalence)", "value": brier_scaled, "low": None, "high": None, "ideal": "1"},
            {"measure": "AUC (discrimination)", "value": auc, "low": None, "high": None, "ideal": "1"}],
         "note": "The E50 / E90 / Emax row shows E90 with E50 and Emax in the interval columns."},
        {"key": "groups", "title": "Risk groups", "columns": [
            {"key": "group", "label": "Group", "type": "integer"}, {"key": "n", "label": "n", "type": "integer"},
            {"key": "p_min", "label": "Lowest risk", "type": "number"}, {"key": "p_max", "label": "Highest risk", "type": "number"},
            {"key": "mean_p", "label": "Mean predicted", "type": "number"}, {"key": "observed", "label": "Events", "type": "number"},
            {"key": "rate", "label": "Observed rate", "type": "number"}, {"key": "low", "label": f"{pct} CI low", "type": "number"},
            {"key": "high", "label": f"{pct} CI high", "type": "number"}],
         "rows": groups, "note": "Wilson intervals for the observed rate."},
    ],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [
        f"Event: {yc} = {event}. Calibration intercept from a logistic model of the outcome with the log-odds as an offset; slope from regressing the outcome on the log-odds (Wald intervals).",
        f"Hosmer–Lemeshow χ²({hl['df']}) = {hl['chi2']:.2f}" + (f", {cs.fmt_p(hl['p'])}" if hl['p'] is not None else "") + f" over {len(hl['groups'])} groups; with large samples it flags trivial miscalibration.",
    ],
    "charts": charts,
    "values": values,
})

O/E is 0.97: fine on average. Yet the slope is 0.62 and the ICI is 0.070. A model can be right overall and wrong for nearly everyone.

06

What a large p-value means

Predict

Predict first

A second model scores p = .867 on Spiegelhalter's test and p = .760 on Hosmer–Lemeshow. Its slope is 0.99.

Do these show that the model is well calibrated?

Yes, this model is well calibratedIt's compatible with that, but these data can't show it
Reveal

They're compatible with it, and they can't show it. These risks come from the data that fitted the model, a large p-value isn't evidence of fit, and Hosmer–Lemeshow depends on the grouping. Calibration curves also need many events: about 100 events and 100 non-events at the very least (Van Calster and colleagues, 2016).

07

Fix it, on separate data

Read

If the intercept or slope is off, recalibrateRecalibrationAdjusts predicted probabilities so that, say, predictions of 30% come true about 30% of the time.: fit the intercept and slope on separate data, then use them to adjust new predictions. The ranking is unchanged, so the AUC holds.

This matters most after moving a model to a new hospital, a new period or a new market. The event rate shifts, and the intercept with it. So check calibration wherever the model will be used, not only where it was built.

08

Same measures, two dialects

Read
Python
import numpy as np
import pandas as pd
import statsmodels.api as sm

df = pd.read_csv("s5_risk.csv")
y = (df["type"] == "Yes").astype(float)
p = df["p_overfit"]
lp = np.log(p / (1 - p))

binomial = sm.families.Binomial()
slope = sm.GLM(y, sm.add_constant(lp), family=binomial).fit().params.iloc[1]
intercept = sm.GLM(y, np.ones(len(y)), family=binomial, offset=lp).fit().params.iloc[0]
print(y.sum() / p.sum(), intercept, slope, ((p - y) ** 2).mean())
R
df <- read.csv("s5_risk.csv")
y <- as.numeric(df$type == "Yes")
p <- df$p_overfit
lp <- qlogis(p)

slope <- coef(glm(y ~ lp, family = binomial))[["lp"]]
intercept <- coef(glm(y ~ offset(lp), family = binomial))[[1]]
c(oe = sum(y) / sum(p), intercept = intercept, slope = slope, brier = mean((p - y)^2))
09

Check your understanding

Checkpoint

Check yourself

A model's predicted risks add up to 125, and 100 events happened. What is the observed/expected ratio?

Show the answer

Answer: 0.8

100 / 125 = 0.8. The model predicts too many events overall.

Check yourself

A model gives a risk of 0.8 to a person who has the event and 0.2 to a person who doesn't. What is the Brier score over these two people?

Show the answer

Answer: 0.04

Each squared error is 0.2² = 0.04, so the mean is 0.04.

Check yourself

On new data, a model's calibration slope is 0.6. What does that suggest?

Show the answer

Answer: b

A slope below 1 says the log-odds spread too widely. The intercept and O/E speak to the overall rate, and the AUC speaks to ranking.

Check yourself

You recalibrate a model with a new intercept and slope. What happens to its AUC?

Show the answer

Answer: a

A positive linear change of the log-odds keeps everyone's order, and the AUC depends only on order.

10

Recap

Recap
  • Discrimination is order. Calibration is whether the numbers mean what they say.
  • Climb the ladder: mean, then slope, then curve.
  • A model can have O/E near 1 and still be wrong for nearly everyone.
  • Fitting data flatters calibration, so check it where the model will be used.

Concepts in this lesson