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.
What runs in CodeSplash
- STAT187Hosmer–Lemeshow test Runs in CodeSplash
- Calibration of predicted risks Verified in Python and R
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
Right order, wrong numbers
ReadCalibrationCalibrationWhether 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.
Bend the probabilities
ExploreAnswer 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?
Above 1 the model is too extreme; below 1 it hedges. At 1 it is perfectly calibrated.
| Brier | ECE | Calibration slope | AUC |
|---|---|---|---|
| 0.175 | 0.087 | 0.50 | 0.835 |
Commit your prediction above to see the result
Make your prediction to see the result.
Predict the slope
PredictPredict 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?
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.
Levels of calibration
ReadVan Calster and colleagues (2016) describe calibration as a ladder:
| Level | Question | On the card | Ideal |
|---|---|---|---|
| Mean | Is 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 |
| Weak | Too extreme or too timid? | Calibration slope | 1 |
| Moderate | Right across the range? | Curve, ICIIntegrated calibration indexThe average absolute gap between predicted risk and a smoothed observed rate. 0 is ideal., E50, E90, Emax | Curve 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.
Read the card
In the appHere's the exaggerated copy. Look at the Calibration measures table and its Ideal column, then the risk groups and the warning.
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
View data
| high | low | n | Observed proportion | Mean predicted risk |
|---|---|---|---|---|
| 0.1170 | 0.0571 | 231 | 0.0823 | 0.0432 |
| 0.3161 | 0.1548 | 71 | 0.2254 | 0.1790 |
| 0.6206 | 0.3529 | 35 | 0.4857 | 0.3092 |
| 0.4982 | 0.2435 | 36 | 0.3611 | 0.4477 |
| 0.6993 | 0.3467 | 19 | 0.5263 | 0.5738 |
| 0.6618 | 0.3698 | 29 | 0.5172 | 0.6853 |
| 0.7964 | 0.5300 | 31 | 0.6774 | 0.8201 |
| 0.8839 | 0.7448 | 80 | 0.8250 | 0.9473 |
View data
| Smoothed observed rate | Predicted risk |
|---|---|
| −0.0003 | 0.0010 |
| 0.0007 | 0.0017 |
| 0.0021 | 0.0027 |
| 0.0035 | 0.0037 |
| 0.0059 | 0.0054 |
| 0.0062 | 0.0056 |
| 0.0064 | 0.0058 |
| 0.0069 | 0.0061 |
| 0.0075 | 0.0065 |
| 0.0078 | 0.0067 |
| 0.0079 | 0.0068 |
| 0.0083 | 0.0071 |
| 0.0093 | 0.0078 |
| 0.0106 | 0.0086 |
| 0.0114 | 0.0091 |
| 0.0118 | 0.0094 |
| 0.0133 | 0.0104 |
| 0.0141 | 0.0109 |
| 0.0150 | 0.0115 |
| 0.0159 | 0.0121 |
| 0.0182 | 0.0136 |
| 0.0190 | 0.0140 |
| 0.0196 | 0.0145 |
| 0.0203 | 0.0149 |
| 0.0209 | 0.0153 |
| 0.0235 | 0.0169 |
| 0.0241 | 0.0172 |
| 0.0254 | 0.0180 |
| 0.0275 | 0.0192 |
| 0.0279 | 0.0195 |
| 0.0291 | 0.0202 |
| 0.0314 | 0.0216 |
| 0.0325 | 0.0222 |
| 0.0350 | 0.0236 |
| 0.0356 | 0.0240 |
| 0.0363 | 0.0244 |
| 0.0380 | 0.0253 |
| 0.0396 | 0.0262 |
| 0.0399 | 0.0264 |
| 0.0429 | 0.0281 |
| 0.0441 | 0.0287 |
| 0.0451 | 0.0292 |
| 0.0490 | 0.0314 |
| 0.0499 | 0.0318 |
| 0.0504 | 0.0321 |
| 0.0532 | 0.0335 |
| 0.0555 | 0.0347 |
| 0.0605 | 0.0373 |
| 0.0657 | 0.0399 |
| 0.0699 | 0.0419 |
| 0.0725 | 0.0432 |
| 0.0772 | 0.0454 |
| 0.0794 | 0.0464 |
| 0.0827 | 0.0479 |
| 0.0856 | 0.0493 |
| 0.0930 | 0.0526 |
| 0.0948 | 0.0534 |
| 0.1001 | 0.0558 |
| 0.1010 | 0.0561 |
| 0.1030 | 0.0570 |
First 60 of 200 rows.
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
| Measure | Estimate | 90% CI low | 90% CI high | Ideal |
|---|---|---|---|---|
| Observed / expected (O/E) | 0.9747 | 0.8810 | 1.078 | 1 |
| Calibration intercept | −0.0840 | −0.3070 | 0.1390 | 0 |
| Calibration slope | 0.6250 | 0.5322 | 0.7178 | 1 |
| ICI (mean |smoothed − predicted|) | 0.0702 | — | — | 0 |
| E50 / E90 / Emax | 0.1383 | 0.0753 | 0.1488 | 0 |
| Brier score | 0.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
| Group | n | Lowest risk | Highest risk | Mean predicted | Events | Observed rate | 90% CI low | 90% CI high |
|---|---|---|---|---|---|---|---|---|
| 1 | 231 | 0.0010 | 0.1241 | 0.0432 | 19 | 0.0823 | 0.0571 | 0.1170 |
| 2 | 71 | 0.1287 | 0.2483 | 0.1790 | 16 | 0.2254 | 0.1548 | 0.3161 |
| 3 | 35 | 0.2502 | 0.3744 | 0.3092 | 17 | 0.4857 | 0.3529 | 0.6206 |
| 4 | 36 | 0.3797 | 0.4988 | 0.4477 | 13 | 0.3611 | 0.2435 | 0.4982 |
| 5 | 19 | 0.5016 | 0.6160 | 0.5738 | 10 | 0.5263 | 0.3467 | 0.6993 |
| 6 | 29 | 0.6280 | 0.7482 | 0.6853 | 15 | 0.5172 | 0.3698 | 0.6618 |
| 7 | 31 | 0.7538 | 0.8717 | 0.8201 | 21 | 0.6774 | 0.5300 | 0.7964 |
| 8 | 80 | 0.8797 | 0.9999 | 0.9473 | 66 | 0.8250 | 0.7448 | 0.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
))
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
| Measure | Estimate | 90% CI low | 90% CI high | Ideal |
|---|---|---|---|---|
| Observed / expected (O/E) | 0.9747 | 0.8810 | 1.078 | 1 |
| Calibration intercept | −0.0840 | −0.3070 | 0.1390 | 0 |
| Calibration slope | 0.6250 | 0.5322 | 0.7178 | 1 |
| ICI (mean |smoothed − predicted|) | 0.0702 | — | — | 0 |
| E50 / E90 / Emax | 0.1383 | 0.0753 | 0.1488 | 0 |
| Brier score | 0.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
| Group | n | Lowest risk | Highest risk | Mean predicted | Events | Observed rate | 90% CI low | 90% CI high |
|---|---|---|---|---|---|---|---|---|
| 1 | 231 | 0.0010 | 0.1241 | 0.0432 | 19 | 0.0823 | 0.0571 | 0.1170 |
| 2 | 71 | 0.1287 | 0.2483 | 0.1790 | 16 | 0.2254 | 0.1548 | 0.3161 |
| 3 | 35 | 0.2502 | 0.3744 | 0.3092 | 17 | 0.4857 | 0.3529 | 0.6206 |
| 4 | 36 | 0.3797 | 0.4988 | 0.4477 | 13 | 0.3611 | 0.2435 | 0.4982 |
| 5 | 19 | 0.5016 | 0.6160 | 0.5738 | 10 | 0.5263 | 0.3467 | 0.6993 |
| 6 | 29 | 0.6280 | 0.7482 | 0.6853 | 15 | 0.5172 | 0.3698 | 0.6618 |
| 7 | 31 | 0.7538 | 0.8717 | 0.8201 | 21 | 0.6774 | 0.5300 | 0.7964 |
| 8 | 80 | 0.8797 | 0.9999 | 0.9473 | 66 | 0.8250 | 0.7448 | 0.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.
What a large p-value means
PredictPredict 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?
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).
Fix it, on separate data
ReadIf 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.
Same measures, two dialects
Readimport 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())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))Check your understanding
CheckpointCheck 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.
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