Skip to content

Expected calibration error and reliability diagrams

When a model built on learned features says 80%, does it happen 80% of the time? Bin the predictions, compare confidence with accuracy, and read ECE with its binning, its bias and what it can hide.

Advanced ~13 min8 steps

What runs in CodeSplash

You will be able to

  • Draw a reliability diagram and compute ECE from binned confidences
  • Say how bin choice and sample size change ECE
  • Explain why a low ECE doesn't prove calibration, and why ranking metrics ignore it
  • Read CodeSplash's calibration checks and fix overconfidence with temperature scaling

Read first

01

From features to probabilities

Read

Self-supervised features usually end up feeding a classifier, and that classifier outputs probabilities. A probability is a promise: among cases given 80%, about 80% should turn out positive. That property is calibrationCalibrationWhether predicted probabilities match observed frequencies — of cases given 30%, about 30% should be positive., and it is separate from how well the model ranks cases. A model can rank perfectly and still be badly calibrated.

02

The reliability diagram

Read

Sort predictions into bins by confidence. In each bin, plot the mean confidence against the observed accuracy. A calibrated model's points sit on the diagonal; points below it mean overconfidence, above it underconfidence.

Expected calibration errorExpected calibration error (ECE)The average gap between predicted probability and observed frequency across probability bins, weighted by bin size. (ECE) summarizes the diagram as a weighted average gap:

ECE=∑bnbn∣acc(b)−conf(b)∣.\mathrm{ECE} = \sum_{b} \frac{n_b}{n} \left| \mathrm{acc}(b) - \mathrm{conf}(b) \right| .

In the reference's four-prediction example with two bins, ECE is 0.15.

03

ECE depends on its bins

Read

ECE is a summary of a binning, not a property of the model alone:

  • Bin scheme. Equal-width bins can leave some nearly empty; equal-mass bins hold equal counts. Name the scheme and the number.
  • Sample size. With few cases per bin, accuracy is noisy and the absolute gaps add up, so ECE is biased upward on small test sets.
  • Cancellation. Over- and underconfident cases in one bin can average out, so an ECE near zero doesn't prove calibration.
  • Top label only. For many classes, the usual ECE checks only the predicted class's probability.
04

Overconfidence, live

Explore

HExplorable · Calibration and reliability

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

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

How sure?
2.00

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

2000
10
BrierECECalibration slopeAUC
0.1750.0870.500.835

Commit your prediction above to see the result

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

Make your prediction to see the result.

Raise Overconfidence and watch the reliability curve bend away from the diagonal and ECE climb while the AUC stays put: ranking ignores calibration. Change Bins and watch ECE move for the same model.

Change the number and kind of bins to see how much of an ECE is the bins talking, then fit one temperature.

HExplorable · How many bins? ECE and temperature scaling

The expected calibration error depends on how you bin. How much of a model's ECE is the bins talking, and can one temperature fix the model?

Score a perfectly calibrated model with these bins on these rows. What ECE will it get?

How sure?
2.00

The model's logits are this many times the truth's. Same model as Calibration and reliability.

1000

Half the rows fit the temperature; the other half score every ECE.

10

More bins see finer miscalibration but hold fewer rows each.

Bin edges

Equal-width bins split [0, 1] evenly; equal-count bins put the same number of predictions in each.

expected calibration error 0.100after T = 2.16 0.033perfect model 0.040

Blue dots are sized by how many rows fall in the bin. Gray dots are a perfectly calibrated model on the same rows: their distance from the diagonal is pure sampling noise, and it sets a floor under any calibration error you compute with these bins.

Commit your prediction above to see the result

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

Make your prediction to see the result.

05

Calibration checks in CodeSplash

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

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

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

Plots

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

First 60 of 200 rows.

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

First 60 of 532 rows.

Assumptions

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

Calibration measures

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

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

Risk groups

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

Wilson intervals for the observed rate.

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

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

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

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

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

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

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

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

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

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

Assumptions

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

Calibration measures

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

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

Risk groups

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

Wilson intervals for the observed rate.

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

# %% Setup
import math

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

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

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

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

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

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

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

