Coverage audits and out-of-distribution scores
Conformal coverage is promised on average, under exchangeability: audit it overall, over time and by group, with width. Score an out-of-distribution detector by ranking and by false alarms at your catch rate.
What runs in CodeSplash
- EVA027Split conformal prediction and coverage audit Runs in CodeSplash
- EVA028AUROC, precision–recall, and operating-point OOD evaluation Runs in CodeSplash
- Audit prediction intervals or sets Verified in Python and R
- Evaluate out-of-distribution detection Verified in Python and R
You will be able to
- Compute a split-conformal cutoff and say what its guarantee covers
- Audit coverage over time and by group, not only overall
- Read AUROC, average precision and the false-positive rate at a target catch rate
- Explain how prevalence and the choice of positive class change PR numbers
The split-conformal cutoff
ReadFit a model on one part, compute a nonconformity score (such as the absolute residual) on a separate calibration part of rows, and take
If the order exceeds , the cutoff is infinite. In the reference's nine-score example with = 20%, the interval around a prediction of 2 runs from 1.2 to 2.8.
The guarantee: if calibration and future rows are exchangeable and the model never saw the calibration labels, future intervals cover with probability at least , on average over rows.
Reference · EVA027 · Runs in CodeSplashSplit conformal prediction and coverage auditConstructs prediction sets using held-out conformity scores, then audits coverage and set size.Overall coverage can hide two failures
ExploreCoverage 90.1% of 506 rows (95% CI 87.2% to 92.4%) against a promised 90%; Kupiec p = .929.
- Coverage
- 0.9012
- Kupiec LR
- 0.0079
- p
- .929
Plots
View data
| Observed coverage | Promised coverage | Mean width |
|---|---|---|
| 0.9012 | 0.9000 | 14.320 |
View data
| river | high | low | Metric | Coverage |
|---|---|---|---|---|
| inland | 0.9334 | 0.8817 | Coverage | 0.9108 |
| river | 0.8793 | 0.6098 | Coverage | 0.7714 |
View data
| Interval width |
|---|
| 13.736 |
| 14.269 |
| 14.511 |
| 14.760 |
| 14.269 |
| 14.511 |
| 14.511 |
| 13.736 |
| 14.511 |
| 13.736 |
| 14.269 |
| 14.269 |
| 13.736 |
| 14.760 |
| 14.511 |
| 14.511 |
| 13.736 |
| 13.736 |
| 14.269 |
| 14.328 |
| 14.511 |
| 13.736 |
| 14.760 |
| 14.511 |
| 14.511 |
| 13.736 |
| 14.511 |
| 13.736 |
| 13.736 |
| 14.511 |
| 14.511 |
| 14.760 |
| 13.736 |
| 13.736 |
| 14.269 |
| 14.760 |
| 14.760 |
| 14.511 |
| 14.328 |
| 14.328 |
| 14.269 |
| 14.760 |
| 14.328 |
| 14.760 |
| 14.269 |
| 14.511 |
| 14.760 |
| 14.760 |
| 13.736 |
| 14.328 |
| 13.736 |
| 14.511 |
| 14.328 |
| 14.269 |
| 13.736 |
| 14.269 |
| 13.736 |
| 14.760 |
| 14.511 |
| 14.511 |
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 — 50.6 misses expected at 90% coverage.
Coverage and width
| Measure | Value | 95% CI low | 95% CI high |
|---|---|---|---|
| Coverage | 0.9012 | 0.8721 | 0.9242 |
| Promised coverage | 0.9000 | — | — |
| Below the interval | 0.0257 | — | — |
| Above the interval | 0.0731 | — | — |
| Mean width | 14.320 | — | — |
| Median width | 14.328 | — | — |
| Winkler score (α = 0.1) | 23.107 | — | — |
Tests of the misses
| Test | LR | df | p |
|---|---|---|---|
| Kupiec: miss rate equals 1 − promised coverage | 0.0079 | 1 | 0.9290 |
| Christoffersen: misses independent in time | 9.984 | 1 | 0.0016 |
| Christoffersen: conditional coverage (both) | 9.992 | 2 | 0.0068 |
Coverage by river
| river | n | Covered | Coverage | 95% CI low | 95% CI high | Mean width |
|---|---|---|---|---|---|---|
| inland | 471 | 429 | 0.9108 | 0.8817 | 0.9334 | 14.320 |
| river | 35 | 27 | 0.7714 | 0.6098 | 0.8793 | 14.323 |
Wilson intervals for each group's coverage.
- Group river is covered 77.1% of the time; even the top of its interval is below the promised 90%.
- Intervals: 456 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 84d7aaf1b29c1b7e
# 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", "lower90", "upper90", "river", "fold")))
n_input <- nrow(df)
df[["river"]] <- factor(df[["river"]], levels = c("inland", "river")) # stored level order
df <- df[stats::complete.cases(df[c("medv", "lower90", "upper90", "river", "fold")]), , 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", "lower90", "upper90", "river", "fold")) # infinite values stop the run (registry/errors.yaml)
# %% Predictions
yc <- "medv"
lower_col <- "lower90"
upper_col <- "upper90"
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.9
alpha <- 1 - nominal
conf <- 0.95
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)
ord <- order(df[["fold"]], method = "radix") # time order (ties keep the data order)
ch <- cs_eval_christoffersen(miss[ord])
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 <- "river"
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 90.1% of 506 rows (95% CI 87.2% to 92.4%) against a promised 90%; Kupiec p = .929.
- Coverage
- 0.9012
- Kupiec LR
- 0.0079
- p
- .929
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 — 50.6 misses expected at 90% coverage.
Coverage and width
| Measure | Value | 95% CI low | 95% CI high |
|---|---|---|---|
| Coverage | 0.9012 | 0.8721 | 0.9242 |
| Promised coverage | 0.9000 | — | — |
| Below the interval | 0.0257 | — | — |
| Above the interval | 0.0731 | — | — |
| Mean width | 14.320 | — | — |
| Median width | 14.328 | — | — |
| Winkler score (α = 0.1) | 23.107 | — | — |
Tests of the misses
| Test | LR | df | p |
|---|---|---|---|
| Kupiec: miss rate equals 1 − promised coverage | 0.0079 | 1 | 0.9290 |
| Christoffersen: misses independent in time | 9.984 | 1 | 0.0016 |
| Christoffersen: conditional coverage (both) | 9.992 | 2 | 0.0068 |
Coverage by river
| river | n | Covered | Coverage | 95% CI low | 95% CI high | Mean width |
|---|---|---|---|---|---|---|
| inland | 471 | 429 | 0.9108 | 0.8817 | 0.9334 | 14.320 |
| river | 35 | 27 | 0.7714 | 0.6098 | 0.8793 | 14.323 |
Wilson intervals for each group's coverage.
- Group river is covered 77.1% of the time; even the top of its interval is below the promised 90%.
- Intervals: 456 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 84d7aaf1b29c1b7e
# 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", "lower90", "upper90", "river", "fold"])
n_input = len(df)
df["river"] = pd.Categorical(df["river"], categories=["inland", "river"]) # stored level order
df = df.dropna(subset=["medv", "lower90", "upper90", "river", "fold"]) # listwise deletion over the analysis columns
df["river"] = df["river"].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", "lower90", "upper90", "river", "fold"]) # infinite values stop the run (registry/errors.yaml)
# %% Predictions
yc = "medv"
lower_col = "lower90"
upper_col = "upper90"
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.9
alpha = 1 - nominal
conf = 0.95
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)
order = np.argsort(df["fold"].to_numpy(), kind="stable") # time order (ties keep the data order)
ch = cov.christoffersen(miss[order])
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 = "river"
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,
})
These 90% intervals cover 90.1% of 506 rows, and Kupiec's test of the miss rate gives p = .929. Overall, the promise holds.
Now in time order: Christoffersen's test asks whether misses come in runs, and gives p = .002. And by group, rows near the river are covered only 77.1% of the time. Marginal coverage is not coverage for every group, every period or every individual.
A set that is always right
ReadCoverage 100.0% of 150 rows (95% CI 97.5% to 100.0%) against a promised 90%; Kupiec p < .001.
- Coverage
- 1
- Kupiec LR
- 31.608
- p
- < .001
Plots
View data
| Observed coverage | Promised coverage |
|---|---|
| 1 | 0.9000 |
View data
| petal | high | low | Metric | Coverage |
|---|---|---|---|---|
| short petals | 1 | 0.9408 | Coverage | 1 |
| long petals | 1 | 0.9586 | Coverage | 1 |
View data
| Labels in the set |
|---|
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 2 |
| 1 |
| 2 |
| 1 |
| 2 |
| 1 |
| 2 |
| 1 |
| 2 |
| 1 |
First 60 of 150 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 — 15.0 misses expected at 90% coverage.
Coverage and set size
| Measure | Value | 95% CI low | 95% CI high |
|---|---|---|---|
| Coverage | 1 | 0.9750 | 1 |
| Promised coverage | 0.9000 | — | — |
| Mean set size | 1.200 | — | — |
| Empty sets | 0 | — | — |
| Single-label sets | 0.8000 | — | — |
Tests of the misses
| Test | LR | df | p |
|---|---|---|---|
| Kupiec: miss rate equals 1 − promised coverage | 31.608 | 1 | 1.886e-8 |
| 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 petal
| petal | n | Covered | Coverage | 95% CI low | 95% CI high | Mean set size |
|---|---|---|---|---|---|---|
| short petals | 61 | 61 | 1 | 0.9408 | 1 | 1 |
| long petals | 89 | 89 | 1 | 0.9586 | 1 | 1.337 |
Wilson intervals for each group's coverage.
- Prediction sets: 150 of 150 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 1deea16acce71986
# Dataset: evp_sets (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_sets.parquet", col_select = c("species", "set90", "petal")))
n_input <- nrow(df)
df[["species"]] <- factor(df[["species"]], levels = c("setosa", "versicolor", "virginica")) # stored level order
df[["set90"]] <- factor(df[["set90"]], levels = c("setosa", "versicolor", "versicolor|virginica", "virginica")) # stored level order
df[["petal"]] <- factor(df[["petal"]], levels = c("short petals", "long petals")) # stored level order
df <- df[stats::complete.cases(df[c("species", "set90", "petal")]), , 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("species", "set90", "petal")) # infinite values stop the run (registry/errors.yaml)
# %% Predictions
yc <- "species"
lower_col <- NULL
upper_col <- NULL
set_col <- "set90"
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" && TRUE) {
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.9
alpha <- 1 - nominal
conf <- 0.95
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 <- "petal"
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 100.0% of 150 rows (95% CI 97.5% to 100.0%) against a promised 90%; Kupiec p < .001.
- Coverage
- 1
- Kupiec LR
- 31.608
- p
- < .001
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 — 15.0 misses expected at 90% coverage.
Coverage and set size
| Measure | Value | 95% CI low | 95% CI high |
|---|---|---|---|
| Coverage | 1 | 0.9750 | 1 |
| Promised coverage | 0.9000 | — | — |
| Mean set size | 1.200 | — | — |
| Empty sets | 0 | — | — |
| Single-label sets | 0.8000 | — | — |
Tests of the misses
| Test | LR | df | p |
|---|---|---|---|
| Kupiec: miss rate equals 1 − promised coverage | 31.608 | 1 | 1.886e-8 |
| 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 petal
| petal | n | Covered | Coverage | 95% CI low | 95% CI high | Mean set size |
|---|---|---|---|---|---|---|
| short petals | 61 | 61 | 1 | 0.9408 | 1 | 1 |
| long petals | 89 | 89 | 1 | 0.9586 | 1 | 1.337 |
Wilson intervals for each group's coverage.
- Prediction sets: 150 of 150 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 1deea16acce71986
# Dataset: evp_sets (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_sets.parquet", columns=["species", "set90", "petal"])
n_input = len(df)
df["species"] = pd.Categorical(df["species"], categories=["setosa", "versicolor", "virginica"]) # stored level order
df["set90"] = pd.Categorical(df["set90"], categories=["setosa", "versicolor", "versicolor|virginica", "virginica"]) # stored level order
df["petal"] = pd.Categorical(df["petal"], categories=["short petals", "long petals"]) # stored level order
df = df.dropna(subset=["species", "set90", "petal"]) # listwise deletion over the analysis columns
df["species"] = df["species"].cat.remove_unused_categories()
df["set90"] = df["set90"].cat.remove_unused_categories()
df["petal"] = df["petal"].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, ["species", "set90", "petal"]) # infinite values stop the run (registry/errors.yaml)
# %% Predictions
yc = "species"
lower_col = None
upper_col = None
set_col = "set90"
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 True:
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.9
alpha = 1 - nominal
conf = 0.95
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 = "petal"
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,
})
These 90% prediction sets cover 100.0% of rows: more than promised, and Kupiec flags it (p < .001). Over-coverage costs size. Here the average set holds 1.2 labels and 80% are single labels. A set holding every label always covers and never helps; always read width or size beside coverage.
Shift, grouped records and repeated measurements break exchangeability. Retraining or tuning after calibration means recalibrating.
HExplorable · Conformal coverage: marginal, conditional and under drift
A conformal interval promises 90% coverage. Over what, exactly, and when does the promise break?
Split conformal aims at 90%. When the noise grows with |x|, what share of points with |x| > 1.5 will it cover?
Interval
Scaled divides residuals by a fitted spread; CQR conformalizes a rough quantile band; normal theory is the t interval.
The model is fit on n rows; the interval is calibrated on n more. As in the Simulation Lab's conformal design.
The interval aims to cover 1 − α of new points.
Noise SD is 1 + this × |x|. At 0 the noise is the same everywhere.
New points get (1 + drift) times the noise the interval was calibrated on.
Commit your prediction above to see the result
Make your prediction to see the result.
Scoring an out-of-distribution detector
ReadAn out-of-distribution (OOD) detector gives each row a strangeness score. Two questions: does it rank strange rows above familiar ones, and what happens at the threshold you will use?
In the reference's five-row example, AUROC is 0.833 and average precision 0.833. Average precision isn't the same as the trapezoid area under the PR curve. Choose the threshold on validation data, then hold it fixed on test.
Reference · EVA028 · Runs in CodeSplashAUROC, precision–recall, and operating-point OOD evaluationEvaluates anomaly or out-of-distribution ranking and threshold behavior.Same scores, different numbers
ExploreAUROC 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,
})
A Mahalanobis distance scores iris flowers. With the 50 unusual flowers as positives, AUROC is 0.949; catching 95% of them flags 24% of familiar ones, and AUPR-out is 0.918.
Make the familiar flowers the positive class instead, with lower distance meaning more familiar: AUROC stays 0.949, but the false alarms at 95% become 26% and AUPR-out 0.975. PR numbers depend on which class is positive and how common it is. State the positive class, the prevalence and the direction.
Rare events and independence
ReadHigh AUROC can sit beside poor precision when anomalies are rare: a small false-positive rate on many familiar rows still swamps a few true alarms. Report the false alarms at the catch rate you need, in counts per day or per thousand cases.
Different OOD test mixtures can reverse a ranking of detectors, so describe the shifts you tested. And many windows from one equipment failure are one event, not many; count and resample events.
AExplorable · A score is not an alarm
How do you turn an anomaly score into alarms with a known false-alarm rate?
What share of new normal rows will raise an alarm (in %)?
Alarm rule
Calibrate on
1 means new normal rows look like the calibration rows.
- No alarm
- Alarm
- Calibration rows (dashed)
- New normal rows
- Planted anomalies
The cutoff comes from the calibration scores, not from the score's own scale. If calibration rows look like new normal rows, the share of normal rows past the cutoff stays near α.
Commit your prediction above to see the result
Make your prediction to see the result.
Coverage and OOD in CodeSplash
In the appIn Analyze, Evaluate predictions includes Audit prediction intervals or sets (coverage with a Wilson interval, Kupiec, Christoffersen with a time column, coverage by group, width or set size) and Evaluate out-of-distribution detection (AUROC with DeLong's interval, AUPR in and out, the false-positive rate at a target catch rate, with the direction always stated).
In Predict, a run's Uncertainty tab builds conformal intervals or sets, with Coverage by group (Mondrian), and the Slices tab's Abstain when unsure shows the risk–coverage trade-off of letting the model skip uncertain rows.
Check: coverage and OOD
CheckpointCheck yourself
Split conformal with n = 19 calibration scores and α = 0.1. Which sorted score (counting from the smallest) is the cutoff? Give its position.
Show the answer
Answer: 18
: the 18th smallest of the 19 scores.
Check yourself
90% conformal intervals cover 90% of rows overall but 77% of rows in one region. Is the guarantee broken?
Show the answer
Answer: b
Marginal coverage averages over rows. Calibrating within groups gives each group its own coverage, at a cost in width.
Check yourself
Coverage over time is right on average, but Christoffersen's independence test rejects. What does that mean?
Show the answer
Answer: a
Clustered misses mean whole periods are under-covered, which matters for any decision made in those periods.
Check yourself
A classifier's conformal sets cover 100% of test rows at a promised 90%. What should you check next?
Show the answer
Answer: b
Over-coverage usually means larger sets. Coverage without size can be achieved by listing every label.
Check yourself
An anomaly detector has AUROC 0.98. Anomalies are 1 in 1,000 rows, and at the threshold that catches 95% of them it flags 3% of normal rows. What does an operator see?
Show the answer
Answer: b
Per 1,000 rows: about 0.95 true alarms and about 30 false ones (3% of 999). High AUROC and poor precision coexist when events are rare.
Check yourself
Swapping which class counts as positive left AUROC unchanged but changed AUPR. Why?
Show the answer
Answer: b
AUROC ranks pairs either way. Precision counts positives among flagged rows, so prevalence and the choice of positive class matter.
Check yourself
Where should an OOD detector's alert threshold be chosen?
Show the answer
Answer: b
A threshold tuned on the test set makes the test's false-alarm rate optimistic.
Recap
Recap- Split conformal uses the -th calibration score; its coverage is marginal and needs exchangeability.
- Audit coverage overall, over time and by group, and always read width or set size.
- Score OOD detectors by ranking (AUROC, AP) and by false alarms at the catch rate you need.
- State the positive class, prevalence and direction; rare events turn small false-positive rates into many false alarms.
Concepts in this lesson