Skip to content

HEvaluate predictions · evaluate.conformal_audit

Audit prediction intervals or sets

Do saved prediction intervals or prediction sets contain the observed values as often as promised, and for every group?

Checks intervals (a lower and an upper column) or prediction sets (labels separated by "|") against what happened: coverage with a Wilson interval, misses below and above, width or set size, the Winkler interval score, Kupiec's test of the miss rate, coverage by group and, with a time column, Christoffersen's tests of whether misses come in runs.

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

A real result

Example “Intervals 90”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Audit prediction intervals or setsRecorded · Python and R agreeRecorded 2026-11-17 · 26 values compared
R

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

Plots

Promised vs observed coverageDo prediction intervals contain the truth as often as they promise?
View data
Observed coveragePromised coverageMean width
0.90120.900014.320
Interval widthsHow is one numeric variable distributed?
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; add a group column to check groups.
  • Enough expected misses — 50.6 misses expected at 90% coverage.

Coverage and width

MeasureValue95% CI low95% CI high
Coverage0.90120.87210.9242
Promised coverage0.9000——
Below the interval0.0257——
Above the interval0.0731——
Mean width14.320——
Median width14.328——
Winkler score (α = 0.1)23.107——

Tests of the misses

TestLRdfp
Kupiec: miss rate equals 1 − promised coverage0.007910.9290
Christoffersen: misses independent in time—1—
Christoffersen: conditional coverage (both)—2—

The Christoffersen tests need a time column and at least one miss.

  • Intervals: 456 of 506 rows covered.
Python

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; add a group column to check groups.
  • Enough expected misses — 50.6 misses expected at 90% coverage.

Coverage and width

MeasureValue95% CI low95% CI high
Coverage0.90120.87210.9242
Promised coverage0.9000——
Below the interval0.0257——
Above the interval0.0731——
Mean width14.320——
Median width14.328——
Winkler score (α = 0.1)23.107——

Tests of the misses

TestLRdfp
Kupiec: miss rate equals 1 − promised coverage0.007910.9290
Christoffersen: misses independent in time—1—
Christoffersen: conditional coverage (both)—2—

The Christoffersen tests need a time column and at least one miss.

  • Intervals: 456 of 506 rows covered.

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Intervals 90evp_regress · lower: lower90 · outcome: medv · upper: upper90
  • Intervals 80 by groupevp_regress · group: access · lower: lower80 · outcome: medv · upper: upper80
  • Intervals time orderevp_regress · group: river · lower: lower90 · outcome: medv · time: fold · upper: upper90
  • Sets cumulativeevp_sets · group: petal · outcome: species · set: set90
  • Sets strict emptyevp_sets · outcome: species · set: set_strict
  • Degenerate constantevp_regress · lower: lower90 · outcome: medv · upper: upper90
  • Degenerate n2evp_regress · lower: lower90 · outcome: medv · upper: upper90

In the guides

Where it sits in the decision guides

  • Probabilistic forecasting (Bayesian, deep ensembles) · DS & ML Decision Guide · Predict — forecast or classify outcomes
  • Predict: regression MAE, RMSE, R²; classification accuracy, precision, recall, F1, AUC; calibration, lift, log loss · DS & ML Decision Guide · How to evaluate — common metrics by question type

What you need

Observed outcomenumeric / categorical / boolean · 1 column
What happened. A number for intervals; a label for prediction sets.
Interval lower boundnumeric · 0–1 column
The lower end of each row's prediction interval (use with the upper bound, or choose a prediction-set column instead).
Interval upper boundnumeric · 0–1 column
The upper end of each row's prediction interval.
Prediction setcategorical · 0–1 column
The labels each row's set contains, separated by "|" (for example "cat|dog"); write {} for an empty set.
Groups to compare (optional)categorical / boolean · 0–1 column
Coverage is also shown for each group, since overall coverage can hide groups that are covered far less often.
Time order (optional)numeric / temporal · 0–1 column
Puts the rows in time order for Christoffersen's tests of whether misses cluster in time.

Choices you make

hypothesis

Promised coveragedefault 0.9

The share of rows the intervals or sets were built to contain (0.9 for 90% intervals).

Confidence leveldefault 0.95

How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.

options

Separator between set labelsdefault |