Calibration of predicted risks reports smoothed measures that need no bins: the integrated calibration indexIntegrated calibration indexThe average absolute gap between predicted risk and a smoothed observed rate. 0 is ideal. (ICI), the mean gap between a smoothed calibration curve and the diagonal, here 0.070; and the calibration slopeCalibration slopeThe coefficient from regressing the outcome on a model's log-odds. Below 1 means the predicted risks are too extreme., here 0.62. A slope below 1 means predictions are too extreme: classic overfitting.

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 1.00; Brier 0.144; ICI 0.024.

Observed / expected
1.000
Calibration intercept
1.287e-8
Calibration slope
1.0000
ICI
0.0242
Brier score
0.1442
Spiegelhalter z
0.0499
p
.960

Plots

Observed vs predicted by risk groupDo predicted probabilities match observed frequencies?
View data
highlownObserved proportionMean predicted risk
0.09770.0033540.01850.0337
0.09940.0033530.01890.0648
0.17860.0297530.07550.1000
0.27050.0785530.15090.1428
0.35530.1345530.22640.1966
0.41570.1797530.28300.2672
0.58550.3266530.45280.3834
0.65620.3966530.52830.5342
0.80480.5646530.69810.7163
0.93580.7558540.87040.8831
Loess calibration curve (span 0.75)Do predicted probabilities match observed frequencies?
View data
Smoothed observed ratePredicted risk
−0.04010.0103
−0.03430.0142
−0.02720.0190
−0.02110.0232
−0.01260.0290
−0.01150.0297
−0.01080.0302
−0.00900.0314
−0.00750.0325
−0.00640.0332
−0.00600.0335
−0.00490.0342
−0.00190.0362
0.00140.0385
0.00350.0400
0.00460.0407
0.00820.0432
0.01020.0446
0.01240.0460
0.01430.0473
0.01930.0507
0.02080.0518
0.02220.0527
0.02340.0536
0.02470.0545
0.02960.0579
0.03070.0586
0.03290.0601
0.03640.0626
0.03720.0631
0.03920.0644
0.04290.0670
0.04450.0681
0.04820.0707
0.04910.0713
0.05020.0721
0.05250.0737
0.05480.0753
0.05520.0756
0.05920.0783
0.06070.0794
0.06200.0802
0.06680.0836
0.06780.0843
0.06840.0847
0.07170.0870
0.07430.0888
0.07970.0926
0.08500.0964
0.08920.0993
0.09160.1010
0.09590.1040
0.09780.1054
0.10070.1074
0.10320.1091
0.10920.1134
0.11060.1144
0.11470.1173
0.11540.1178
0.11680.1188

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.0545
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.2100
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

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

MeasureEstimate95% CI low95% CI highIdeal
Observed / expected (O/E)1.0000.88661.1281
Calibration intercept1.287e-8−0.22410.22410
Calibration slope1.00000.82321.1771
ICI (mean |smoothed − predicted|)0.0242——0
E50 / E90 / Emax0.04560.02400.06110
Brier score0.1442——0
Scaled Brier (1 − Brier / Brier of the prevalence)0.3504——1
AUC (discrimination)0.8552——1

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

Risk groups

GroupnLowest riskHighest riskMean predictedEventsObserved rate95% CI low95% CI high
1540.01030.05070.033710.01850.00330.0977
2530.05110.07940.064810.01890.00330.0994
3530.07940.12030.100040.07550.02970.1786
4530.12240.16250.142880.15090.07850.2705
5530.16830.22040.1966120.22640.13450.3553
6530.22080.32210.2672150.28300.17970.4157
7530.32250.43570.3834240.45280.32660.5855
8530.43710.61950.5342280.52830.39660.6562
9530.62680.79030.7163370.69810.56460.8048
10540.79320.99500.8831470.87040.75580.9358

Wilson intervals for the observed rate.

  • 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.24, p = .835 over 10 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 3c40a459cc1b9bbd
# 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", "lp_full")))
n_input <- nrow(df)
df[["diabetic"]] <- factor(df[["diabetic"]], levels = c("false", "true"))  # stored level order
df <- df[stats::complete.cases(df[c("diabetic", "lp_full")]), , 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", "lp_full"))  # infinite values stop the run (registry/errors.yaml)

# %% Predictions
yc <- "diabetic"
pc <- "lp_full"
y_levels <- c("false", "true")  # stored level order
event <- "true"  # default: the last level ("true")
y <- as.numeric(as.character(df[[yc]]) == event)
raw <- as.numeric(df[[pc]])
scale <- "logit"
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
))
Python

