Evaluating saved predictions
Predictions made elsewhere still deserve an honest check. Compare two models on the same rows, audit intervals and prediction sets, score whole distributions, and test an out-of-distribution score.
What runs in CodeSplash
- Compare two models' predictions Verified in Python and R
- Audit prediction intervals or sets Verified in Python and R
- Score probabilistic predictions Verified in Python and R
- Evaluate out-of-distribution detection Verified in Python and R
You will be able to
- Compare two models' predictions of the same rows with a paired interval
- Audit whether intervals or sets cover as often as promised, overall and by group
- Read the CRPS, its skill and a PIT histogram for predicted distributions
- Read the false-positive rate at 95% caught for an out-of-distribution score
Predictions are evidence too
ReadSometimes the model lives somewhere else: a vendor's score, a colleague's notebook, last year's forecast. All you have is a table, with one row per case, what happened, and what was predicted. The Evaluate predictions family in Analyze works from exactly that table.
One rule comes first. The predictions must be for rows the model never saw: out-of-fold or test-set predictions. Scores on training rows flatter every model, and they flatter the more flexible one most.
Two models, the same rows
PredictPredict first
Both models predicted the same 506 house prices. Compare their errors as two samples, or pair them row by row?
Reveal
Paired. Hard rows are hard for both models, so pairing removes that shared difficulty and narrows the interval.
A six-predictor model (A) against a two-predictor model (B), on out-of-fold predictions:
RMSE: A 5.05, B 5.592; A − B = -0.5414 (95% CI -0.7563 to -0.3472), p < .001 (sign-flip permutation of squared errors). Model A is better on RMSE.
- RMSE, model A
- 5.050
- RMSE, model B
- 5.592
- Difference A − B
- −0.5414
- p
- < .001
Plots
View data
| Model | high | low | Metric | RMSE |
|---|---|---|---|---|
| A: pred_a | 5.689 | 4.452 | RMSE | 5.050 |
| B: pred_b | 6.175 | 5.030 | RMSE | 5.592 |
View data
| RMSE: A − B |
|---|
| −0.6168 |
| −0.5475 |
| −0.5246 |
| −0.6838 |
| −0.3967 |
| −0.5642 |
| −0.6365 |
| −0.4658 |
| −0.4068 |
| −0.6365 |
| −0.5742 |
| −0.5878 |
| −0.6428 |
| −0.4561 |
| −0.5369 |
| −0.4827 |
| −0.5010 |
| −0.4649 |
| −0.5459 |
| −0.5748 |
| −0.4326 |
| −0.5478 |
| −0.5055 |
| −0.4027 |
| −0.5399 |
| −0.4903 |
| −0.5914 |
| −0.7070 |
| −0.4350 |
| −0.6255 |
| −0.5571 |
| −0.4862 |
| −0.4358 |
| −0.4977 |
| −0.6330 |
| −0.5601 |
| −0.5363 |
| −0.3968 |
| −0.4905 |
| −0.5941 |
| −0.5060 |
| −0.4024 |
| −0.5336 |
| −0.5897 |
| −0.5312 |
| −0.6637 |
| −0.3641 |
| −0.6738 |
| −0.5318 |
| −0.7320 |
| −0.5696 |
| −0.3673 |
| −0.5512 |
| −0.6663 |
| −0.6047 |
| −0.4344 |
| −0.5765 |
| −0.5542 |
| −0.5773 |
| −0.4679 |
First 60 of 2000 rows.
Assumptions
- Both models scored the same rows — 506 rows scored by both models. Use out-of-fold or held-out predictions: scores on the training rows flatter both models.
- Rows or clusters are independent — Rows are resampled one at a time; repeated measurements of the same unit need a cluster column.
- Enough rows — 506 rows.
RMSE of each model
| Model | Column | RMSE | 95% CI low | 95% CI high |
|---|---|---|---|---|
| A | pred_a | 5.050 | 4.452 | 5.689 |
| B | pred_b | 5.592 | 5.030 | 6.175 |
| A − B | −0.5414 | −0.7563 | −0.3472 |
Percentile intervals from 2000 paired bootstrap resamples. Lower is better.
- Bootstrap SE of the difference 0.1042. Model A does better on 58.3% of rows (ties count half).
The exact R script · R R version 4.5.1 (2025-06-13)
# Compare two models' predictions
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.paired_metric 1.0.0 · spec 887d286cb16f0390
# Dataset: evp_regress (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_eval_paired_* (paired bootstrap, sign flips), cs_delong_paired
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/evp_regress.parquet", col_select = c("medv", "pred_a", "pred_b")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("medv", "pred_a", "pred_b")]), , 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("medv", "pred_a", "pred_b")) # infinite values stop the run (registry/errors.yaml)
# %% Predictions
yc <- "medv"
ac <- "pred_a"
bc <- "pred_b"
binary <- FALSE
metric <- "auto"
if (metric == "auto") metric <- if (binary) "auc" else "rmse" # the usual yardstick for each kind of outcome
if (binary && metric %in% c("mae", "rmse", "mse", "r2")) {
cs_error("CS_E_INVALID_OPTION", option = "Metric", allowed = "AUC, Brier score, log loss or accuracy for a two-level outcome", value = metric)
}
if (!binary && metric %in% c("auc", "brier", "log_loss", "accuracy")) {
cs_error("CS_E_INVALID_OPTION", option = "Metric", allowed = "MAE, RMSE, MSE or R² for a numeric outcome", value = metric)
}
event <- NA_character_
if (binary) {
present <- levels(df[[yc]]) # levels with data, in stored order
cs_check_groups(df[[yc]], yc, minimum = 2, exactly = 2)
event <- present[length(present)] # default: the last level ("true")
y <- as.numeric(as.character(df[[yc]]) == event)
} else {
y <- as.numeric(df[[yc]])
}
pa <- as.numeric(df[[ac]])
pb <- as.numeric(df[[bc]])
n <- length(y)
cs_check_rows(n, 3, "A paired comparison")
if (metric == "r2") cs_check_not_constant(y, yc) # R2 divides by the outcome's spread
if (metric %in% c("brier", "log_loss")) {
for (cv in list(list(ac, pa), list(bc, pb))) {
bad <- sum(cv[[2]] < 0 | cv[[2]] > 1)
if (bad > 0) cs_error("CS_E_INVALID_VALUES", column = cv[[1]], requirement = "a probability between 0 and 1", count = bad)
}
}
cc <- NULL
codes <- NULL
g <- n
threshold <- 0.5
reps <- as.integer(2000)
conf <- 0.95
seed <- 42 # portable Wichmann-Hill streams: Python draws the same resamples and flips
# %% Metric
la <- cs_eval_paired_losses(metric, y, pa, threshold) # per-row loss (accuracy: 1 = correct); NULL for AUC
lb <- cs_eval_paired_losses(metric, y, pb, threshold)
yc0 <- y - mean(y) # R2 sums use the centered outcome (exact for any shift, and stable)
if (metric == "auc") {
ma <- cs_eval_auc(y, pa)
mb <- cs_eval_auc(y, pb)
} else {
ma <- cs_eval_paired_from_sums(metric, sum(la), n, sum(yc0), sum(yc0 * yc0))
mb <- cs_eval_paired_from_sums(metric, sum(lb), n, sum(yc0), sum(yc0 * yc0))
}
diff <- ma - mb
# %% Paired bootstrap
boot <- cs_eval_paired_bootstrap(metric, y, pa, pb, codes, g, reps, seed, threshold) # replicate values of A, B and A - B
valid <- !is.na(boot$diff)
reps_used <- sum(valid)
dci <- cs_eval_percentile(boot$diff, conf)
aci <- cs_eval_percentile(boot$a, conf)
bci <- cs_eval_percentile(boot$b, conf)
boot_se <- if (reps_used >= 2) stats::sd(boot$diff[valid]) else NaN
# %% Test
row_win <- NA_real_
if (metric == "auc") {
if (is.null(codes)) {
dl <- cs_delong_paired(pa[y == 1], pa[y == 0], pb[y == 1], pb[y == 0], conf)
p_value <- dl$p
p_method <- "DeLong's paired test"
} else {
p_value <- if (isTRUE(boot_se > 0)) 2 * stats::pnorm(-abs(diff / boot_se)) else NaN
p_method <- "bootstrap z test over clusters"
}
} else {
d <- la - lb
du <- if (is.null(codes)) d else as.numeric(vapply(split(d, factor(codes, levels = seq_len(g))), sum, numeric(1)))
p_value <- cs_eval_sign_flip(du, n, reps, seed + 1)$p
p_method <- paste0("sign-flip permutation", if (metric %in% c("rmse", "mse", "r2")) " of squared errors" else "",
if (!is.null(codes)) " over clusters" else "")
row_win <- cs_eval_row_win_share(metric, la, lb)
}
# %% Assumptions
lower <- cs_eval_paired_lower_is_better[[metric]]
label <- cs_eval_paired_labels[[metric]]
n_events <- if (binary) sum(y) else NA
small <- n < 30 || (!is.null(codes) && g < 10) || (metric == "auc" && min(n_events, n - n_events) < 10)
assumptions <- list(
list(key = "paired", label = "Both models scored the same rows", status = "info",
detail = sprintf("%d rows scored by both models. Use out-of-fold or held-out predictions: scores on the training rows flatter both models.", n)),
list(key = "independence", label = "Rows or clusters are independent", status = "info",
detail = if (!is.null(codes)) sprintf("Whole clusters of %s are resampled (%d clusters).", cc, g) else
"Rows are resampled one at a time; repeated measurements of the same unit need a cluster column."),
list(key = "sample_size", label = "Enough rows", status = if (small) "warn" else "pass",
detail = paste0(sprintf("%d rows", n), if (!is.null(codes)) sprintf(", %d clusters", g) else "",
if (binary) sprintf(", %d events", n_events) else "",
if (small) "; intervals are rough with this few." else "."))
)
if (reps_used < reps) warnings <- c(warnings, sprintf("%d resamples had only one outcome class (AUC undefined) and were left out.", reps - reps_used))
better <- if (is.na(diff) || diff == 0) NA_character_ else if ((diff < 0) == lower) "A" else "B"
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
values <- list(
n = n, n_clusters = if (!is.null(codes)) g else NA, metric = metric, metric_label = label,
lower_is_better = lower, positive_level = event,
metric_a = ma, metric_a_low = aci[1], metric_a_high = aci[2],
metric_b = mb, metric_b_low = bci[1], metric_b_high = bci[2],
diff = diff, diff_low = dci[1], diff_high = dci[2], boot_se = boot_se,
p_value = p_value, p_method = p_method, row_win_a = row_win, reps_used = reps_used
)
charts <- list(
cs_chart("models", "group-metrics", sprintf("%s of each model (%s bootstrap intervals)", label, pct),
list(group = cs_col("Model", c(paste0("A: ", ac), paste0("B: ", bc)), "categorical"),
metric = cs_col("Metric", c(label, label), "categorical"),
value = cs_col(label, c(ma, mb)), low = cs_col("low", c(aci[1], bci[1])), high = cs_col("high", c(aci[2], bci[2]))),
controls = list(reference = NA, band_low = 0, band_high = 0)),
cs_chart("differences", "histogram", sprintf("Bootstrap differences in %s (A − B)", label),
list(x = cs_col(sprintf("%s: A − B", label), boot$diff[valid])))
)
verdict <- if (!isTRUE(p_value < 1 - conf)) "Neither model is better at this sample size." else sprintf("Model %s is better on %s.", better, label)
summary <- sprintf("%s: A %.4g, B %.4g; A − B = %.4g (%s CI %.4g to %.4g), %s (%s). %s",
label, ma, mb, diff, pct, dci[1], dci[2], cs_fmt_p(p_value), p_method, verdict)
notes <- list(paste0(sprintf("Bootstrap SE of the difference %.4g.", boot_se),
if (!is.na(row_win)) sprintf(" Model A does better on %.1f%% of rows (ties count half).", 100 * row_win) else ""))
if (binary) notes[[length(notes) + 1]] <- sprintf("Event: %s = %s.", yc, event)
cs_publish(list(
method = "evaluate.paired_metric",
methodVersion = "1.0.0",
title = "Compare two models' predictions",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
statistics = list(
list(key = "metric_a", label = paste0(label, ", model A"), value = ma),
list(key = "metric_b", label = paste0(label, ", model B"), value = mb),
list(key = "diff", label = "Difference A − B", value = diff),
list(key = "p_value", label = "p", value = p_value, format = "p")
),
tables = list(
list(key = "comparison", title = paste0(label, " of each model"),
columns = list(list(key = "model", label = "Model", type = "string"), list(key = "column", label = "Column", type = "string"),
list(key = "value", label = label, 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 = list(
list(model = "A", column = ac, value = ma, low = aci[1], high = aci[2]),
list(model = "B", column = bc, value = mb, low = bci[1], high = bci[2]),
list(model = "A − B", column = "", value = diff, low = dci[1], high = dci[2])),
note = paste0(sprintf("Percentile intervals from %d paired bootstrap resamples", reps_used),
if (!is.null(codes)) sprintf(" of whole clusters (%s).", cc) else ".",
if (lower) " Lower is better." else " Higher is better."))
),
assumptions = assumptions,
warnings = warnings,
notes = notes,
charts = charts,
values = values
))
RMSE: A 5.05, B 5.592; A − B = -0.5414 (95% CI -0.7563 to -0.3472), p < .001 (sign-flip permutation of squared errors). Model A is better on RMSE.
- RMSE, model A
- 5.050
- RMSE, model B
- 5.592
- Difference A − B
- −0.5414
- p
- < .001
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Both models scored the same rows — 506 rows scored by both models. Use out-of-fold or held-out predictions: scores on the training rows flatter both models.
- Rows or clusters are independent — Rows are resampled one at a time; repeated measurements of the same unit need a cluster column.
- Enough rows — 506 rows.
RMSE of each model
| Model | Column | RMSE | 95% CI low | 95% CI high |
|---|---|---|---|---|
| A | pred_a | 5.050 | 4.452 | 5.689 |
| B | pred_b | 5.592 | 5.030 | 6.175 |
| A − B | −0.5414 | −0.7563 | −0.3472 |
Percentile intervals from 2000 paired bootstrap resamples. Lower is better.
- Bootstrap SE of the difference 0.1042. Model A does better on 58.3% of rows (ties count half).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Compare two models' predictions
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.paired_metric 1.0.0 · spec 887d286cb16f0390
# Dataset: evp_regress (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
from scipy import stats
import codesplash as cs
from codesplash.errors import check_groups, check_not_constant, check_rows
from codesplash.evaluate import paired as pm # paired bootstrap and sign flips (twin: codesplashr cs_eval_paired_*)
from codesplash.stats import roc # DeLong's paired AUC test (twin: cs_delong_paired)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/evp_regress.parquet", columns=["medv", "pred_a", "pred_b"])
n_input = len(df)
df = df.dropna(subset=["medv", "pred_a", "pred_b"]) # listwise deletion over the analysis columns
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, ["medv", "pred_a", "pred_b"]) # infinite values stop the run (registry/errors.yaml)
# %% Predictions
yc, ac, bc = "medv", "pred_a", "pred_b"
binary = False
metric = "auto"
if metric == "auto":
metric = "auc" if binary else "rmse" # the usual yardstick for each kind of outcome
if binary and metric in pm.NUMERIC:
cs.cs_error("CS_E_INVALID_OPTION", option="Metric", allowed="AUC, Brier score, log loss or accuracy for a two-level outcome", value=metric)
if not binary and metric in pm.BINARY:
cs.cs_error("CS_E_INVALID_OPTION", option="Metric", allowed="MAE, RMSE, MSE or R² for a numeric outcome", value=metric)
event = None
if binary:
present = [str(v) for v in df[yc].cat.categories] # levels with data, in stored order
check_groups(df[yc], yc, minimum=2, exactly=2)
event = present[-1] # default: the last level ("true")
y = (df[yc].astype(str) == event).to_numpy().astype(float)
else:
y = df[yc].to_numpy(dtype=float)
pa = df[ac].to_numpy(dtype=float)
pb = df[bc].to_numpy(dtype=float)
n = int(y.size)
check_rows(n, 3, "A paired comparison")
if metric == "r2":
check_not_constant(y, yc) # R² divides by the outcome's spread
if metric in ("brier", "log_loss"):
for c, v in ((ac, pa), (bc, pb)):
bad = int(np.sum((v < 0) | (v > 1)))
if bad:
cs.cs_error("CS_E_INVALID_VALUES", column=c, requirement="a probability between 0 and 1", count=bad)
cc, codes, g = None, None, n
threshold = 0.5
reps = int(2000)
conf = 0.95
seed = 42 # portable Wichmann–Hill streams: R draws the same resamples and flips
# %% Metric
la = pm.row_losses(metric, y, pa, threshold) # per-row loss (accuracy: 1 = correct); None for AUC
lb = pm.row_losses(metric, y, pb, threshold)
yc0 = y - y.mean() # R² sums use the centered outcome (exact for any shift, and stable)
if metric == "auc":
ma, mb = pm.auc(y, pa), pm.auc(y, pb)
else:
ma = float(pm.from_sums(metric, la.sum(), n, yc0.sum(), (yc0 * yc0).sum()))
mb = float(pm.from_sums(metric, lb.sum(), n, yc0.sum(), (yc0 * yc0).sum()))
diff = ma - mb
# %% Paired bootstrap
boot = pm.bootstrap(metric, y, pa, pb, codes, g, reps, seed, threshold) # replicate values of A, B and A − B
valid = ~np.isnan(boot["diff"])
reps_used = int(valid.sum())
diff_low, diff_high = pm.percentile(boot["diff"], conf)
a_low, a_high = pm.percentile(boot["a"], conf)
b_low, b_high = pm.percentile(boot["b"], conf)
boot_se = float(np.std(boot["diff"][valid], ddof=1)) if reps_used >= 2 else math.nan
# %% Test
if metric == "auc":
if codes is None:
dl = roc.delong_paired(pa[y == 1], pa[y == 0], pb[y == 1], pb[y == 0], conf)
p_value, p_method = dl["p"], "DeLong's paired test"
else:
z = diff / boot_se if boot_se > 0 else math.nan
p_value = float(2 * stats.norm.sf(abs(z))) if boot_se > 0 else math.nan
p_method = "bootstrap z test over clusters"
row_win = None
else:
d = la - lb
du = np.bincount(codes, weights=d, minlength=g) if codes is not None else d
p_value = pm.sign_flip(du, n, reps, seed + 1)["p"]
p_method = "sign-flip permutation" + (" of squared errors" if metric in ("rmse", "mse", "r2") else "") + (" over clusters" if codes is not None else "")
row_win = pm.row_win_share(metric, la, lb)
# %% Assumptions
lower = pm.LOWER_IS_BETTER[metric]
label = pm.LABELS[metric]
n_events = int(y.sum()) if binary else None
small = n < 30 or (codes is not None and g < 10) or (metric == "auc" and min(n_events, n - n_events) < 10)
assumptions = [
{"key": "paired", "label": "Both models scored the same rows", "status": "info",
"detail": f"{n} rows scored by both models. Use out-of-fold or held-out predictions: scores on the training rows flatter both models."},
{"key": "independence", "label": "Rows or clusters are independent", "status": "info",
"detail": (f"Whole clusters of {cc} are resampled ({g} clusters)." if codes is not None
else "Rows are resampled one at a time; repeated measurements of the same unit need a cluster column.")},
{"key": "sample_size", "label": "Enough rows", "status": "warn" if small else "pass",
"detail": (f"{n} rows" + (f", {g} clusters" if codes is not None else "") + (f", {n_events} events" if binary else "")
+ ("; intervals are rough with this few." if small else "."))},
]
if reps_used < reps:
warnings.append(f"{reps - reps_used} resamples had only one outcome class (AUC undefined) and were left out.")
better = None if diff == 0 or math.isnan(diff) else ("A" if (diff < 0) == lower else "B")
# %% Result
pct = f"{conf:.0%}"
values = {
"n": n, "n_clusters": g if codes is not None else None, "metric": metric, "metric_label": label,
"lower_is_better": lower, "positive_level": event,
"metric_a": ma, "metric_a_low": a_low, "metric_a_high": a_high,
"metric_b": mb, "metric_b_low": b_low, "metric_b_high": b_high,
"diff": diff, "diff_low": diff_low, "diff_high": diff_high, "boot_se": boot_se,
"p_value": p_value, "p_method": p_method, "row_win_a": row_win, "reps_used": reps_used,
}
charts = [
cs.chart("models", "group-metrics", f"{label} of each model ({pct} bootstrap intervals)", {
"group": cs.col("Model", [f"A: {ac}", f"B: {bc}"], "categorical"),
"metric": cs.col("Metric", [label, label], "categorical"),
"value": cs.col(label, [ma, mb]), "low": cs.col("low", [a_low, b_low]), "high": cs.col("high", [a_high, b_high])},
controls={"reference": None, "band_low": 0, "band_high": 0}),
cs.chart("differences", "histogram", f"Bootstrap differences in {label} (A − B)", {
"x": cs.col(f"{label}: A − B", boot["diff"][valid])}),
]
verdict = ("Neither model is better at this sample size." if not (p_value < 1 - conf)
else f"Model {better} is better on {label}.")
summary = (f"{label}: A {ma:.4g}, B {mb:.4g}; A − B = {diff:.4g} ({pct} CI {diff_low:.4g} to {diff_high:.4g}), "
f"{cs.fmt_p(p_value)} ({p_method}). {verdict}")
cs.publish({
"method": "evaluate.paired_metric",
"methodVersion": "1.0.0",
"title": "Compare two models' predictions",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"statistics": [
{"key": "metric_a", "label": f"{label}, model A", "value": ma},
{"key": "metric_b", "label": f"{label}, model B", "value": mb},
{"key": "diff", "label": "Difference A − B", "value": diff},
{"key": "p_value", "label": "p", "value": p_value, "format": "p"},
],
"tables": [
{"key": "comparison", "title": f"{label} of each model", "columns": [
{"key": "model", "label": "Model", "type": "string"}, {"key": "column", "label": "Column", "type": "string"},
{"key": "value", "label": label, "type": "number"},
{"key": "low", "label": f"{pct} CI low", "type": "number"}, {"key": "high", "label": f"{pct} CI high", "type": "number"}],
"rows": [
{"model": "A", "column": ac, "value": ma, "low": a_low, "high": a_high},
{"model": "B", "column": bc, "value": mb, "low": b_low, "high": b_high},
{"model": "A − B", "column": "", "value": diff, "low": diff_low, "high": diff_high}],
"note": f"Percentile intervals from {reps_used} paired bootstrap resamples" + (f" of whole clusters ({cc})." if codes is not None else ".")
+ (" Lower is better." if lower else " Higher is better.")},
],
"assumptions": assumptions,
"warnings": warnings,
"notes": [
f"Bootstrap SE of the difference {boot_se:.4g}." + (f" Model A does better on {row_win:.1%} of rows (ties count half)." if row_win is not None else ""),
*([f"Event: {yc} = {event}."] if binary else []),
],
"charts": charts,
"values": values,
})
A's RMSE minus B's is −0.541 (paired bootstrap interval −0.756 to −0.347). RMSE is a loss, so negative favors A. The p-value, 0.000500, comes from flipping the sign of each row's squared-error difference.
When rows come in groups (visits of one patient), set a cluster column so whole clusters are resampled together.
Do the intervals keep their promise?
ExploreAn 80% interval should miss about one row in five. Too few misses means the intervals are wider than they need to be. Too many means the promise is broken.
Coverage 80.2% of 506 rows (90% CI 77.2% to 83.0%) against a promised 80%; Kupiec p = .894.
- Coverage
- 0.8024
- Kupiec LR
- 0.0178
- p
- .894
Plots
View data
| Observed coverage | Promised coverage | Mean width |
|---|---|---|
| 0.8024 | 0.8000 | 10.606 |
View data
| access | high | low | Metric | Coverage |
|---|---|---|---|---|
| low access | 0.9047 | 0.8247 | Coverage | 0.8698 |
| mid access | 0.8363 | 0.7376 | Coverage | 0.7912 |
| high access | 0.7791 | 0.6515 | Coverage | 0.7197 |
View data
| Interval width |
|---|
| 10.268 |
| 10.651 |
| 10.837 |
| 10.635 |
| 10.651 |
| 10.837 |
| 10.837 |
| 10.268 |
| 10.837 |
| 10.268 |
| 10.651 |
| 10.651 |
| 10.268 |
| 10.635 |
| 10.837 |
| 10.837 |
| 10.268 |
| 10.268 |
| 10.651 |
| 10.642 |
| 10.837 |
| 10.268 |
| 10.635 |
| 10.837 |
| 10.837 |
| 10.268 |
| 10.837 |
| 10.268 |
| 10.268 |
| 10.837 |
| 10.837 |
| 10.635 |
| 10.268 |
| 10.268 |
| 10.651 |
| 10.635 |
| 10.635 |
| 10.837 |
| 10.642 |
| 10.642 |
| 10.651 |
| 10.635 |
| 10.642 |
| 10.635 |
| 10.651 |
| 10.837 |
| 10.635 |
| 10.635 |
| 10.268 |
| 10.642 |
| 10.268 |
| 10.837 |
| 10.642 |
| 10.651 |
| 10.268 |
| 10.651 |
| 10.268 |
| 10.635 |
| 10.837 |
| 10.837 |
First 60 of 506 rows.
Assumptions
- Intervals were made without these rows — Coverage is only meaningful on rows the model and its calibration never saw.
- Rows are exchangeable — Conformal coverage is an average over rows; the group table shows whether any group falls short.
- Enough expected misses — 101.2 misses expected at 80% coverage.
Coverage and width
| Measure | Value | 90% CI low | 90% CI high |
|---|---|---|---|
| Coverage | 0.8024 | 0.7717 | 0.8298 |
| Promised coverage | 0.8000 | — | — |
| Below the interval | 0.0810 | — | — |
| Above the interval | 0.1166 | — | — |
| Mean width | 10.606 | — | — |
| Median width | 10.642 | — | — |
| Winkler score (α = 0.2) | 17.655 | — | — |
Tests of the misses
| Test | LR | df | p |
|---|---|---|---|
| Kupiec: miss rate equals 1 − promised coverage | 0.0178 | 1 | 0.8937 |
| Christoffersen: misses independent in time | — | 1 | — |
| Christoffersen: conditional coverage (both) | — | 2 | — |
The Christoffersen tests need a time column and at least one miss.
Coverage by access
| access | n | Covered | Coverage | 90% CI low | 90% CI high | Mean width |
|---|---|---|---|---|---|---|
| low access | 192 | 167 | 0.8698 | 0.8247 | 0.9047 | 10.608 |
| mid access | 182 | 144 | 0.7912 | 0.7376 | 0.8363 | 10.615 |
| high access | 132 | 95 | 0.7197 | 0.6515 | 0.7791 | 10.591 |
Wilson intervals for each group's coverage.
- Group high access is covered 72.0% of the time; even the top of its interval is below the promised 80%.
- Intervals: 406 of 506 rows covered.
The exact R script · R R version 4.5.1 (2025-06-13)
# Audit prediction intervals or sets
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.conformal_audit 1.0.0 · spec 50c511a267183a20
# Dataset: evp_regress (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_eval_wilson, cs_eval_kupiec, cs_eval_christoffersen, cs_eval_parse_sets, cs_eval_winkler
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/evp_regress.parquet", col_select = c("medv", "lower80", "upper80", "access")))
n_input <- nrow(df)
df[["access"]] <- factor(df[["access"]], levels = c("low access", "mid access", "high access")) # stored level order
df <- df[stats::complete.cases(df[c("medv", "lower80", "upper80", "access")]), , 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("medv", "lower80", "upper80", "access")) # infinite values stop the run (registry/errors.yaml)
# %% Predictions
yc <- "medv"
lower_col <- "lower80"
upper_col <- "upper80"
set_col <- NULL
if (!is.null(set_col) && (!is.null(lower_col) || !is.null(upper_col))) {
cs_error("CS_E_INVALID_OPTION", option = "Prediction columns", allowed = "a lower and an upper column, or one prediction-set column", value = "both")
}
if (is.null(set_col) && (is.null(lower_col) || is.null(upper_col))) {
cs_error("CS_E_INVALID_OPTION", option = "Prediction columns", allowed = "a lower and an upper column, or one prediction-set column", value = "one bound only")
}
form <- if (!is.null(set_col)) "set" else "interval"
if (form == "interval" && FALSE) {
cs_error("CS_E_INVALID_OPTION", option = "Observed outcome", allowed = "a numeric column for intervals", value = yc)
}
n <- nrow(df)
cs_check_rows(n, 3, "A coverage audit")
nominal <- 0.8
alpha <- 1 - nominal
conf <- 0.9
if (form == "interval") {
y <- as.numeric(df[[yc]])
lo <- as.numeric(df[[lower_col]])
hi <- as.numeric(df[[upper_col]])
bad <- sum(lo > hi)
if (bad > 0) cs_error("CS_E_INVALID_VALUES", column = upper_col, requirement = "at least the lower bound", count = bad)
covered <- lo <= y & y <= hi
width <- hi - lo
size <- NULL
} else {
labels <- as.character(df[[yc]])
sets <- cs_eval_parse_sets(as.character(df[[set_col]]), "|")
covered <- mapply(function(lab, s) lab %in% s, labels, sets, USE.NAMES = FALSE)
size <- as.numeric(lengths(sets))
width <- NULL
}
# %% Coverage
k <- sum(covered)
coverage <- k / n
cw <- cs_eval_wilson(k, n, conf)
miss <- as.integer(!covered)
kp <- cs_eval_kupiec(sum(miss), n, alpha)
ch <- list(lr = NULL, p = NULL)
cc_lr <- if (!is.null(ch$lr)) kp$lr + ch$lr else NULL
cc_p <- if (!is.null(cc_lr)) stats::pchisq(cc_lr, 2, lower.tail = FALSE) else NULL
nz <- function(x) if (is.null(x)) NA else x
if (form == "interval") {
n_below <- sum(y < lo)
n_above <- sum(y > hi)
mean_width <- mean(width)
median_width <- stats::median(width)
winkler <- mean(cs_eval_winkler(y, lo, hi, alpha))
mean_size <- NA
share_empty <- NA
share_singleton <- NA
} else {
n_below <- NA
n_above <- NA
mean_width <- NA
median_width <- NA
winkler <- NA
mean_size <- mean(size)
share_empty <- mean(size == 0)
share_singleton <- mean(size == 1)
}
# %% Groups
group_rows <- list()
gc <- "access"
gv <- as.character(df[[gc]])
for (lv in levels(df[[gc]])) {
m <- gv == lv
ng <- sum(m)
kg <- sum(covered[m])
wg <- cs_eval_wilson(kg, ng, conf)
group_rows[[length(group_rows) + 1]] <- list(group = lv, n = ng, covered = kg, coverage = kg / ng, low = wg[1], high = wg[2],
size = if (form == "interval") mean(width[m]) else mean(size[m]))
}
worst <- NULL
if (length(group_rows)) worst <- group_rows[[which.min(vapply(group_rows, function(r) r$coverage, numeric(1)))]] # ties: the first group
# %% Assumptions
expected_misses <- n * alpha
assumptions <- list(
list(key = "held_out", label = "Intervals were made without these rows", status = "info",
detail = "Coverage is only meaningful on rows the model and its calibration never saw."),
list(key = "exchangeable", label = "Rows are exchangeable", status = "info",
detail = paste0("Conformal coverage is an average over rows; ",
if (length(group_rows)) "the group table shows whether any group falls short." else "add a group column to check groups.")),
list(key = "enough_misses", label = "Enough expected misses", status = if (expected_misses >= 10) "pass" else "warn",
detail = paste0(sprintf("%.1f misses expected at %.0f%% coverage", expected_misses, 100 * nominal),
if (expected_misses >= 10) "." else "; the tests have little power with fewer than 10."))
)
if (!is.null(worst) && worst$high < nominal) {
warnings <- c(warnings, sprintf("Group %s is covered %.1f%% of the time; even the top of its interval is below the promised %.0f%%.",
worst$group, 100 * worst$coverage, 100 * nominal))
}
if (cw[2] < nominal) warnings <- c(warnings, sprintf("Coverage %.1f%% is below the promised %.0f%%, beyond chance at this sample size.", 100 * coverage, 100 * nominal))
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
values <- list(
n = n, form = form, nominal = nominal, covered = k, coverage = coverage, coverage_low = cw[1], coverage_high = cw[2],
n_below = n_below, n_above = n_above, mean_width = mean_width, median_width = median_width, winkler = winkler,
mean_size = mean_size, share_empty = share_empty, share_singleton = share_singleton,
kupiec_lr = kp$lr, kupiec_p = kp$p, christoffersen_lr = nz(ch$lr), christoffersen_p = nz(ch$p), cc_lr = nz(cc_lr), cc_p = nz(cc_p),
n_groups = if (length(group_rows)) length(group_rows) else NA,
worst_group = if (!is.null(worst)) worst$group else NA, worst_group_coverage = if (!is.null(worst)) worst$coverage else NA,
worst_group_low = if (!is.null(worst)) worst$low else NA, worst_group_high = if (!is.null(worst)) worst$high else NA
)
cov_roles <- list(nominal = cs_col("Promised coverage", nominal), coverage = cs_col("Observed coverage", coverage))
if (form == "interval") cov_roles$width <- cs_col("Mean width", mean_width)
charts <- list(cs_chart("coverage", "interval-coverage", "Promised vs observed coverage", cov_roles))
if (length(group_rows)) {
gr <- function(k) vapply(group_rows, function(r) r[[k]], numeric(1))
charts[[length(charts) + 1]] <- cs_chart("groups", "group-metrics", sprintf("Coverage by %s (%s Wilson intervals)", gc, pct),
list(group = cs_col(gc, vapply(group_rows, function(r) r$group, character(1)), "categorical"),
metric = cs_col("Metric", rep("Coverage", length(group_rows)), "categorical"),
value = cs_col("Coverage", gr("coverage")), low = cs_col("low", gr("low")), high = cs_col("high", gr("high"))),
controls = list(reference = nominal, band_low = 0, band_high = 0))
}
if (form == "interval") {
charts[[length(charts) + 1]] <- cs_chart("widths", "histogram", "Interval widths", list(x = cs_col("Interval width", width)))
} else {
sizes <- sort(unique(as.integer(size)))
charts[[length(charts) + 1]] <- cs_chart("sizes", "bar", "Prediction-set sizes",
list(x = cs_col("Labels in the set", as.character(as.integer(size)), "categorical", as.character(sizes))))
}
tables <- list()
measures <- list(
list(measure = "Coverage", value = coverage, low = cw[1], high = cw[2]),
list(measure = "Promised coverage", value = nominal, low = NA, high = NA)
)
if (form == "interval") {
measures <- c(measures, list(
list(measure = "Below the interval", value = n_below / n, low = NA, high = NA),
list(measure = "Above the interval", value = n_above / n, low = NA, high = NA),
list(measure = "Mean width", value = mean_width, low = NA, high = NA),
list(measure = "Median width", value = median_width, low = NA, high = NA),
list(measure = sprintf("Winkler score (α = %g)", alpha), value = winkler, low = NA, high = NA)))
} else {
measures <- c(measures, list(
list(measure = "Mean set size", value = mean_size, low = NA, high = NA),
list(measure = "Empty sets", value = share_empty, low = NA, high = NA),
list(measure = "Single-label sets", value = share_singleton, low = NA, high = NA)))
}
tables[[1]] <- list(key = "measures", title = paste0("Coverage and ", if (form == "interval") "width" else "set size"),
columns = list(list(key = "measure", label = "Measure", type = "string"), list(key = "value", label = "Value", 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 = measures)
tables[[2]] <- list(key = "tests", title = "Tests of the misses",
columns = list(list(key = "test", label = "Test", type = "string"), list(key = "lr", label = "LR", type = "number"),
list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p", type = "number")),
rows = list(
list(test = "Kupiec: miss rate equals 1 − promised coverage", lr = kp$lr, df = 1, p = kp$p),
list(test = "Christoffersen: misses independent in time", lr = nz(ch$lr), df = 1, p = nz(ch$p)),
list(test = "Christoffersen: conditional coverage (both)", lr = nz(cc_lr), df = 2, p = nz(cc_p))),
note = if (is.null(ch$lr)) "The Christoffersen tests need a time column and at least one miss." else NA)
if (length(group_rows)) {
tables[[3]] <- list(key = "groups", title = sprintf("Coverage by %s", gc),
columns = list(list(key = "group", label = gc, type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "covered", label = "Covered", type = "integer"), list(key = "coverage", label = "Coverage", 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 = "size", label = if (form == "interval") "Mean width" else "Mean set size", type = "number")),
rows = group_rows, note = "Wilson intervals for each group's coverage.")
}
summary <- sprintf("Coverage %.1f%% of %d rows (%s CI %.1f%% to %.1f%%) against a promised %.0f%%; Kupiec %s.",
100 * coverage, n, pct, 100 * cw[1], 100 * cw[2], 100 * nominal, cs_fmt_p(kp$p))
cs_publish(list(
method = "evaluate.conformal_audit",
methodVersion = "1.0.0",
title = "Audit prediction intervals or sets",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
statistics = list(
list(key = "coverage", label = "Coverage", value = coverage),
list(key = "kupiec_lr", label = "Kupiec LR", value = kp$lr),
list(key = "kupiec_p", label = "p", value = kp$p, format = "p")
),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("%s: %d of %d rows covered.", if (form == "interval") "Intervals" else "Prediction sets", k, n)),
charts = charts,
values = values
))
Coverage 80.2% of 506 rows (90% CI 77.2% to 83.0%) against a promised 80%; Kupiec p = .894.
- Coverage
- 0.8024
- Kupiec LR
- 0.0178
- p
- .894
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Intervals were made without these rows — Coverage is only meaningful on rows the model and its calibration never saw.
- Rows are exchangeable — Conformal coverage is an average over rows; the group table shows whether any group falls short.
- Enough expected misses — 101.2 misses expected at 80% coverage.
Coverage and width
| Measure | Value | 90% CI low | 90% CI high |
|---|---|---|---|
| Coverage | 0.8024 | 0.7717 | 0.8298 |
| Promised coverage | 0.8000 | — | — |
| Below the interval | 0.0810 | — | — |
| Above the interval | 0.1166 | — | — |
| Mean width | 10.606 | — | — |
| Median width | 10.642 | — | — |
| Winkler score (α = 0.2) | 17.655 | — | — |
Tests of the misses
| Test | LR | df | p |
|---|---|---|---|
| Kupiec: miss rate equals 1 − promised coverage | 0.0178 | 1 | 0.8937 |
| Christoffersen: misses independent in time | — | 1 | — |
| Christoffersen: conditional coverage (both) | — | 2 | — |
The Christoffersen tests need a time column and at least one miss.
Coverage by access
| access | n | Covered | Coverage | 90% CI low | 90% CI high | Mean width |
|---|---|---|---|---|---|---|
| low access | 192 | 167 | 0.8698 | 0.8247 | 0.9047 | 10.608 |
| mid access | 182 | 144 | 0.7912 | 0.7376 | 0.8363 | 10.615 |
| high access | 132 | 95 | 0.7197 | 0.6515 | 0.7791 | 10.591 |
Wilson intervals for each group's coverage.
- Group high access is covered 72.0% of the time; even the top of its interval is below the promised 80%.
- Intervals: 406 of 506 rows covered.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Audit prediction intervals or sets
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.conformal_audit 1.0.0 · spec 50c511a267183a20
# Dataset: evp_regress (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
from scipy import stats
import codesplash as cs
from codesplash.errors import check_rows
from codesplash.evaluate import coverage as cov # Wilson, Kupiec, Christoffersen, sets (twin: codesplashr cs_eval_*)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/evp_regress.parquet", columns=["medv", "lower80", "upper80", "access"])
n_input = len(df)
df["access"] = pd.Categorical(df["access"], categories=["low access", "mid access", "high access"]) # stored level order
df = df.dropna(subset=["medv", "lower80", "upper80", "access"]) # listwise deletion over the analysis columns
df["access"] = df["access"].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, ["medv", "lower80", "upper80", "access"]) # infinite values stop the run (registry/errors.yaml)
# %% Predictions
yc = "medv"
lower_col = "lower80"
upper_col = "upper80"
set_col = None
if set_col is not None and (lower_col is not None or upper_col is not None):
cs.cs_error("CS_E_INVALID_OPTION", option="Prediction columns", allowed="a lower and an upper column, or one prediction-set column", value="both")
if set_col is None and (lower_col is None or upper_col is None):
cs.cs_error("CS_E_INVALID_OPTION", option="Prediction columns", allowed="a lower and an upper column, or one prediction-set column", value="one bound only")
form = "set" if set_col is not None else "interval"
if form == "interval" and False:
cs.cs_error("CS_E_INVALID_OPTION", option="Observed outcome", allowed="a numeric column for intervals", value=yc)
n = len(df)
check_rows(n, 3, "A coverage audit")
nominal = 0.8
alpha = 1 - nominal
conf = 0.9
if form == "interval":
y = df[yc].to_numpy(dtype=float)
lo = df[lower_col].to_numpy(dtype=float)
hi = df[upper_col].to_numpy(dtype=float)
bad = int(np.sum(lo > hi))
if bad:
cs.cs_error("CS_E_INVALID_VALUES", column=upper_col, requirement="at least the lower bound", count=bad)
covered = (lo <= y) & (y <= hi)
width = hi - lo
size = None
else:
labels = df[yc].astype(str).tolist()
sets = cov.parse_sets(df[set_col].astype(str).tolist(), "|")
covered = np.array([lab in s for lab, s in zip(labels, sets)], dtype=bool)
size = np.array([len(s) for s in sets], dtype=float)
width = None
# %% Coverage
k = int(covered.sum())
coverage = k / n
cov_low, cov_high = cov.wilson(k, n, conf)
miss = (~covered).astype(np.int64)
kp = cov.kupiec(int(miss.sum()), n, alpha)
ch = {"lr": None, "p": None}
cc_lr = kp["lr"] + ch["lr"] if ch["lr"] is not None else None
cc_p = float(stats.chi2.sf(cc_lr, 2)) if cc_lr is not None else None
if form == "interval":
n_below, n_above = int(np.sum(y < lo)), int(np.sum(y > hi))
mean_width, median_width = float(width.mean()), float(np.median(width))
winkler = float(cov.winkler(y, lo, hi, alpha).mean())
mean_size = share_empty = share_singleton = None
else:
n_below = n_above = mean_width = median_width = winkler = None
mean_size = float(size.mean())
share_empty, share_singleton = float(np.mean(size == 0)), float(np.mean(size == 1))
# %% Groups
group_rows = []
gc = "access"
gv = df[gc].astype(str).to_numpy()
for lv in [str(x) for x in df[gc].cat.categories]:
m = gv == lv
ng, kg = int(m.sum()), int(covered[m].sum())
lw, hg = cov.wilson(kg, ng, conf)
group_rows.append({"group": lv, "n": ng, "covered": kg, "coverage": kg / ng, "low": lw, "high": hg,
"size": float(width[m].mean()) if form == "interval" else float(size[m].mean())})
worst = min(group_rows, key=lambda r: r["coverage"]) if group_rows else None # ties: the first group
# %% Assumptions
expected_misses = n * alpha
assumptions = [
{"key": "held_out", "label": "Intervals were made without these rows", "status": "info",
"detail": "Coverage is only meaningful on rows the model and its calibration never saw."},
{"key": "exchangeable", "label": "Rows are exchangeable", "status": "info",
"detail": "Conformal coverage is an average over rows; " + ("the group table shows whether any group falls short." if group_rows else "add a group column to check groups.")},
{"key": "enough_misses", "label": "Enough expected misses", "status": "pass" if expected_misses >= 10 else "warn",
"detail": f"{expected_misses:.1f} misses expected at {nominal:.0%} coverage" + ("." if expected_misses >= 10 else "; the tests have little power with fewer than 10.")},
]
if worst is not None and worst["high"] < nominal:
warnings.append(f"Group {worst['group']} is covered {worst['coverage']:.1%} of the time; even the top of its interval is below the promised {nominal:.0%}.")
if cov_high < nominal:
warnings.append(f"Coverage {coverage:.1%} is below the promised {nominal:.0%}, beyond chance at this sample size.")
# %% Result
pct = f"{conf:.0%}"
values = {
"n": n, "form": form, "nominal": nominal, "covered": k, "coverage": coverage, "coverage_low": cov_low, "coverage_high": cov_high,
"n_below": n_below, "n_above": n_above, "mean_width": mean_width, "median_width": median_width, "winkler": winkler,
"mean_size": mean_size, "share_empty": share_empty, "share_singleton": share_singleton,
"kupiec_lr": kp["lr"], "kupiec_p": kp["p"], "christoffersen_lr": ch["lr"], "christoffersen_p": ch["p"], "cc_lr": cc_lr, "cc_p": cc_p,
"n_groups": len(group_rows) if group_rows else None, "worst_group": worst["group"] if worst else None,
"worst_group_coverage": worst["coverage"] if worst else None, "worst_group_low": worst["low"] if worst else None,
"worst_group_high": worst["high"] if worst else None,
}
charts = [
cs.chart("coverage", "interval-coverage", "Promised vs observed coverage", {
"nominal": cs.col("Promised coverage", [nominal]), "coverage": cs.col("Observed coverage", [coverage]),
"width": cs.col("Mean width", [mean_width]) if form == "interval" else None}),
]
if group_rows:
charts.append(cs.chart("groups", "group-metrics", f"Coverage by {gc} ({pct} Wilson intervals)", {
"group": cs.col(gc, [r["group"] for r in group_rows], "categorical"),
"metric": cs.col("Metric", ["Coverage"] * len(group_rows), "categorical"),
"value": cs.col("Coverage", [r["coverage"] for r in group_rows]),
"low": cs.col("low", [r["low"] for r in group_rows]), "high": cs.col("high", [r["high"] for r in group_rows])},
controls={"reference": nominal, "band_low": 0, "band_high": 0}))
if form == "interval":
charts.append(cs.chart("widths", "histogram", "Interval widths", {"x": cs.col("Interval width", width)}))
else:
sizes = sorted(set(int(s) for s in size))
charts.append(cs.chart("sizes", "bar", "Prediction-set sizes", {
"x": cs.col("Labels in the set", [str(int(s)) for s in size], "categorical", [str(s) for s in sizes])}))
group_table = []
if group_rows:
group_table = [{"key": "groups", "title": f"Coverage by {gc}", "columns": [
{"key": "group", "label": gc, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "covered", "label": "Covered", "type": "integer"}, {"key": "coverage", "label": "Coverage", "type": "number"},
{"key": "low", "label": f"{pct} CI low", "type": "number"}, {"key": "high", "label": f"{pct} CI high", "type": "number"},
{"key": "size", "label": "Mean width" if form == "interval" else "Mean set size", "type": "number"}],
"rows": group_rows, "note": "Wilson intervals for each group's coverage."}]
measures = [
{"measure": "Coverage", "value": coverage, "low": cov_low, "high": cov_high},
{"measure": "Promised coverage", "value": nominal, "low": None, "high": None},
]
if form == "interval":
measures += [
{"measure": "Below the interval", "value": n_below / n, "low": None, "high": None},
{"measure": "Above the interval", "value": n_above / n, "low": None, "high": None},
{"measure": "Mean width", "value": mean_width, "low": None, "high": None},
{"measure": "Median width", "value": median_width, "low": None, "high": None},
{"measure": f"Winkler score (α = {alpha:g})", "value": winkler, "low": None, "high": None},
]
else:
measures += [
{"measure": "Mean set size", "value": mean_size, "low": None, "high": None},
{"measure": "Empty sets", "value": share_empty, "low": None, "high": None},
{"measure": "Single-label sets", "value": share_singleton, "low": None, "high": None},
]
summary = (f"Coverage {coverage:.1%} of {n} rows ({pct} CI {cov_low:.1%} to {cov_high:.1%}) against a promised {nominal:.0%}; "
f"Kupiec {cs.fmt_p(kp['p'])}.")
cs.publish({
"method": "evaluate.conformal_audit",
"methodVersion": "1.0.0",
"title": "Audit prediction intervals or sets",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"statistics": [
{"key": "coverage", "label": "Coverage", "value": coverage},
{"key": "kupiec_lr", "label": "Kupiec LR", "value": kp["lr"]},
{"key": "kupiec_p", "label": "p", "value": kp["p"], "format": "p"},
],
"tables": [
{"key": "measures", "title": "Coverage and " + ("width" if form == "interval" else "set size"), "columns": [
{"key": "measure", "label": "Measure", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
{"key": "low", "label": f"{pct} CI low", "type": "number"}, {"key": "high", "label": f"{pct} CI high", "type": "number"}],
"rows": measures},
{"key": "tests", "title": "Tests of the misses", "columns": [
{"key": "test", "label": "Test", "type": "string"}, {"key": "lr", "label": "LR", "type": "number"},
{"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p", "type": "number"}],
"rows": [
{"test": "Kupiec: miss rate equals 1 − promised coverage", "lr": kp["lr"], "df": 1, "p": kp["p"]},
{"test": "Christoffersen: misses independent in time", "lr": ch["lr"], "df": 1, "p": ch["p"]},
{"test": "Christoffersen: conditional coverage (both)", "lr": cc_lr, "df": 2, "p": cc_p}],
"note": "The Christoffersen tests need a time column and at least one miss." if ch["lr"] is None else None},
*group_table,
],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"{'Intervals' if form == 'interval' else 'Prediction sets'}: {k} of {n} rows covered."],
"charts": charts,
"values": values,
})
Overall coverage is 0.802. Kupiec's test of the miss rate gives 0.894. Now read the group table. Conformal intervals promise coverage on average over rows. The least-covered group, high access, is covered 0.720 of the time.
The same audit works for prediction sets from a classifier. Coverage is how often the set holds the true label, and the sizes show what that costs: a set holding every label is always right, and never useful.
Scoring a whole distribution
PredictA predicted mean with an SD is a full distribution. The CRPS compares it with what happened, in the outcome's own units, so a point forecast and a distribution can be scored on one scale. Lower is better.
506 predictive distributions (normal); PIT uniformity χ²(9) = 72.06, p < .001; CRPS 2.638 (skill 47.2%).
- CRPS
- 2.638
- Log score
- 3.046
- PIT χ²
- 72.063
- p
- < .001
Plots
View data
| Share of rows |
|---|
| 0.0415 |
| 0.1146 |
| 0.1324 |
| 0.1522 |
| 0.1462 |
| 0.1206 |
| 0.0929 |
| 0.0455 |
| 0.0672 |
| 0.0870 |
View data
| Observed coverage | Promised coverage | Mean width |
|---|---|---|
| 0.6047 | 0.5000 | 6.752 |
| 0.8715 | 0.8000 | 12.830 |
| 0.9209 | 0.9000 | 16.467 |
| 0.9506 | 0.9500 | 19.622 |
Assumptions
- Predictions were made without these rows — Use out-of-fold or test-set predictions: scores on the fitted rows are too good.
- Enough rows per PIT bin — The smallest expected count is 50.6.
Scores
| Score | Value | Reference forecast |
|---|---|---|
| CRPS (exact, normal) | 2.638 | 4.998 |
| CRPS skill (1 − CRPS / reference) | 0.4723 | — |
| Log score (negative log-likelihood) | 3.046 | — |
| Mean predicted SD (sharpness) | 5.006 | — |
The reference forecast is one normal for every row, with the outcome's mean and SD. Lower CRPS and log score are better.
Central intervals
| Promised | Covered | Coverage | 95% CI low | 95% CI high | Mean width |
|---|---|---|---|---|---|
| 0.5000 | 306 | 0.6047 | 0.5615 | 0.6464 | 6.752 |
| 0.8000 | 441 | 0.8715 | 0.8396 | 0.8979 | 12.830 |
| 0.9000 | 466 | 0.9209 | 0.8941 | 0.9414 | 16.467 |
| 0.9500 | 481 | 0.9506 | 0.9281 | 0.9663 | 19.622 |
Wilson intervals for each coverage share.
- PIT categories tested against their expected shares with χ²(9).
The exact R script · R R version 4.5.1 (2025-06-13)
# Score probabilistic predictions
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.probabilistic 1.0.0 · spec b3574198e5795f82
# Dataset: evp_regress (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_eval_crps_normal, cs_eval_nll_normal, cs_eval_pit_bins, cs_eval_pinball, cs_eval_wis, cs_eval_wilson
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/evp_regress.parquet", col_select = c("medv", "pred_a", "sd_a")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("medv", "pred_a", "sd_a")]), , 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("medv", "pred_a", "sd_a")) # infinite values stop the run (registry/errors.yaml)
# %% Predictions
yc <- "medv"
mean_col <- "pred_a"
sd_col <- "sd_a"
q_cols <- c()
allowed <- "a mean and an SD column, or quantile columns"
if (length(q_cols) && (!is.null(mean_col) || !is.null(sd_col))) {
cs_error("CS_E_INVALID_OPTION", option = "Prediction columns", allowed = allowed, value = "both")
}
if (!length(q_cols) && (is.null(mean_col) || is.null(sd_col))) {
cs_error("CS_E_INVALID_OPTION", option = "Prediction columns", allowed = allowed, value = "a mean or an SD alone")
}
form <- if (length(q_cols)) "quantile" else "normal"
y <- as.numeric(df[[yc]])
n <- length(y)
cs_check_rows(n, 3, "Scoring predictive distributions")
conf <- 0.95
bins <- as.integer(10)
nll <- crps <- crps_ref <- crps_skill <- mean_sd <- mean_pinball <- wis <- NA_real_
cov90 <- c(NA_real_, NA_real_, NA_real_)
n_crossing <- NA
n_levels <- NA
coverage_rows <- list()
reliability_rows <- list()
if (form == "normal") {
mu <- as.numeric(df[[mean_col]])
sd <- as.numeric(df[[sd_col]])
bad <- sum(sd <= 0)
if (bad > 0) cs_error("CS_E_INVALID_VALUES", column = sd_col, requirement = "a standard deviation above zero", count = bad)
} else {
levels_text <- "0.05, 0.25, 0.5, 0.75, 0.95"
taus <- cs_eval_parse_levels(levels_text)
if (length(taus) != length(q_cols) || any(!(taus > 0 & taus < 1)) || anyDuplicated(taus) > 0) {
cs_error("CS_E_INVALID_OPTION", option = "Quantile levels",
allowed = sprintf("%d different levels between 0 and 1, one per quantile column", length(q_cols)), value = levels_text)
}
ord <- order(taus, method = "radix") # columns sorted by level
taus <- taus[ord]
q <- do.call(cbind, lapply(q_cols[ord], function(cn) as.numeric(df[[cn]])))
n_levels <- length(taus)
}
# %% Scores
if (form == "normal") {
z <- (y - mu) / sd
nll <- mean(cs_eval_nll_normal(y, mu, sd))
crps <- mean(cs_eval_crps_normal(y, mu, sd))
ybar <- mean(y)
sy <- stats::sd(y)
if (sy > 0) {
crps_ref <- mean(cs_eval_crps_normal(y, ybar, sy)) # one normal for every row: the outcome's mean and SD
crps_skill <- 1 - crps / crps_ref
}
mean_sd <- mean(sd)
pit <- stats::pnorm(z)
counts <- cs_eval_pit_bins(pit, bins)
expected <- rep(1 / bins, bins)
for (lev in c(0.5, 0.8, 0.9, 0.95)) {
zq <- stats::qnorm((1 + lev) / 2)
kc <- sum(abs(z) <= zq)
w <- cs_eval_wilson(kc, n, conf)
coverage_rows[[length(coverage_rows) + 1]] <- list(level = lev, covered = kc, coverage = kc / n, low = w[1], high = w[2], width = mean(2 * zq * sd))
}
} else {
n_crossing <- if (n_levels > 1) sum(apply(q[, -n_levels, drop = FALSE] > q[, -1, drop = FALSE], 1, any)) else 0L
losses <- vapply(seq_len(n_levels), function(k) mean(cs_eval_pinball(y, q[, k], taus[k])), numeric(1))
mean_pinball <- mean(losses)
pairs <- cs_eval_central_pairs(taus)
if (length(pairs)) wis <- mean(cs_eval_wis(y, q, taus))
cat <- rowSums(q < y) # number of quantiles strictly below the outcome
counts <- tabulate(cat + 1, nbins = n_levels + 1)
expected <- diff(c(0, taus, 1))
for (pr in pairs) {
kc <- sum(q[, pr[1]] <= y & y <= q[, pr[2]])
w <- cs_eval_wilson(kc, n, conf)
coverage_rows[[length(coverage_rows) + 1]] <- list(level = 1 - 2 * taus[pr[1]], covered = kc, coverage = kc / n, low = w[1], high = w[2],
width = mean(q[, pr[2]] - q[, pr[1]]))
}
for (k in seq_len(n_levels)) {
kb <- sum(y <= q[, k])
w <- cs_eval_wilson(kb, n, conf)
reliability_rows[[length(reliability_rows) + 1]] <- list(level = taus[k], below = kb, share = kb / n, low = w[1], high = w[2], pinball = losses[k])
}
}
test <- cs_eval_chisq(counts, expected)
for (r in coverage_rows) if (abs(r$level - 0.9) < 1e-9) cov90 <- c(r$coverage, r$low, r$high)
# %% Assumptions
min_expected <- min(expected * n)
assumptions <- list(
list(key = "held_out", label = "Predictions were made without these rows", status = "info",
detail = "Use out-of-fold or test-set predictions: scores on the fitted rows are too good."),
list(key = "pit_bins", label = "Enough rows per PIT bin", status = if (min_expected >= 5) "pass" else "warn",
detail = paste0(sprintf("The smallest expected count is %.1f", min_expected),
if (min_expected >= 5) "." else "; the χ² test is rough below 5 — use fewer bins."))
)
if (form == "quantile") {
assumptions[[3]] <- list(key = "quantiles_ordered", label = "Quantiles do not cross", status = if (n_crossing == 0) "pass" else "warn",
detail = if (n_crossing == 0) "No row has a higher level with a lower quantile." else
sprintf("%d row(s) have crossing quantiles; they are scored as given.", n_crossing))
}
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
values <- list(
n = n, form = form, n_levels = n_levels, nll = nll, crps = crps, crps_ref = crps_ref, crps_skill = crps_skill,
mean_sd = mean_sd, mean_pinball = mean_pinball, wis = wis,
pit_chi2 = test$chi2, pit_df = test$df, pit_p = test$p,
coverage_90 = cov90[1], coverage_90_low = cov90[2], coverage_90_high = cov90[3], n_crossing = n_crossing
)
rv <- function(rows, k) vapply(rows, function(r) as.numeric(r[[k]]), numeric(1))
charts <- list()
if (form == "normal") {
charts[[length(charts) + 1]] <- cs_chart("pit", "pit-histogram", sprintf("PIT histogram (%d bins)", bins), list(share = cs_col("Share of rows", counts / n)))
}
if (length(coverage_rows)) {
charts[[length(charts) + 1]] <- cs_chart("coverage", "interval-coverage", "Central intervals: promised vs observed coverage",
list(nominal = cs_col("Promised coverage", rv(coverage_rows, "level")), coverage = cs_col("Observed coverage", rv(coverage_rows, "coverage")),
width = cs_col("Mean width", rv(coverage_rows, "width"))))
}
if (length(reliability_rows)) {
charts[[length(charts) + 1]] <- cs_chart("quantiles", "calibration", "How often the outcome falls below each quantile",
list(predicted = cs_col("Quantile level", rv(reliability_rows, "level")), observed = cs_col("Share of outcomes at or below", rv(reliability_rows, "share")),
n = cs_col("n", rep(n, length(reliability_rows))), low = cs_col("low", rv(reliability_rows, "low")), high = cs_col("high", rv(reliability_rows, "high"))))
}
tables <- list()
if (form == "normal") {
tables[[1]] <- list(key = "scores", title = "Scores",
columns = list(list(key = "score", label = "Score", type = "string"), list(key = "value", label = "Value", type = "number"),
list(key = "reference", label = "Reference forecast", type = "number")),
rows = list(
list(score = "CRPS (exact, normal)", value = crps, reference = crps_ref),
list(score = "CRPS skill (1 − CRPS / reference)", value = crps_skill, reference = NA),
list(score = "Log score (negative log-likelihood)", value = nll, reference = NA),
list(score = "Mean predicted SD (sharpness)", value = mean_sd, reference = NA)),
note = "The reference forecast is one normal for every row, with the outcome's mean and SD. Lower CRPS and log score are better.")
} else {
tables[[1]] <- list(key = "scores", title = "Scores",
columns = list(list(key = "score", label = "Score", type = "string"), list(key = "value", label = "Value", type = "number")),
rows = list(
list(score = "Mean pinball loss", value = mean_pinball),
list(score = "Weighted interval score", value = wis),
list(score = "Rows with crossing quantiles", value = as.numeric(n_crossing))),
note = "Lower is better. The weighted interval score needs pairs of levels that add up to 1 (such as 0.05 and 0.95).")
tables[[2]] <- list(key = "quantiles", title = "Each quantile",
columns = list(list(key = "level", label = "Level", type = "number"), list(key = "below", label = "Outcomes at or below", type = "integer"),
list(key = "share", label = "Share", 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 = "pinball", label = "Pinball loss", type = "number")),
rows = reliability_rows, note = "A calibrated quantile at level τ has about τ of the outcomes at or below it.")
}
if (length(coverage_rows)) {
tables[[length(tables) + 1]] <- list(key = "coverage", title = "Central intervals",
columns = list(list(key = "level", label = "Promised", type = "number"), list(key = "covered", label = "Covered", type = "integer"),
list(key = "coverage", label = "Coverage", 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 = "width", label = "Mean width", type = "number")),
rows = coverage_rows, note = "Wilson intervals for each coverage share.")
}
summary <- paste0(sprintf("%d predictive distributions (%s); PIT uniformity χ²(%d) = %.2f, %s", n, form, test$df, test$chi2, cs_fmt_p(test$p)),
if (form == "normal" && !is.na(crps_skill)) sprintf("; CRPS %.4g (skill %.1f%%).", crps, 100 * crps_skill) else
if (form == "normal") sprintf("; CRPS %.4g.", crps) else sprintf("; mean pinball loss %.4g.", mean_pinball))
stats_rows <- if (form == "normal") list(list(key = "crps", label = "CRPS", value = crps), list(key = "nll", label = "Log score", value = nll)) else
list(list(key = "mean_pinball", label = "Mean pinball loss", value = mean_pinball), list(key = "wis", label = "Weighted interval score", value = wis))
cs_publish(list(
method = "evaluate.probabilistic",
methodVersion = "1.0.0",
title = "Score probabilistic predictions",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
statistics = c(stats_rows, list(
list(key = "pit_chi2", label = "PIT χ²", value = test$chi2),
list(key = "pit_p", label = "p", value = test$p, format = "p")
)),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("PIT categories tested against their expected shares with χ²(%d).", test$df)),
charts = charts,
values = values
))
506 predictive distributions (normal); PIT uniformity χ²(9) = 72.06, p < .001; CRPS 2.638 (skill 47.2%).
- CRPS
- 2.638
- Log score
- 3.046
- PIT χ²
- 72.063
- p
- < .001
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Predictions were made without these rows — Use out-of-fold or test-set predictions: scores on the fitted rows are too good.
- Enough rows per PIT bin — The smallest expected count is 50.6.
Scores
| Score | Value | Reference forecast |
|---|---|---|
| CRPS (exact, normal) | 2.638 | 4.998 |
| CRPS skill (1 − CRPS / reference) | 0.4723 | — |
| Log score (negative log-likelihood) | 3.046 | — |
| Mean predicted SD (sharpness) | 5.006 | — |
The reference forecast is one normal for every row, with the outcome's mean and SD. Lower CRPS and log score are better.
Central intervals
| Promised | Covered | Coverage | 95% CI low | 95% CI high | Mean width |
|---|---|---|---|---|---|
| 0.5000 | 306 | 0.6047 | 0.5615 | 0.6464 | 6.752 |
| 0.8000 | 441 | 0.8715 | 0.8396 | 0.8979 | 12.830 |
| 0.9000 | 466 | 0.9209 | 0.8941 | 0.9414 | 16.467 |
| 0.9500 | 481 | 0.9506 | 0.9281 | 0.9663 | 19.622 |
Wilson intervals for each coverage share.
- PIT categories tested against their expected shares with χ²(9).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Score probabilistic predictions
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.probabilistic 1.0.0 · spec b3574198e5795f82
# Dataset: evp_regress (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
from scipy import stats
import codesplash as cs
from codesplash.errors import check_rows
from codesplash.evaluate import coverage as cov # Wilson intervals (twin: cs_eval_wilson)
from codesplash.evaluate import scores as sc # CRPS, log score, PIT, pinball, WIS (twin: codesplashr cs_eval_*)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/evp_regress.parquet", columns=["medv", "pred_a", "sd_a"])
n_input = len(df)
df = df.dropna(subset=["medv", "pred_a", "sd_a"]) # listwise deletion over the analysis columns
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, ["medv", "pred_a", "sd_a"]) # infinite values stop the run (registry/errors.yaml)
# %% Predictions
yc = "medv"
mean_col = "pred_a"
sd_col = "sd_a"
q_cols = []
allowed = "a mean and an SD column, or quantile columns"
if q_cols and (mean_col is not None or sd_col is not None):
cs.cs_error("CS_E_INVALID_OPTION", option="Prediction columns", allowed=allowed, value="both")
if not q_cols and (mean_col is None or sd_col is None):
cs.cs_error("CS_E_INVALID_OPTION", option="Prediction columns", allowed=allowed, value="a mean or an SD alone")
form = "quantile" if q_cols else "normal"
y = df[yc].to_numpy(dtype=float)
n = int(y.size)
check_rows(n, 3, "Scoring predictive distributions")
conf = 0.95
bins = int(10)
nll = crps = crps_ref = crps_skill = mean_sd = mean_pinball = wis = None
cov90 = (None, None, None)
n_crossing = None
coverage_rows, reliability_rows = [], []
if form == "normal":
mu = df[mean_col].to_numpy(dtype=float)
sd = df[sd_col].to_numpy(dtype=float)
bad = int(np.sum(sd <= 0))
if bad:
cs.cs_error("CS_E_INVALID_VALUES", column=sd_col, requirement="a standard deviation above zero", count=bad)
n_levels = None
else:
taus = sc.parse_levels("0.05, 0.25, 0.5, 0.75, 0.95")
if len(taus) != len(q_cols) or any(not (0 < t < 1) for t in taus) or len(set(taus)) != len(taus):
cs.cs_error("CS_E_INVALID_OPTION", option="Quantile levels",
allowed=f"{len(q_cols)} different levels between 0 and 1, one per quantile column", value="0.05, 0.25, 0.5, 0.75, 0.95")
order = np.argsort(np.asarray(taus), kind="stable") # columns sorted by level
taus = [taus[i] for i in order]
q = np.column_stack([df[q_cols[i]].to_numpy(dtype=float) for i in order])
n_levels = len(taus)
# %% Scores
if form == "normal":
z = (y - mu) / sd
nll = float(np.mean(sc.nll_normal(y, mu, sd)))
crps = float(np.mean(sc.crps_normal(y, mu, sd)))
ybar, sy = float(np.mean(y)), float(np.std(y, ddof=1))
if sy > 0:
crps_ref = float(np.mean(sc.crps_normal(y, ybar, sy))) # one normal for every row: the outcome's mean and SD
crps_skill = 1 - crps / crps_ref
mean_sd = float(np.mean(sd))
pit = stats.norm.cdf(z)
counts = sc.pit_bins(pit, bins)
expected = np.full(bins, 1 / bins)
for lev in sc.LEVELS:
zq = float(stats.norm.ppf((1 + lev) / 2))
kc = int(np.sum(np.abs(z) <= zq))
lw, hg = cov.wilson(kc, n, conf)
coverage_rows.append({"level": lev, "covered": kc, "coverage": kc / n, "low": lw, "high": hg, "width": float(np.mean(2 * zq * sd))})
else:
n_crossing = int(np.sum(np.any(q[:, :-1] > q[:, 1:], axis=1))) if n_levels > 1 else 0
losses = [float(np.mean(sc.pinball(y, q[:, k], taus[k]))) for k in range(n_levels)]
mean_pinball = float(np.mean(losses))
pairs = sc.central_pairs(taus)
if pairs:
wis = float(np.mean(sc.wis(y, q, taus)))
cat = np.sum(q < y[:, None], axis=1) # number of quantiles strictly below the outcome
counts = np.bincount(cat, minlength=n_levels + 1)
expected = np.diff(np.concatenate([[0.0], taus, [1.0]]))
for i, j in pairs:
kc = int(np.sum((q[:, i] <= y) & (y <= q[:, j])))
lw, hg = cov.wilson(kc, n, conf)
coverage_rows.append({"level": 1 - 2 * taus[i], "covered": kc, "coverage": kc / n, "low": lw, "high": hg,
"width": float(np.mean(q[:, j] - q[:, i]))})
for k in range(n_levels):
kb = int(np.sum(y <= q[:, k]))
lw, hg = cov.wilson(kb, n, conf)
reliability_rows.append({"level": taus[k], "below": kb, "share": kb / n, "low": lw, "high": hg, "pinball": losses[k]})
test = sc.chisq(counts, expected)
for r in coverage_rows:
if abs(r["level"] - 0.9) < 1e-9:
cov90 = (r["coverage"], r["low"], r["high"])
# %% Assumptions
min_expected = float(np.min(np.asarray(expected) * n))
assumptions = [
{"key": "held_out", "label": "Predictions were made without these rows", "status": "info",
"detail": "Use out-of-fold or test-set predictions: scores on the fitted rows are too good."},
{"key": "pit_bins", "label": "Enough rows per PIT bin", "status": "pass" if min_expected >= 5 else "warn",
"detail": f"The smallest expected count is {min_expected:.1f}" + ("." if min_expected >= 5 else "; the χ² test is rough below 5 — use fewer bins.")},
]
if form == "quantile":
assumptions.append({"key": "quantiles_ordered", "label": "Quantiles do not cross", "status": "pass" if n_crossing == 0 else "warn",
"detail": "No row has a higher level with a lower quantile." if n_crossing == 0 else f"{n_crossing} row(s) have crossing quantiles; they are scored as given."})
# %% Result
pct = f"{conf:.0%}"
values = {
"n": n, "form": form, "n_levels": n_levels, "nll": nll, "crps": crps, "crps_ref": crps_ref, "crps_skill": crps_skill,
"mean_sd": mean_sd, "mean_pinball": mean_pinball, "wis": wis,
"pit_chi2": test["chi2"], "pit_df": float(test["df"]), "pit_p": test["p"],
"coverage_90": cov90[0], "coverage_90_low": cov90[1], "coverage_90_high": cov90[2], "n_crossing": n_crossing,
}
charts = []
if form == "normal":
charts.append(cs.chart("pit", "pit-histogram", f"PIT histogram ({bins} bins)", {"share": cs.col("Share of rows", counts / n)}))
if coverage_rows:
charts.append(cs.chart("coverage", "interval-coverage", "Central intervals: promised vs observed coverage", {
"nominal": cs.col("Promised coverage", [r["level"] for r in coverage_rows]),
"coverage": cs.col("Observed coverage", [r["coverage"] for r in coverage_rows]),
"width": cs.col("Mean width", [r["width"] for r in coverage_rows])}))
if reliability_rows:
charts.append(cs.chart("quantiles", "calibration", "How often the outcome falls below each quantile", {
"predicted": cs.col("Quantile level", [r["level"] for r in reliability_rows]),
"observed": cs.col("Share of outcomes at or below", [r["share"] for r in reliability_rows]),
"n": cs.col("n", [n] * len(reliability_rows)),
"low": cs.col("low", [r["low"] for r in reliability_rows]), "high": cs.col("high", [r["high"] for r in reliability_rows])}))
tables = []
if form == "normal":
tables.append({"key": "scores", "title": "Scores", "columns": [
{"key": "score", "label": "Score", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
{"key": "reference", "label": "Reference forecast", "type": "number"}],
"rows": [
{"score": "CRPS (exact, normal)", "value": crps, "reference": crps_ref},
{"score": "CRPS skill (1 − CRPS / reference)", "value": crps_skill, "reference": None},
{"score": "Log score (negative log-likelihood)", "value": nll, "reference": None},
{"score": "Mean predicted SD (sharpness)", "value": mean_sd, "reference": None}],
"note": "The reference forecast is one normal for every row, with the outcome's mean and SD. Lower CRPS and log score are better."})
else:
tables.append({"key": "scores", "title": "Scores", "columns": [
{"key": "score", "label": "Score", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
"rows": [
{"score": "Mean pinball loss", "value": mean_pinball},
{"score": "Weighted interval score", "value": wis},
{"score": "Rows with crossing quantiles", "value": float(n_crossing)}],
"note": "Lower is better. The weighted interval score needs pairs of levels that add up to 1 (such as 0.05 and 0.95)."})
tables.append({"key": "quantiles", "title": "Each quantile", "columns": [
{"key": "level", "label": "Level", "type": "number"}, {"key": "below", "label": "Outcomes at or below", "type": "integer"},
{"key": "share", "label": "Share", "type": "number"}, {"key": "low", "label": f"{pct} CI low", "type": "number"},
{"key": "high", "label": f"{pct} CI high", "type": "number"}, {"key": "pinball", "label": "Pinball loss", "type": "number"}],
"rows": reliability_rows, "note": "A calibrated quantile at level τ has about τ of the outcomes at or below it."})
if coverage_rows:
tables.append({"key": "coverage", "title": "Central intervals", "columns": [
{"key": "level", "label": "Promised", "type": "number"}, {"key": "covered", "label": "Covered", "type": "integer"},
{"key": "coverage", "label": "Coverage", "type": "number"}, {"key": "low", "label": f"{pct} CI low", "type": "number"},
{"key": "high", "label": f"{pct} CI high", "type": "number"}, {"key": "width", "label": "Mean width", "type": "number"}],
"rows": coverage_rows, "note": "Wilson intervals for each coverage share."})
summary = (f"{n} predictive distributions ({form}); PIT uniformity χ²({test['df']}) = {test['chi2']:.2f}, {cs.fmt_p(test['p'])}"
+ (f"; CRPS {crps:.4g} (skill {crps_skill:.1%})." if form == "normal" and crps_skill is not None else
f"; CRPS {crps:.4g}." if form == "normal" else f"; mean pinball loss {mean_pinball:.4g}."))
cs.publish({
"method": "evaluate.probabilistic",
"methodVersion": "1.0.0",
"title": "Score probabilistic predictions",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"statistics": [
*([{"key": "crps", "label": "CRPS", "value": crps}, {"key": "nll", "label": "Log score", "value": nll}] if form == "normal" else
[{"key": "mean_pinball", "label": "Mean pinball loss", "value": mean_pinball}, {"key": "wis", "label": "Weighted interval score", "value": wis}]),
{"key": "pit_chi2", "label": "PIT χ²", "value": test["chi2"]},
{"key": "pit_p", "label": "p", "value": test["p"], "format": "p"},
],
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"PIT categories tested against their expected shares with χ²({test['df']})."],
"charts": charts,
"values": values,
})
The CRPS is 2.64. Its skill is 0.472, which measures how much better than one normal distribution for every row the model does. The PIT histogram asks where each outcome landed inside its own predicted distribution. A calibrated model fills the bins evenly. A U shape means the outcomes keep landing in the tails, so the SDs are too small. A hump means they are too large.
Flagging the unfamiliar
ExploreAn out-of-distribution score should be high for rows unlike the training data. Here virginica irises play the stranger, and the score is the distance from the other two species:
AUROC 0.949 (95% CI 0.918 to 0.981); catching 96.0% of the 50 out-of-distribution rows flags 24.0% of the 100 familiar ones. AUPR-out 0.918, AUPR-in 0.975.
- AUROC
- 0.9494
- FPR at 95% TPR
- 0.2400
- AUPR-out
- 0.9182
- p (AUROC = 0.5)
- < .001
Plots
View data
| False-positive rate (familiar rows flagged) | Catches 95% | True-positive rate (out-of-distribution rows caught) |
|---|---|---|
| 0 | false | 0 |
| 0 | false | 0.0200 |
| 0 | false | 0.0400 |
| 0 | false | 0.0600 |
| 0 | false | 0.0800 |
| 0 | false | 0.1000 |
| 0 | false | 0.1200 |
| 0 | false | 0.1400 |
| 0 | false | 0.1600 |
| 0 | false | 0.1800 |
| 0 | false | 0.2000 |
| 0 | false | 0.2200 |
| 0 | false | 0.2400 |
| 0 | false | 0.2600 |
| 0 | false | 0.2800 |
| 0 | false | 0.3000 |
| 0 | false | 0.3200 |
| 0 | false | 0.3400 |
| 0 | false | 0.3600 |
| 0 | false | 0.3800 |
| 0 | false | 0.4000 |
| 0 | false | 0.4200 |
| 0 | false | 0.4400 |
| 0 | false | 0.4600 |
| 0 | false | 0.4800 |
| 0 | false | 0.5000 |
| 0.0100 | false | 0.5000 |
| 0.0100 | false | 0.5200 |
| 0.0100 | false | 0.5400 |
| 0.0100 | false | 0.5600 |
| 0.0100 | false | 0.5800 |
| 0.0100 | false | 0.6000 |
| 0.0100 | false | 0.6200 |
| 0.0100 | false | 0.6400 |
| 0.0200 | false | 0.6400 |
| 0.0200 | false | 0.6600 |
| 0.0200 | false | 0.6800 |
| 0.0200 | false | 0.7200 |
| 0.0200 | false | 0.7400 |
| 0.0300 | false | 0.7400 |
| 0.0400 | false | 0.7400 |
| 0.0500 | false | 0.7400 |
| 0.0600 | false | 0.7400 |
| 0.0600 | false | 0.7600 |
| 0.0700 | false | 0.7600 |
| 0.0800 | false | 0.7600 |
| 0.0800 | false | 0.7800 |
| 0.0800 | false | 0.8000 |
| 0.0900 | false | 0.8000 |
| 0.1000 | false | 0.8000 |
| 0.1100 | false | 0.8000 |
| 0.1100 | false | 0.8200 |
| 0.1200 | false | 0.8200 |
| 0.1300 | false | 0.8200 |
| 0.1400 | false | 0.8200 |
| 0.1400 | false | 0.8400 |
| 0.1500 | false | 0.8400 |
| 0.1600 | false | 0.8400 |
| 0.1600 | false | 0.8600 |
| 0.1700 | false | 0.8600 |
First 60 of 150 rows.
View data
| Positive class | Precision | Recall |
|---|---|---|
| Out-of-distribution | 1 | 0.0200 |
| Out-of-distribution | 1 | 0.0400 |
| Out-of-distribution | 1 | 0.0600 |
| Out-of-distribution | 1 | 0.0800 |
| Out-of-distribution | 1 | 0.1000 |
| Out-of-distribution | 1 | 0.1200 |
| Out-of-distribution | 1 | 0.1400 |
| Out-of-distribution | 1 | 0.1600 |
| Out-of-distribution | 1 | 0.1800 |
| Out-of-distribution | 1 | 0.2000 |
| Out-of-distribution | 1 | 0.2200 |
| Out-of-distribution | 1 | 0.2400 |
| Out-of-distribution | 1 | 0.2600 |
| Out-of-distribution | 1 | 0.2800 |
| Out-of-distribution | 1 | 0.3000 |
| Out-of-distribution | 1 | 0.3200 |
| Out-of-distribution | 1 | 0.3400 |
| Out-of-distribution | 1 | 0.3600 |
| Out-of-distribution | 1 | 0.3800 |
| Out-of-distribution | 1 | 0.4000 |
| Out-of-distribution | 1 | 0.4200 |
| Out-of-distribution | 1 | 0.4400 |
| Out-of-distribution | 1 | 0.4600 |
| Out-of-distribution | 1 | 0.4800 |
| Out-of-distribution | 1 | 0.5000 |
| Out-of-distribution | 0.9615 | 0.5000 |
| Out-of-distribution | 0.9630 | 0.5200 |
| Out-of-distribution | 0.9643 | 0.5400 |
| Out-of-distribution | 0.9655 | 0.5600 |
| Out-of-distribution | 0.9667 | 0.5800 |
| Out-of-distribution | 0.9677 | 0.6000 |
| Out-of-distribution | 0.9688 | 0.6200 |
| Out-of-distribution | 0.9697 | 0.6400 |
| Out-of-distribution | 0.9412 | 0.6400 |
| Out-of-distribution | 0.9429 | 0.6600 |
| Out-of-distribution | 0.9444 | 0.6800 |
| Out-of-distribution | 0.9474 | 0.7200 |
| Out-of-distribution | 0.9487 | 0.7400 |
| Out-of-distribution | 0.9250 | 0.7400 |
| Out-of-distribution | 0.9024 | 0.7400 |
| Out-of-distribution | 0.8810 | 0.7400 |
| Out-of-distribution | 0.8605 | 0.7400 |
| Out-of-distribution | 0.8636 | 0.7600 |
| Out-of-distribution | 0.8444 | 0.7600 |
| Out-of-distribution | 0.8261 | 0.7600 |
| Out-of-distribution | 0.8298 | 0.7800 |
| Out-of-distribution | 0.8333 | 0.8000 |
| Out-of-distribution | 0.8163 | 0.8000 |
| Out-of-distribution | 0.8000 | 0.8000 |
| Out-of-distribution | 0.7843 | 0.8000 |
| Out-of-distribution | 0.7885 | 0.8200 |
| Out-of-distribution | 0.7736 | 0.8200 |
| Out-of-distribution | 0.7593 | 0.8200 |
| Out-of-distribution | 0.7455 | 0.8200 |
| Out-of-distribution | 0.7500 | 0.8400 |
| Out-of-distribution | 0.7368 | 0.8400 |
| Out-of-distribution | 0.7241 | 0.8400 |
| Out-of-distribution | 0.7288 | 0.8600 |
| Out-of-distribution | 0.7167 | 0.8600 |
| Out-of-distribution | 0.7213 | 0.8800 |
First 60 of 298 rows.
View data
| Rows | score_maha |
|---|---|
| Familiar | 1.245 |
| Familiar | 2.456 |
| Familiar | 1.554 |
| Familiar | 2.323 |
| Familiar | 1.503 |
| Familiar | 2.978 |
| Familiar | 2.624 |
| Familiar | 1.249 |
| Familiar | 3.441 |
| Familiar | 3.288 |
| Familiar | 2.520 |
| Familiar | 2.640 |
| Familiar | 3.088 |
| Familiar | 3.700 |
| Familiar | 7.763 |
| Familiar | 9.118 |
| Familiar | 6.577 |
| Familiar | 1.616 |
| Familiar | 3.789 |
| Familiar | 2.375 |
| Familiar | 3.011 |
| Familiar | 2.790 |
| Familiar | 3.499 |
| Familiar | 2.791 |
| Familiar | 7.101 |
| Familiar | 2.528 |
| Familiar | 1.456 |
| Familiar | 1.534 |
| Familiar | 1.733 |
| Familiar | 2.517 |
| Familiar | 2.029 |
| Familiar | 4.669 |
| Familiar | 8.438 |
| Familiar | 5.793 |
| Familiar | 1.667 |
| Familiar | 2.881 |
| Familiar | 4.612 |
| Familiar | 3.349 |
| Familiar | 3.114 |
| Familiar | 1.302 |
| Familiar | 2.176 |
| Familiar | 12.495 |
| Familiar | 3.144 |
| Familiar | 7.444 |
| Familiar | 3.718 |
| Familiar | 2.804 |
| Familiar | 3.923 |
| Familiar | 1.976 |
| Familiar | 2.195 |
| Familiar | 1.231 |
| Familiar | 7.428 |
| Familiar | 3.094 |
| Familiar | 5.657 |
| Familiar | 3.631 |
| Familiar | 3.459 |
| Familiar | 4.361 |
| Familiar | 4.670 |
| Familiar | 4.330 |
| Familiar | 4.901 |
| Familiar | 6.899 |
First 60 of 150 rows.
Assumptions
- Scores come from a fitted detector — Fix the detector and any threshold before looking at these rows; tuning on them flatters every metric.
- Enough rows of each kind — 50 out-of-distribution and 100 familiar rows.
Detection metrics
| Metric | Value | 95% CI low | 95% CI high | Chance level |
|---|---|---|---|---|
| AUROC | 0.9494 | 0.9183 | 0.9805 | 0.5000 |
| FPR at 95% TPR | 0.2400 | — | — | 0.9500 |
| AUPR-out (out-of-distribution positive) | 0.9182 | — | — | 0.3333 |
| AUPR-in (familiar positive) | 0.9746 | — | — | 0.6667 |
Threshold 4.93678: rows with a score ≥ it are flagged (TPR 96.0%). DeLong interval for the AUROC.
- Out-of-distribution: split = out. Larger scores mean more likely out-of-distribution.
The exact R script · R R version 4.5.1 (2025-06-13)
# Evaluate out-of-distribution detection
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.ood 1.0.0 · spec fffdf59d46b92863
# Dataset: evp_ood (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_eval_fpr_at_tpr, cs_eval_average_precision, cs_eval_ood_roc, cs_auc_delong
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/evp_ood.parquet", col_select = c("score_maha", "split")))
n_input <- nrow(df)
df[["split"]] <- factor(df[["split"]], levels = c("in", "out")) # stored level order
df <- df[stats::complete.cases(df[c("score_maha", "split")]), , 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("score_maha", "split")) # infinite values stop the run (registry/errors.yaml)
# %% Scores
sc_col <- "score_maha"
lc <- "split"
present <- levels(df[[lc]]) # levels with data, in stored order
cs_check_groups(df[[lc]], lc, minimum = 2, exactly = 2)
out_level <- present[length(present)] # default: the last level ("true")
direction <- "higher"
raw <- as.numeric(df[[sc_col]])
s <- if (direction == "higher") raw else -raw # larger = more likely out-of-distribution
pos <- as.character(df[[lc]]) == out_level
n <- length(pos)
n_out <- sum(pos)
n_in <- n - n_out
target <- 0.95
conf <- 0.95
# %% Detection
dl <- cs_auc_delong(s[pos], s[!pos], conf)
op <- cs_eval_fpr_at_tpr(s, pos, target)
threshold <- if (direction == "higher") op$threshold else -op$threshold
aupr_out <- cs_eval_average_precision(s, pos)
aupr_in <- cs_eval_average_precision(-s, !pos)
# %% Assumptions
small <- min(n_in, n_out) < 20
assumptions <- list(
list(key = "held_out", label = "Scores come from a fitted detector", status = "info",
detail = "Fix the detector and any threshold before looking at these rows; tuning on them flatters every metric."),
list(key = "sample_size", label = "Enough rows of each kind", status = if (small) "warn" else "pass",
detail = paste0(sprintf("%d out-of-distribution and %d familiar rows", n_out, n_in),
if (small) "; the rates are noisy with fewer than 20 of either." else "."))
)
if (isTRUE(dl$auc < 0.5)) warnings <- c(warnings, "AUROC is below 0.5: the score ranks familiar rows as stranger than the out-of-distribution ones. Check the direction setting.")
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
values <- list(
n = n, n_in = n_in, n_out = n_out, ood_level = out_level, direction = direction, prevalence_out = n_out / n,
auroc = dl$auc, auroc_se = dl$se, auroc_low = dl$low, auroc_high = dl$high, auroc_p = dl$p,
target_tpr = target, threshold = threshold, tpr_at_threshold = op$tpr, fpr_at_tpr = op$fpr, tnr_at_tpr = 1 - op$fpr,
aupr_out = aupr_out, aupr_in = aupr_in
)
rc <- cs_eval_ood_roc(s, pos)
chosen <- rep(FALSE, length(rc$tpr))
chosen[1 + which(rc$threshold == op$threshold)[1]] <- TRUE # the operating point (element 1 is the (0, 0) start)
keep <- sort(union(cs_eval_thin(length(rc$tpr)), which(chosen)))
pr_out <- cs_eval_ood_pr(s, pos)
pr_in <- cs_eval_ood_pr(-s, !pos)
ko <- cs_eval_thin(length(pr_out$recall))
ki <- cs_eval_thin(length(pr_in$recall))
charts <- list(
cs_chart("roc", "roc-curve", sprintf("ROC curve (AUROC %.3f)", dl$auc),
list(fpr = cs_col("False-positive rate (familiar rows flagged)", rc$fpr[keep]),
tpr = cs_col("True-positive rate (out-of-distribution rows caught)", rc$tpr[keep]),
optimal = cs_col(sprintf("Catches %.0f%%", 100 * target), chosen[keep], "boolean"))),
cs_chart("pr", "pr-curve", "Precision–recall, each class as positive",
list(recall = cs_col("Recall", c(pr_out$recall[ko], pr_in$recall[ki])),
precision = cs_col("Precision", c(pr_out$precision[ko], pr_in$precision[ki])),
curve = cs_col("Positive class", c(rep("Out-of-distribution", length(ko)), rep("Familiar", length(ki))), "categorical",
c("Out-of-distribution", "Familiar")))),
cs_chart("scores", "overlap-density", "Scores of familiar and out-of-distribution rows",
list(score = cs_col(sc_col, raw),
group = cs_col("Rows", ifelse(pos, "Out-of-distribution", "Familiar"), "categorical", c("Familiar", "Out-of-distribution"))))
)
summary <- sprintf("AUROC %.3f (%s CI %.3f to %.3f); catching %.1f%% of the %d out-of-distribution rows flags %.1f%% of the %d familiar ones. AUPR-out %.3f, AUPR-in %.3f.",
dl$auc, pct, dl$low, dl$high, 100 * op$tpr, n_out, 100 * op$fpr, n_in, aupr_out, aupr_in)
cs_publish(list(
method = "evaluate.ood",
methodVersion = "1.0.0",
title = "Evaluate out-of-distribution detection",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
statistics = list(
list(key = "auroc", label = "AUROC", value = dl$auc),
list(key = "fpr_at_tpr", label = sprintf("FPR at %.0f%% TPR", 100 * target), value = op$fpr),
list(key = "aupr_out", label = "AUPR-out", value = aupr_out),
list(key = "auroc_p", label = "p (AUROC = 0.5)", value = dl$p, format = "p")
),
tables = list(
list(key = "metrics", title = "Detection metrics",
columns = list(list(key = "metric", label = "Metric", type = "string"), list(key = "value", label = "Value", 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 = "chance", label = "Chance level", type = "number")),
rows = list(
list(metric = "AUROC", value = dl$auc, low = dl$low, high = dl$high, chance = 0.5),
list(metric = sprintf("FPR at %.0f%% TPR", 100 * target), value = op$fpr, low = NA, high = NA, chance = target),
list(metric = "AUPR-out (out-of-distribution positive)", value = aupr_out, low = NA, high = NA, chance = n_out / n),
list(metric = "AUPR-in (familiar positive)", value = aupr_in, low = NA, high = NA, chance = n_in / n)),
note = sprintf("Threshold %.6g: rows with a score %s it are flagged (TPR %.1f%%). DeLong interval for the AUROC.",
threshold, if (direction == "higher") "≥" else "≤", 100 * op$tpr))
),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Out-of-distribution: %s = %s. Larger scores mean %s.", lc, out_level,
if (direction == "higher") "more likely out-of-distribution" else "more familiar")),
charts = charts,
values = values
))
AUROC 0.949 (95% CI 0.918 to 0.981); catching 96.0% of the 50 out-of-distribution rows flags 24.0% of the 100 familiar ones. AUPR-out 0.918, AUPR-in 0.975.
- AUROC
- 0.9494
- FPR at 95% TPR
- 0.2400
- AUPR-out
- 0.9182
- p (AUROC = 0.5)
- < .001
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Scores come from a fitted detector — Fix the detector and any threshold before looking at these rows; tuning on them flatters every metric.
- Enough rows of each kind — 50 out-of-distribution and 100 familiar rows.
Detection metrics
| Metric | Value | 95% CI low | 95% CI high | Chance level |
|---|---|---|---|---|
| AUROC | 0.9494 | 0.9183 | 0.9805 | 0.5000 |
| FPR at 95% TPR | 0.2400 | — | — | 0.9500 |
| AUPR-out (out-of-distribution positive) | 0.9182 | — | — | 0.3333 |
| AUPR-in (familiar positive) | 0.9746 | — | — | 0.6667 |
Threshold 4.93678: rows with a score ≥ it are flagged (TPR 96.0%). DeLong interval for the AUROC.
- Out-of-distribution: split = out. Larger scores mean more likely out-of-distribution.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Evaluate out-of-distribution detection
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.ood 1.0.0 · spec fffdf59d46b92863
# Dataset: evp_ood (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 codesplash as cs
from codesplash.errors import check_groups
from codesplash.evaluate import ood # thresholds, FPR at a target TPR, average precision (twin: codesplashr cs_eval_*)
from codesplash.stats import roc # AUROC with DeLong's SE (twin: cs_auc_delong)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/evp_ood.parquet", columns=["score_maha", "split"])
n_input = len(df)
df["split"] = pd.Categorical(df["split"], categories=["in", "out"]) # stored level order
df = df.dropna(subset=["score_maha", "split"]) # listwise deletion over the analysis columns
df["split"] = df["split"].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, ["score_maha", "split"]) # infinite values stop the run (registry/errors.yaml)
# %% Scores
sc_col, lc = "score_maha", "split"
present = [str(v) for v in df[lc].cat.categories] # levels with data, in stored order
check_groups(df[lc], lc, minimum=2, exactly=2)
out_level = present[-1] # default: the last level ("true")
direction = "higher"
raw = df[sc_col].to_numpy(dtype=float)
s = raw if direction == "higher" else -raw # larger = more likely out-of-distribution
pos = (df[lc].astype(str) == out_level).to_numpy()
n, n_out = int(pos.size), int(pos.sum())
n_in = n - n_out
target = 0.95
conf = 0.95
# %% Detection
dl = roc.auc_delong(s[pos], s[~pos], conf)
op = ood.fpr_at_tpr(s, pos, target)
threshold = op["threshold"] if direction == "higher" else -op["threshold"]
aupr_out = ood.average_precision(s, pos)
aupr_in = ood.average_precision(-s, ~pos)
# %% Assumptions
small = min(n_in, n_out) < 20
assumptions = [
{"key": "held_out", "label": "Scores come from a fitted detector", "status": "info",
"detail": "Fix the detector and any threshold before looking at these rows; tuning on them flatters every metric."},
{"key": "sample_size", "label": "Enough rows of each kind", "status": "warn" if small else "pass",
"detail": f"{n_out} out-of-distribution and {n_in} familiar rows" + ("; the rates are noisy with fewer than 20 of either." if small else ".")},
]
if dl["auc"] < 0.5:
warnings.append("AUROC is below 0.5: the score ranks familiar rows as stranger than the out-of-distribution ones. Check the direction setting.")
# %% Result
pct = f"{conf:.0%}"
values = {
"n": n, "n_in": n_in, "n_out": n_out, "ood_level": out_level, "direction": direction, "prevalence_out": n_out / n,
"auroc": dl["auc"], "auroc_se": dl["se"], "auroc_low": dl["low"], "auroc_high": dl["high"], "auroc_p": dl["p"],
"target_tpr": target, "threshold": threshold, "tpr_at_threshold": op["tpr"], "fpr_at_tpr": op["fpr"], "tnr_at_tpr": 1 - op["fpr"],
"aupr_out": aupr_out, "aupr_in": aupr_in,
}
rc = ood.roc_curve(s, pos)
keep = ood.thin(rc["tpr"].size)
chosen = np.zeros(rc["tpr"].size, dtype=bool)
chosen[1 + int(np.flatnonzero(rc["threshold"] == op["threshold"])[0])] = True # the operating point (index 0 is the (0, 0) start)
keep = np.union1d(keep, np.flatnonzero(chosen))
pr_out, pr_in = ood.pr_curve(s, pos), ood.pr_curve(-s, ~pos)
ko, ki = ood.thin(pr_out["recall"].size), ood.thin(pr_in["recall"].size)
charts = [
cs.chart("roc", "roc-curve", f"ROC curve (AUROC {dl['auc']:.3f})", {
"fpr": cs.col("False-positive rate (familiar rows flagged)", rc["fpr"][keep]),
"tpr": cs.col("True-positive rate (out-of-distribution rows caught)", rc["tpr"][keep]),
"optimal": cs.col(f"Catches {target:.0%}", chosen[keep], "boolean")}),
cs.chart("pr", "pr-curve", "Precision–recall, each class as positive", {
"recall": cs.col("Recall", np.concatenate([pr_out["recall"][ko], pr_in["recall"][ki]])),
"precision": cs.col("Precision", np.concatenate([pr_out["precision"][ko], pr_in["precision"][ki]])),
"curve": cs.col("Positive class", ["Out-of-distribution"] * ko.size + ["Familiar"] * ki.size, "categorical",
["Out-of-distribution", "Familiar"])}),
cs.chart("scores", "overlap-density", "Scores of familiar and out-of-distribution rows", {
"score": cs.col(sc_col, raw), "group": cs.col("Rows", np.where(pos, "Out-of-distribution", "Familiar"), "categorical",
["Familiar", "Out-of-distribution"])}),
]
summary = (f"AUROC {dl['auc']:.3f} ({pct} CI {dl['low']:.3f} to {dl['high']:.3f}); catching {op['tpr']:.1%} of the "
f"{n_out} out-of-distribution rows flags {op['fpr']:.1%} of the {n_in} familiar ones. AUPR-out {aupr_out:.3f}, AUPR-in {aupr_in:.3f}.")
cs.publish({
"method": "evaluate.ood",
"methodVersion": "1.0.0",
"title": "Evaluate out-of-distribution detection",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"statistics": [
{"key": "auroc", "label": "AUROC", "value": dl["auc"]},
{"key": "fpr_at_tpr", "label": f"FPR at {target:.0%} TPR", "value": op["fpr"]},
{"key": "aupr_out", "label": "AUPR-out", "value": aupr_out},
{"key": "auroc_p", "label": "p (AUROC = 0.5)", "value": dl["p"], "format": "p"},
],
"tables": [
{"key": "metrics", "title": "Detection metrics", "columns": [
{"key": "metric", "label": "Metric", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
{"key": "low", "label": f"{pct} CI low", "type": "number"}, {"key": "high", "label": f"{pct} CI high", "type": "number"},
{"key": "chance", "label": "Chance level", "type": "number"}],
"rows": [
{"metric": "AUROC", "value": dl["auc"], "low": dl["low"], "high": dl["high"], "chance": 0.5},
{"metric": f"FPR at {target:.0%} TPR", "value": op["fpr"], "low": None, "high": None, "chance": target},
{"metric": "AUPR-out (out-of-distribution positive)", "value": aupr_out, "low": None, "high": None, "chance": n_out / n},
{"metric": "AUPR-in (familiar positive)", "value": aupr_in, "low": None, "high": None, "chance": n_in / n}],
"note": f"Threshold {threshold:.6g}: rows with a score {'≥' if direction == 'higher' else '≤'} it are flagged (TPR {op['tpr']:.1%}). DeLong interval for the AUROC."},
],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Out-of-distribution: {lc} = {out_level}. Larger scores mean {'more likely out-of-distribution' if direction == 'higher' else 'more familiar'}."],
"charts": charts,
"values": values,
})
AUROC is 0.949, but the number teams act on is the false-positive rate at 95% caught. Set the threshold so that 95% of the strangers are flagged. Then 0.240 of the familiar rows get flagged too. Each of those is a false alarm someone has to deal with.
Check your understanding
CheckpointCheck yourself
The metric is AUC and the difference A − B is 0.03, with an interval from 0.01 to 0.05. What does that say?
Show the answer
Answer: a
AUC is higher-is-better, so a positive A − B favors A, and an interval above zero means the gap isn't just resampling noise.
Check yourself
Each patient appears in 12 rows (monthly visits). What happens to the interval if you leave the cluster column empty?
Show the answer
Answer: b
Resampling rows one at a time pretends there is more independent information than there is. Resampling whole patients gives an honest width.
Check yourself
A 95% interval method is applied to 500 test rows. How many misses would you expect if the promise holds?
Show the answer
Answer: 25
. Kupiec's test asks whether the observed number of misses is far from 25.
Check yourself
Overall coverage is 90.1% for 90% intervals, but one group is covered 74% of the time (95% CI 65% to 81%). What follows?
Show the answer
Answer: b
Conformal coverage is marginal: it holds on average over rows, not within every group. The group's whole interval sits below 90%.
Check yourself
A PIT histogram has tall bars at both ends and a low middle. What is wrong with the predicted distributions?
Show the answer
Answer: a
A U shape is the signature of SDs that are too small. A hump in the middle means they are too large, and a slope means the means are biased.
Check yourself
CRPS skill is −0.05. How do you read it?
Show the answer
Answer: b
Skill = 1 − CRPS / CRPS of the reference. Below zero means the reference forecast, which knows nothing about the rows, scores better.
Check yourself
Detector A has AUROC 0.95 and FPR at 95% TPR of 0.40. Detector B has AUROC 0.93 and FPR at 95% TPR of 0.12. You must catch 95% of the strangers. Which do you deploy?
Show the answer
Answer: b
AUROC averages over every threshold. Once the catch rate is fixed, the false-positive rate at that point is what the alarm queue will feel.
Check yourself
Your score is the model's top predicted probability, so higher means more confident. What do you set?
Show the answer
Answer: b
A confidence is high for familiar rows. The direction setting says so explicitly, and it is never guessed from the data.
In the app
In the appOpen Analyze and choose Evaluate predictions in the Test Chooser. Bind the outcome and the prediction columns, then pick what you want to know: compare two models, audit coverage, score distributions, or test an out-of-distribution score.
Recap
Recap- Use predictions the model made for rows it never saw.
- Two models on the same rows: compare them paired, and set a cluster column when rows come in groups.
- Intervals and sets: check coverage overall and by group, and read width or set size alongside it.
- Distributions: the CRPS scores the whole forecast, its skill compares it with a naive forecast, and the PIT histogram shows the direction of any miscalibration.
- Out-of-distribution scores: fix the catch rate you need, then read the false alarms it costs.
Concepts in this lesson