HDiagnostic accuracy · diagnostic.calibration
Calibration of predicted risks
Do the predicted risks of a model match the observed event rates, overall and across the range of risk?
Compares predicted probabilities with what happened: observed/expected ratio, calibration intercept (calibration-in-the-large) and slope by logistic recalibration, a loess calibration curve with the integrated calibration index (ICI, E50, E90, Emax), risk groups with Wilson intervals, the Brier score, Spiegelhalter's z and the Hosmer–Lemeshow test.
A real result
Example “Pima full missing”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Observed rate 33.3% vs mean predicted 33.3% (O/E 1.00); calibration intercept 0.00, slope 0.99; Brier 0.145; ICI 0.026.
- Observed / expected
- 1.002
- Calibration intercept
- 0.0037
- Calibration slope
- 0.9902
- ICI
- 0.0257
- Brier score
- 0.1455
- Spiegelhalter z
- 0.1671
- p
- .867
Plots
View data
| high | low | n | Observed proportion | Mean predicted risk |
|---|---|---|---|---|
| 0.0994 | 0.0033 | 53 | 0.0189 | 0.0334 |
| 0.1012 | 0.0034 | 52 | 0.0192 | 0.0652 |
| 0.1786 | 0.0297 | 53 | 0.0755 | 0.1008 |
| 0.2752 | 0.0801 | 52 | 0.1538 | 0.1432 |
| 0.3757 | 0.1493 | 53 | 0.2453 | 0.1968 |
| 0.4025 | 0.1677 | 52 | 0.2692 | 0.2681 |
| 0.5950 | 0.3334 | 52 | 0.4615 | 0.3838 |
| 0.6562 | 0.3966 | 53 | 0.5283 | 0.5345 |
| 0.8009 | 0.5573 | 52 | 0.6923 | 0.7180 |
| 0.9345 | 0.7516 | 53 | 0.8679 | 0.8825 |
View data
| Smoothed observed rate | Predicted risk |
|---|---|
| −0.0394 | 0.0103 |
| −0.0337 | 0.0142 |
| −0.0266 | 0.0190 |
| −0.0205 | 0.0232 |
| −0.0120 | 0.0290 |
| −0.0110 | 0.0297 |
| −0.0102 | 0.0302 |
| −0.0092 | 0.0309 |
| −0.0069 | 0.0325 |
| −0.0059 | 0.0332 |
| −0.0058 | 0.0332 |
| −0.0044 | 0.0342 |
| −0.0014 | 0.0362 |
| 0.0019 | 0.0385 |
| 0.0040 | 0.0400 |
| 0.0043 | 0.0402 |
| 0.0076 | 0.0424 |
| 0.0107 | 0.0446 |
| 0.0127 | 0.0459 |
| 0.0139 | 0.0467 |
| 0.0197 | 0.0507 |
| 0.0207 | 0.0514 |
| 0.0220 | 0.0523 |
| 0.0239 | 0.0536 |
| 0.0252 | 0.0545 |
| 0.0309 | 0.0584 |
| 0.0326 | 0.0596 |
| 0.0344 | 0.0608 |
| 0.0371 | 0.0627 |
| 0.0383 | 0.0635 |
| 0.0425 | 0.0664 |
| 0.0449 | 0.0681 |
| 0.0472 | 0.0697 |
| 0.0490 | 0.0709 |
| 0.0507 | 0.0721 |
| 0.0521 | 0.0731 |
| 0.0543 | 0.0746 |
| 0.0554 | 0.0754 |
| 0.0589 | 0.0777 |
| 0.0612 | 0.0794 |
| 0.0622 | 0.0801 |
| 0.0663 | 0.0829 |
| 0.0682 | 0.0842 |
| 0.0685 | 0.0844 |
| 0.0715 | 0.0865 |
| 0.0724 | 0.0871 |
| 0.0794 | 0.0920 |
| 0.0845 | 0.0955 |
| 0.0865 | 0.0970 |
| 0.0910 | 0.1001 |
| 0.0937 | 0.1020 |
| 0.0972 | 0.1044 |
| 0.1011 | 0.1072 |
| 0.1025 | 0.1082 |
| 0.1044 | 0.1095 |
| 0.1111 | 0.1142 |
| 0.1135 | 0.1159 |
| 0.1155 | 0.1173 |
| 0.1175 | 0.1187 |
| 0.1181 | 0.1192 |
First 60 of 200 rows.
View data
| Predicted risk |
|---|
| 0.0511 |
| 0.8341 |
| 0.0756 |
| 0.7643 |
| 0.3225 |
| 0.0643 |
| 0.6767 |
| 0.6976 |
| 0.7298 |
| 0.9380 |
| 0.5526 |
| 0.9094 |
| 0.2208 |
| 0.2531 |
| 0.0332 |
| 0.1255 |
| 0.6687 |
| 0.4996 |
| 0.1074 |
| 0.0357 |
| 0.2089 |
| 0.0644 |
| 0.0309 |
| 0.0964 |
| 0.6805 |
| 0.0584 |
| 0.5031 |
| 0.2001 |
| 0.2041 |
| 0.1506 |
| 0.2986 |
| 0.2378 |
| 0.3836 |
| 0.2120 |
| 0.4687 |
| 0.0332 |
| 0.0124 |
| 0.1312 |
| 0.8998 |
| 0.1224 |
| 0.2432 |
| 0.0230 |
| 0.0707 |
| 0.2125 |
| 0.2192 |
| 0.2078 |
| 0.5048 |
| 0.9593 |
| 0.0731 |
| 0.0579 |
| 0.6646 |
| 0.1732 |
| 0.0920 |
| 0.3344 |
| 0.1340 |
| 0.0713 |
| 0.4015 |
| 0.7512 |
| 0.8396 |
| 0.0707 |
First 60 of 525 rows.
Assumptions
- Enough events and non-events — 175 events and 350 non-events.
- Predictions are probabilities — All predictions lie strictly between 0 and 1.
Calibration measures
| Measure | Estimate | 95% CI low | 95% CI high | Ideal |
|---|---|---|---|---|
| Observed / expected (O/E) | 1.002 | 0.8875 | 1.130 | 1 |
| Calibration intercept | 0.0037 | −0.2216 | 0.2290 | 0 |
| Calibration slope | 0.9902 | 0.8133 | 1.167 | 1 |
| ICI (mean |smoothed − predicted|) | 0.0257 | — | — | 0 |
| E50 / E90 / Emax | 0.0495 | 0.0253 | 0.0614 | 0 |
| Brier score | 0.1455 | — | — | 0 |
| Scaled Brier (1 − Brier / Brier of the prevalence) | 0.3453 | — | — | 1 |
| AUC (discrimination) | 0.8532 | — | — | 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 | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|---|
| 1 | 53 | 0.0103 | 0.0495 | 0.0334 | 1 | 0.0189 | 0.0033 | 0.0994 |
| 2 | 52 | 0.0507 | 0.0794 | 0.0652 | 1 | 0.0192 | 0.0034 | 0.1012 |
| 3 | 53 | 0.0801 | 0.1224 | 0.1008 | 4 | 0.0755 | 0.0297 | 0.1786 |
| 4 | 52 | 0.1237 | 0.1625 | 0.1432 | 8 | 0.1538 | 0.0801 | 0.2752 |
| 5 | 53 | 0.1683 | 0.2208 | 0.1968 | 13 | 0.2453 | 0.1493 | 0.3757 |
| 6 | 52 | 0.2232 | 0.3221 | 0.2681 | 14 | 0.2692 | 0.1677 | 0.4025 |
| 7 | 52 | 0.3225 | 0.4357 | 0.3838 | 24 | 0.4615 | 0.3334 | 0.5950 |
| 8 | 53 | 0.4371 | 0.6268 | 0.5345 | 28 | 0.5283 | 0.3966 | 0.6562 |
| 9 | 52 | 0.6365 | 0.7903 | 0.7180 | 36 | 0.6923 | 0.5573 | 0.8009 |
| 10 | 53 | 0.7932 | 0.9950 | 0.8825 | 46 | 0.8679 | 0.7516 | 0.9345 |
Wilson intervals for the observed rate.
- 7 of 532 rows were left out because a value was missing.
- Event: diabetic = true. 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 χ²(8) = 4.98, p = .760 over 10 groups; with large samples it flags trivial miscalibration.
Observed rate 33.3% vs mean predicted 33.3% (O/E 1.00); calibration intercept 0.00, slope 0.99; Brier 0.145; ICI 0.026.
- Observed / expected
- 1.002
- Calibration intercept
- 0.0037
- Calibration slope
- 0.9902
- ICI
- 0.0257
- Brier score
- 0.1455
- Spiegelhalter z
- 0.1671
- p
- .867
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough events and non-events — 175 events and 350 non-events.
- Predictions are probabilities — All predictions lie strictly between 0 and 1.
Calibration measures
| Measure | Estimate | 95% CI low | 95% CI high | Ideal |
|---|---|---|---|---|
| Observed / expected (O/E) | 1.002 | 0.8875 | 1.130 | 1 |
| Calibration intercept | 0.0037 | −0.2216 | 0.2290 | 0 |
| Calibration slope | 0.9902 | 0.8133 | 1.167 | 1 |
| ICI (mean |smoothed − predicted|) | 0.0257 | — | — | 0 |
| E50 / E90 / Emax | 0.0495 | 0.0253 | 0.0614 | 0 |
| Brier score | 0.1455 | — | — | 0 |
| Scaled Brier (1 − Brier / Brier of the prevalence) | 0.3453 | — | — | 1 |
| AUC (discrimination) | 0.8532 | — | — | 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 | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|---|
| 1 | 53 | 0.0103 | 0.0495 | 0.0334 | 1 | 0.0189 | 0.0033 | 0.0994 |
| 2 | 52 | 0.0507 | 0.0794 | 0.0652 | 1 | 0.0192 | 0.0034 | 0.1012 |
| 3 | 53 | 0.0801 | 0.1224 | 0.1008 | 4 | 0.0755 | 0.0297 | 0.1786 |
| 4 | 52 | 0.1237 | 0.1625 | 0.1432 | 8 | 0.1538 | 0.0801 | 0.2752 |
| 5 | 53 | 0.1683 | 0.2208 | 0.1968 | 13 | 0.2453 | 0.1493 | 0.3757 |
| 6 | 52 | 0.2232 | 0.3221 | 0.2681 | 14 | 0.2692 | 0.1677 | 0.4025 |
| 7 | 52 | 0.3225 | 0.4357 | 0.3838 | 24 | 0.4615 | 0.3334 | 0.5950 |
| 8 | 53 | 0.4371 | 0.6268 | 0.5345 | 28 | 0.5283 | 0.3966 | 0.6562 |
| 9 | 52 | 0.6365 | 0.7903 | 0.7180 | 36 | 0.6923 | 0.5573 | 0.8009 |
| 10 | 53 | 0.7932 | 0.9950 | 0.8825 | 46 | 0.8679 | 0.7516 | 0.9345 |
Wilson intervals for the observed rate.
- 7 of 532 rows were left out because a value was missing.
- Event: diabetic = true. 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 χ²(8) = 4.98, p = .760 over 10 groups; with large samples it flags trivial miscalibration.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Pima full missings5_risk · outcome: diabetic · predicted: risk score
- Overfit equal binss5_risk · outcome: type · predicted: p_overfit
- Logit scales5_risk · outcome: diabetic · predicted: lp_full
- Percent scales5_risk · outcome: type · predicted: p_percent
- Ties edgess5_ties · outcome: event · predicted: p_edge
- External validation dfs5_risk · outcome: diabetic · predicted: risk score
- Degenerate constants5_risk · outcome: diabetic · predicted: risk score
- Degenerate tiess5_risk · outcome: diabetic · predicted: risk score
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Multiple predictors: logistic / ML · Statistics Guide · H — Diagnostic accuracy
- PR curves, calibration, decision curves · Statistics Guide · H — Diagnostic accuracy
- Probabilistic forecasting (Bayesian, deep ensembles) · DS & ML Decision Guide · Predict — forecast or classify outcomes
What you need
- Observed outcomecategorical / boolean · 1 column · 2–2 levels
- What happened (two levels).
- Predicted risknumeric · 1 column
- The model's predicted probability of the event (or a percentage or log-odds — see "Scale").
Choices you make
hypothesis
- Event leveldefault —
The outcome level the predictions are risks of (default the last stored level — true for true/false columns).
- Scale of the predictionsdefault probability
The units of your prediction column: probabilities, percentages or log-odds. All are converted to probabilities.
- Probability (0–1)(default) — Your column holds probabilities from 0 to 1, so nothing is converted.
- Percent (0–100) — Your column holds percentages from 0 to 100, which are divided by 100.
- Log-odds (linear predictor) — Your column holds log-odds, such as a model's linear predictor, which are converted to probabilities.
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
statistics
- Risk groupsdefault quantile
How predictions are grouped: equal-size risk groups (deciles) or equal-width bins on 0–1.
- Equal-size groups (deciles of risk)(default) — Puts the same number of predictions in each group; the usual choice, since every group is well filled.
- Equal-width bins on 0–1 — Cuts 0–1 into equal-width bins; easy to read, though some bins may hold few predictions.
- Number of groupsdefault 10
Also the number of Hosmer–Lemeshow groups.
- Where the predictions come from (Hosmer–Lemeshow df)default development
Sets the Hosmer–Lemeshow degrees of freedom: groups − 2 for a model fitted on these rows, groups for probabilities fixed before seeing them.
- A model fitted on these rows (df = groups − 2)(default) — The usual goodness-of-fit check of a model on its own data.
- An external model or score (df = groups) — Validation of predictions made without these rows (Hosmer, Lemeshow & Sturdivant 2013).
- Loess spandefault 0.75
Share of the data each point of the loess calibration curve uses (degree 2, evaluated exactly at each prediction).
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Enough events and non-events
Calibration curves need many events: about 100 events and 100 non-events at least, 200 for a stable flexible curve (Van Calster et al. 2016).
Predictions are probabilities
Predictions must lie in [0, 1]; exact 0 or 1 are moved 1e-10 inside for the log-odds.
What it reports
- Tests: Predicted risks are miscalibrated (Spiegelhalter)
- n
- How many independent units the analysis used; it sets precision and power.
- n_events
- How many independent units the analysis used; it sets precision and power.
- positive_level
- Which group counts as first (or treated, or positive) decides the sign of differences and ratios on the card.
- observed_rate
- Whether predicted probabilities match observed frequencies — of cases given 30%, about 30% should be positive.
- mean_predicted
- Whether predicted probabilities match observed frequencies — of cases given 30%, about 30% should be positive.
- oe_ratio
- Whether predicted risks are right on average. It's measured by the observed/expected ratio or the calibration intercept.
- oe_low
- A range of effect values compatible with your data at the chosen confidence level.
- oe_high
- A range of effect values compatible with your data at the chosen confidence level.
- cal_intercept
- Whether predicted risks are right on average. It's measured by the observed/expected ratio or the calibration intercept.
- cal_intercept_se
- The typical size of the error in an estimate, the standard deviation of its sampling distribution.
- cal_intercept_low
- A range of effect values compatible with your data at the chosen confidence level.
- cal_intercept_high
- A range of effect values compatible with your data at the chosen confidence level.
- cal_slope
- The coefficient from regressing the outcome on a model's log-odds. Below 1 means the predicted risks are too extreme.
- cal_slope_se
- The typical size of the error in an estimate, the standard deviation of its sampling distribution.
- cal_slope_low
- A range of effect values compatible with your data at the chosen confidence level.
- cal_slope_high
- A range of effect values compatible with your data at the chosen confidence level.
- brier
- The mean squared error of predicted probabilities; lower is better and it rewards calibration.
- brier_scaled
- The mean squared error of predicted probabilities; lower is better and it rewards calibration.
- ici
- The average absolute gap between predicted risk and a smoothed observed rate. 0 is ideal.
- e50
- The average absolute gap between predicted risk and a smoothed observed rate. 0 is ideal.
- e90
- The average absolute gap between predicted risk and a smoothed observed rate. 0 is ideal.
- emax
- The average absolute gap between predicted risk and a smoothed observed rate. 0 is ideal.
- smoothed
- True when a loess calibration curve could be fitted; false with too few distinct risks, and then ICI, E50, E90 and Emax are empty.
- hl_chi2
- A sum of squared, scaled differences between observed and expected counts or estimates.
- hl_df
- How much independent information is left to estimate variability after fitting the model.
- hl_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- spiegelhalter_z
- An estimate in standard-error units, compared with the standard normal distribution.
- spiegelhalter_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- auc
- The chance a random positive scores higher than a random negative; 0.5 is guessing, 1 is perfect ranking.
- n_clipped
- How many independent units the analysis used; it sets precision and power.
- n_groups
- How many independent units the analysis used; it sets precision and power.
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-9). Python uses pandas, numpy, scipy, statsmodels, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Calibration intercept and slope are maximum-likelihood fits (R glm, Python statsmodels GLM, both stop when the deviance changes by less than 1e-14 relative); usually identical, but with exact 0/1 predictions (log-odds ±23) the deviance is flat near the optimum and the estimates differ by up to 1e-6.
- The loess curve is R's loess(surface = 'direct'); Python reproduces it with the codesplash twin (same neighborhoods and weights).
The exact script CodeSplash ran for example “Pima full missing” · 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 e3d8f53640f5c069
# 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=["diabetic", "risk score"])
n_input = len(df)
df["diabetic"] = pd.Categorical(df["diabetic"], categories=["false", "true"]) # stored level order
df = df.dropna(subset=["diabetic", "risk score"]) # listwise deletion over the analysis columns
df["diabetic"] = df["diabetic"].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, ["diabetic", "risk score"]) # infinite values stop the run (registry/errors.yaml)
# %% Predictions
yc, pc = "diabetic", "risk score"
y_levels = ["false", "true"] # 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.95
zc = float(stats.norm.ppf(1 - (1 - conf) / 2))
bins, binning, span = int(10), "quantile", 0.75
# %% 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,
})
The exact script CodeSplash ran for example “Pima full missing” · 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 e3d8f53640f5c069
# 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("diabetic", "risk score")))
n_input <- nrow(df)
df[["diabetic"]] <- factor(df[["diabetic"]], levels = c("false", "true")) # stored level order
df <- df[stats::complete.cases(df[c("diabetic", "risk score")]), , 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("diabetic", "risk score")) # infinite values stop the run (registry/errors.yaml)
# %% Predictions
yc <- "diabetic"
pc <- "risk score"
y_levels <- c("false", "true") # 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.95
zc <- stats::qnorm(1 - (1 - conf) / 2)
bins <- as.integer(10)
binning <- "quantile"
span <- 0.75
# %% 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
))
Sources
- Austin, P. C., & Steyerberg, E. W. (2019). The Integrated Calibration Index (ICI) and related metrics for quantifying the calibration of logistic regression models. Statistics in Medicine, 38, 4051–4065.
- Van Calster, B., Nieboer, D., Vergouwe, Y., De Cock, B., Pencina, M. J., & Steyerberg, E. W. (2016). A calibration hierarchy for risk models was defined: from utopia to empirical data. Journal of Clinical Epidemiology, 74, 167–176.
- Spiegelhalter, D. J. (1986). Probabilistic prediction in patient management and clinical trials. Statistics in Medicine, 5, 421–433.
- Hosmer, D. W., & Lemeshow, S. (1980). Goodness of fit tests for the multiple logistic regression model. Communications in Statistics — Theory and Methods, 9, 1043–1069.
- Debray, T. P. A., et al. (2017). A guide to systematic review and meta-analysis of prediction model performance. BMJ, 356, i6460.
From the CodeSplash method registry · diagnostic.calibration v1.1.2.