Skip to content

Proper scores and calibration: the Brier score and beyond

Judge probabilities with a proper scoring rule and a reliability check together. The Brier score mixes calibration and discrimination, bin summaries depend on binning, and calibration on one population says little about another.

Advanced ~14 min9 steps

What runs in CodeSplash

You will be able to

  • Compute the Brier score and state which column convention it uses
  • Compare a Brier score with a prevalence-only forecast
  • Read calibration intercept, slope and ICI beside the Brier score
  • Fit a recalibration on held-out predictions and check it by slice

Read first

01

Score the whole probability

Read

Accuracy only asks whether the top class was right. A probability forecast says more, and a proper scoring ruleProper scoring ruleA score whose expected value is best when you report your true probability. Log loss and Brier are proper. rewards it for saying the truth: its expected value is best when you report your real belief. Log loss and the Brier scoreBrier scoreThe mean squared error of predicted probabilities; lower is better and it rewards calibration. are proper.

BS=1n∑i∑c=1C(pic−1{yi=c})2.\mathrm{BS} = \frac{1}{n}\sum_i \sum_{c=1}^{C} \left(p_{ic} - \mathbf 1\{y_i = c\}\right)^2 .

Lower is better.

02

Which convention?

Read

For a yes-or-no outcome, many tools use one column: (pi−yi)2(p_i - y_i)^2, the squared gap between the predicted chance of "yes" and what happened. The two-column form above counts both classes, so it is exactly twice as large. In the reference's four-row example, the one-column Brier score is 0.1375.

State the convention whenever you report a Brier score, and compare it with a prevalence-only forecast that gives every case the base rate. A rare outcome makes even a useless forecast's Brier score look small.

Reference · EVA026 · Runs in CodeSplashBrier scoreEvaluates probabilistic predictions with a squared-error proper scoring rule.
03

Brier is not a calibration error

Explore

The Brier score mixes two things: calibration (do 30% forecasts come true 30% of the time?) and discrimination (do cases that happen get higher forecasts?). A model can improve one and worsen the other.

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.

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.

So read it next to a reliability check. Bin summaries such as the expected calibration error change with the number and placement of bins and with sample size; smoothed curves and the integrated calibration index avoid the bin choice.

04

An overfit model, read four ways

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

On held-out rows, an overfit diabetes model scores Brier 0.150, a scaled Brier (skill over the prevalence forecast) of 0.32, and AUC 0.86. It ranks cases well.

Its calibration slope is 0.62: well below 1, so its probabilities are too extreme, the signature of overfitting. The average gap between predicted and smoothed observed risk (ICI) is 0.070.

05

Recalibrate on held-out predictions

Read

Temperature scaling, Platt scaling or isotonic regression can fix miscalibration. Fit them on held-out or out-of-fold predictions, never on the final test set and never on the model's own training predictions.

Then check calibration where it matters. Calibration by slice (by site, period or group) can fail while the overall curve looks perfect, and calibration under one distribution says nothing about calibration after a shift.

06

Calibration in CodeSplash

In the app

Predict's Evaluation tab for a binary model shows the Brier score, calibration intercept and slope, ICI and Spiegelhalter's test, a smoothed calibration curve with a band, and reliability bins with intervals. The Slices tab adds Calibration by slice. Recalibrated runs fit their calibrator on out-of-fold predictions.

For probabilities made elsewhere, Analyze's Calibration of predicted risks method reads an outcome and a probability column and reports the same measures.

07

What runs here

Read
08

Check: Brier and calibration

Checkpoint

Check yourself

A binary model's one-column Brier score is 0.1375. What is the same forecast's Brier score in the two-column convention? Four decimals.

Show the answer

Answer: 0.275

The two-column sum counts the error on both classes, and for two classes they are equal, so it doubles: 0.275.

Check yourself

An outcome occurs in 2% of cases. A model has Brier score 0.019. Is that good?

Show the answer

Answer: b

A rare outcome gives small Brier scores to any forecast. The skill over the prevalence-only forecast is what tells you something.

Check yourself

Model A has a lower Brier score than model B. What follows?

Show the answer

Answer: c

The Brier score combines calibration and discrimination. A lower total can hide worse calibration offset by better ranking.

Check yourself

A model's calibration slope on held-out data is 0.6. What does it mean?

Show the answer

Answer: b

A slope below 1 means the observed log-odds change less than the predicted ones: forecasts near 0 and 1 overstate their certainty.

Check yourself

Where should temperature scaling be fitted?

Show the answer

Answer: c

The calibrator needs honest predictions, and the test set must stay unused until the plan is frozen.

Check yourself

Two reports give different ECE values for the same predictions. What is the likeliest reason?

Show the answer

Answer: a

Bin summaries depend on the binning and on sample size. Report the bins, or use a smoothed measure such as ICI.

09

Recap

Recap
  • Score probabilities with a proper rule (log loss, Brier) and state the Brier convention; two columns doubles one.
  • Compare with a prevalence-only forecast; rare outcomes flatter every Brier score.
  • Brier mixes calibration and discrimination; read slope, intercept and ICI beside it.
  • Recalibrate on held-out predictions, and check calibration by slice and after shifts.

Concepts in this lesson