Skip to content

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.

Verified in Python and R Python and R agree to 6 decimals

A real result

Example “Pima full missing”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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

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

Observed vs predicted by risk groupDo predicted probabilities match observed frequencies?
View data
highlownObserved proportionMean predicted risk
0.09940.0033530.01890.0334
0.10120.0034520.01920.0652
0.17860.0297530.07550.1008
0.27520.0801520.15380.1432
0.37570.1493530.24530.1968
0.40250.1677520.26920.2681
0.59500.3334520.46150.3838
0.65620.3966530.52830.5345
0.80090.5573520.69230.7180
0.93450.7516530.86790.8825
Loess calibration curve (span 0.75)Do predicted probabilities match observed frequencies?
View data
Smoothed observed ratePredicted risk
−0.03940.0103
−0.03370.0142
−0.02660.0190
−0.02050.0232
−0.01200.0290
−0.01100.0297
−0.01020.0302
−0.00920.0309
−0.00690.0325
−0.00590.0332
−0.00580.0332
−0.00440.0342
−0.00140.0362
0.00190.0385
0.00400.0400
0.00430.0402
0.00760.0424
0.01070.0446
0.01270.0459
0.01390.0467
0.01970.0507
0.02070.0514
0.02200.0523
0.02390.0536
0.02520.0545
0.03090.0584
0.03260.0596
0.03440.0608
0.03710.0627
0.03830.0635
0.04250.0664
0.04490.0681
0.04720.0697
0.04900.0709
0.05070.0721
0.05210.0731
0.05430.0746
0.05540.0754
0.05890.0777
0.06120.0794
0.06220.0801
0.06630.0829
0.06820.0842
0.06850.0844
0.07150.0865
0.07240.0871
0.07940.0920
0.08450.0955
0.08650.0970
0.09100.1001
0.09370.1020
0.09720.1044
0.10110.1072
0.10250.1082
0.10440.1095
0.11110.1142
0.11350.1159
0.11550.1173
0.11750.1187
0.11810.1192

First 60 of 200 rows.

Predicted risksHow is one numeric variable distributed?
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

MeasureEstimate95% CI low95% CI highIdeal
Observed / expected (O/E)1.0020.88751.1301
Calibration intercept0.0037−0.22160.22900
Calibration slope0.99020.81331.1671
ICI (mean |smoothed − predicted|)0.0257——0
E50 / E90 / Emax0.04950.02530.06140
Brier score0.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

GroupnLowest riskHighest riskMean predictedEventsObserved rate95% CI low95% CI high
1530.01030.04950.033410.01890.00330.0994
2520.05070.07940.065210.01920.00340.1012
3530.08010.12240.100840.07550.02970.1786
4520.12370.16250.143280.15380.08010.2752
5530.16830.22080.1968130.24530.14930.3757
6520.22320.32210.2681140.26920.16770.4025
7520.32250.43570.3838240.46150.33340.5950
8530.43710.62680.5345280.52830.39660.6562
9520.63650.79030.7180360.69230.55730.8009
10530.79320.99500.8825460.86790.75160.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.
Python

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

MeasureEstimate95% CI low95% CI highIdeal
Observed / expected (O/E)1.0020.88751.1301
Calibration intercept0.0037−0.22160.22900
Calibration slope0.99020.81331.1671
ICI (mean |smoothed − predicted|)0.0257——0
E50 / E90 / Emax0.04950.02530.06140
Brier score0.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

GroupnLowest riskHighest riskMean predictedEventsObserved rate95% CI low95% CI high
1530.01030.04950.033410.01890.00330.0994
2520.05070.07940.065210.01920.00340.1012
3530.08010.12240.100840.07550.02970.1786
4520.12370.16250.143280.15380.08010.2752
5530.16830.22080.1968130.24530.14930.3757
6520.22320.32210.2681140.26920.16770.4025
7520.32250.43570.3838240.46150.33340.5950
8530.43710.62680.5345280.52830.39660.6562
9520.63650.79030.7180360.69230.55730.8009
10530.79320.99500.8825460.86790.75160.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).
Python

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,
})
R

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.