Observed rate 33.3% vs mean predicted 33.3% (O/E 1.00); calibration intercept 0.00, slope 1.00; Brier 0.144; ICI 0.024.

Observed / expected
1.000
Calibration intercept
1.287e-8
Calibration slope
1.0000
ICI
0.0242
Brier score
0.1442
Spiegelhalter z
0.0499
p
.960

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

MeasureEstimate95% CI low95% CI highIdeal
Observed / expected (O/E)1.0000.88661.1281
Calibration intercept1.287e-8−0.22410.22410
Calibration slope1.00000.82321.1771
ICI (mean |smoothed − predicted|)0.0242——0
E50 / E90 / Emax0.04560.02400.06110
Brier score0.1442——0
Scaled Brier (1 − Brier / Brier of the prevalence)0.3504——1
AUC (discrimination)0.8552——1

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

Risk groups

GroupnLowest riskHighest riskMean predictedEventsObserved rate95% CI low95% CI high
1540.01030.05070.033710.01850.00330.0977
2530.05110.07940.064810.01890.00330.0994
3530.07940.12030.100040.07550.02970.1786
4530.12240.16250.142880.15090.07850.2705
5530.16830.22040.1966120.22640.13450.3553
6530.22080.32210.2672150.28300.17970.4157
7530.32250.43570.3834240.45280.32660.5855
8530.43710.61950.5342280.52830.39660.6562
9530.62680.79030.7163370.69810.56460.8048
10540.79320.99500.8831470.87040.75580.9358

Wilson intervals for the observed rate.

  • 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.24, p = .835 over 10 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 3c40a459cc1b9bbd
# 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", "lp_full"])
n_input = len(df)
df["diabetic"] = pd.Categorical(df["diabetic"], categories=["false", "true"])  # stored level order
df = df.dropna(subset=["diabetic", "lp_full"])  # 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", "lp_full"])  # infinite values stop the run (registry/errors.yaml)

# %% Predictions
yc, pc = "diabetic", "lp_full"
y_levels = ["false", "true"]  # stored level order
event = "true"  # default: the last level ("true")
y = (df[yc].astype(str) == event).to_numpy().astype(float)
raw = df[pc].to_numpy(dtype=float)
scale = "logit"
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,
})

Scored on the very rows a logistic model was fit to, its linear predictor has slope 1.00 and ICI 0.024. A logistic fit is calibrated on its own training rows by construction, so this says nothing about new data: check calibration on held-out rows. Predict's evaluation reports ECE with equal-width bins for every classifier.

06

Fixing overconfidence

Read

Temperature scalingTemperature scalingDivides a model's logits by one learned number to soften or sharpen its probabilities without changing its ranking. divides a classifier's logits by one number fitted on held-out data. It changes the probabilities without changing their order, so accuracy and AUC stay the same while calibration improves. Fit it on a calibration split, never on the test rows you'll report.

07

Check: calibration

Checkpoint

Check yourself

In one bin holding half the cases, mean confidence is 0.9 and accuracy is 0.7. What does this bin add to ECE?

Show the answer

Answer: a

ECE weights each bin's absolute gap by its share of cases: 0.5 × |0.7 − 0.9| = 0.1.

Check yourself

A classifier's AUC is 0.92 and its ECE is high. What's going on?

Show the answer

Answer: a

AUC depends only on order. Calibration is about the probabilities themselves; temperature scaling can fix it without changing the order.

Check yourself

A model's ECE is near zero on 10 equal-width bins. Is it calibrated?

Show the answer

Answer: b

A small ECE is consistent with calibration but doesn't prove it. Check the reliability diagram and a smoothed measure such as ICI.

Check yourself

On a test set of 150 cases, 15 bins give a higher ECE than 5 bins for the same model. Why?

Show the answer

Answer: a

ECE depends on its binning and sample size. Report the scheme, or use a bin-free smoothed measure such as ICI.

08

Recap

Recap
  • Calibration asks whether stated probabilities come true; ranking metrics like AUC ignore it.
  • A reliability diagram plots confidence against accuracy by bin; ECE is the weighted average gap.
  • ECE depends on bins and sample size, and a small value can hide canceling errors.
  • CodeSplash reports ECE in Predict and ICI and the calibration slope in Calibration of predicted risks; temperature scaling fixes overconfidence.

Concepts in this lesson