The character between the labels of a prediction set.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Intervals were made without these rows

    Coverage is only meaningful on rows the model and its calibration never saw (a test set or out-of-fold predictions).

  • Rows are exchangeable

    Conformal guarantees are about the average over rows like the calibration rows; a shift in the data, or a group, can be covered less often.

  • Enough expected misses

    The tests need about ten or more expected misses (rows × (1 − promised coverage)); with fewer they have little power.

What it reports

  • Tests: Coverage differs from the promised level (Kupiec)
  • Tests: Misses cluster in time (Christoffersen)
n
The rows with an outcome and a complete interval or prediction set.
form
interval when a lower and an upper column were given; set when a prediction-set column was given.
nominal
The share of rows the intervals or sets were built to contain, such as 0.9 for 90% intervals.
covered
The share of rows whose interval or set contains what happened, with a Wilson interval and the count covered.
coverage
The share of rows whose interval or set contains what happened, with a Wilson interval and the count covered.
coverage_low
The share of rows whose interval or set contains what happened, with a Wilson interval and the count covered.
coverage_high
The share of rows whose interval or set contains what happened, with a Wilson interval and the count covered.
n_below
Rows whose outcome fell below the lower bound or above the upper bound (intervals only).
n_above
Rows whose outcome fell below the lower bound or above the upper bound (intervals only).
mean_width
The mean and median of upper − lower: narrower intervals at the same coverage are more useful.
median_width
The mean and median of upper − lower: narrower intervals at the same coverage are more useful.
winkler
Width plus 2/α times how far the outcome fell outside the interval; lower is better (α = 1 − promised coverage).
mean_size
The mean number of labels per set, and the shares of empty and single-label sets (prediction sets only).
share_empty
The mean number of labels per set, and the shares of empty and single-label sets (prediction sets only).
share_singleton
The mean number of labels per set, and the shares of empty and single-label sets (prediction sets only).
kupiec_lr
Likelihood-ratio test that the miss rate equals 1 − promised coverage (χ² with 1 df).
kupiec_p
Likelihood-ratio test that the miss rate equals 1 − promised coverage (χ² with 1 df).
christoffersen_lr
Do misses come in runs over time (independence, 1 df), and together with Kupiec (conditional coverage, 2 df)? Needs a time column.
christoffersen_p
Do misses come in runs over time (independence, 1 df), and together with Kupiec (conditional coverage, 2 df)? Needs a time column.
cc_lr
Do misses come in runs over time (independence, 1 df), and together with Kupiec (conditional coverage, 2 df)? Needs a time column.
cc_p
Do misses come in runs over time (independence, 1 df), and together with Kupiec (conditional coverage, 2 df)? Needs a time column.
n_groups
The group with the lowest coverage, its Wilson interval, and how many groups were compared.
worst_group
The group with the lowest coverage, its Wilson interval, and how many groups were compared.
worst_group_coverage
The group with the lowest coverage, its Wilson interval, and how many groups were compared.
worst_group_low
The group with the lowest coverage, its Wilson interval, and how many groups were compared.
worst_group_high
The group with the lowest coverage, its Wilson interval, and how many groups were compared.

Python and R

Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.

Python

The exact script CodeSplash ran for example “Intervals 90” · 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 e2646199d4c00a21
# 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"])
n_input = len(df)
df = df.dropna(subset=["medv", "lower90", "upper90"])  # 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", "lower90", "upper90"])  # 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)
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 = []
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,
})
R

The exact script CodeSplash ran for example “Intervals 90” · 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 e2646199d4c00a21
# 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")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("medv", "lower90", "upper90")]), , 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"))  # 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)
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()
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
))

Sources

  • Kupiec, P. H. (1995). Techniques for verifying the accuracy of risk measurement models. Journal of Derivatives, 3, 73–84.
  • Christoffersen, P. F. (1998). Evaluating interval forecasts. International Economic Review, 39, 841–862.
  • Winkler, R. L. (1972). A decision-theoretic approach to interval estimation. Journal of the American Statistical Association, 67, 187–191.
  • Angelopoulos, A. N., & Bates, S. (2023). Conformal prediction: a gentle introduction. Foundations and Trends in Machine Learning, 16, 494–591.
  • Wilson, E. B. (1927). Probable inference, the law of succession, and statistical inference. Journal of the American Statistical Association, 22, 209–212.

From the CodeSplash method registry · evaluate.conformal_audit v1.0.0.