Skip to content

HEvaluate predictions · evaluate.probabilistic

Score probabilistic predictions

How good are predictions given as distributions (a mean and SD, or quantiles), and are they calibrated?

Scores predictive distributions against what happened. For a predicted mean and SD (normal): the log score, the exact CRPS with its skill over a one-size-fits-all forecast, the PIT histogram with a uniformity test, and coverage of central intervals. For predicted quantiles: the pinball loss, the weighted interval score, interval coverage and how often the outcome falls below each quantile.

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

A real result

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

Score probabilistic predictionsRecorded · Python and R agreeRecorded 2026-11-17 · 17 values compared
R

506 predictive distributions (normal); PIT uniformity χ²(9) = 72.06, p < .001; CRPS 2.638 (skill 47.2%).

CRPS
2.638
Log score
3.046
PIT χ²
72.063
p
< .001

Plots

PIT histogram (10 bins)Do the actual values look like draws from the forecast distributions?
View data
Share of rows
0.0415
0.1146
0.1324
0.1522
0.1462
0.1206
0.0929
0.0455
0.0672
0.0870
Central intervals: promised vs observed coverageDo prediction intervals contain the truth as often as they promise?
View data
Observed coveragePromised coverageMean width
0.60470.50006.752
0.87150.800012.830
0.92090.900016.467
0.95060.950019.622

Assumptions

  • Predictions were made without these rows — Use out-of-fold or test-set predictions: scores on the fitted rows are too good.
  • Enough rows per PIT bin — The smallest expected count is 50.6.

Scores

ScoreValueReference forecast
CRPS (exact, normal)2.6384.998
CRPS skill (1 − CRPS / reference)0.4723—
Log score (negative log-likelihood)3.046—
Mean predicted SD (sharpness)5.006—

The reference forecast is one normal for every row, with the outcome's mean and SD. Lower CRPS and log score are better.

Central intervals

PromisedCoveredCoverage95% CI low95% CI highMean width
0.50003060.60470.56150.64646.752
0.80004410.87150.83960.897912.830
0.90004660.92090.89410.941416.467
0.95004810.95060.92810.966319.622

Wilson intervals for each coverage share.

  • PIT categories tested against their expected shares with χ²(9).
Python

506 predictive distributions (normal); PIT uniformity χ²(9) = 72.06, p < .001; CRPS 2.638 (skill 47.2%).

CRPS
2.638
Log score
3.046
PIT χ²
72.063
p
< .001

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

Assumptions

  • Predictions were made without these rows — Use out-of-fold or test-set predictions: scores on the fitted rows are too good.
  • Enough rows per PIT bin — The smallest expected count is 50.6.

Scores

ScoreValueReference forecast
CRPS (exact, normal)2.6384.998
CRPS skill (1 − CRPS / reference)0.4723—
Log score (negative log-likelihood)3.046—
Mean predicted SD (sharpness)5.006—

The reference forecast is one normal for every row, with the outcome's mean and SD. Lower CRPS and log score are better.

Central intervals

PromisedCoveredCoverage95% CI low95% CI highMean width
0.50003060.60470.56150.64646.752
0.80004410.87150.83960.897912.830
0.90004660.92090.89410.941416.467
0.95004810.95060.92810.966319.622

Wilson intervals for each coverage share.

  • PIT categories tested against their expected shares with χ²(9).

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

  • Normal defaultevp_regress · mean: pred_a · outcome: medv · sd: sd_a
  • Normal bins 20evp_regress · mean: pred_a · outcome: medv · sd: sd_a
  • Quantiles fiveevp_regress · outcome: medv · quantiles: q05, q25, q50, q75, q95
  • Quantiles no medianevp_regress · outcome: medv · quantiles: q95, q05, q75, q25
  • Degenerate constantevp_regress · mean: pred_a · outcome: medv · sd: sd_a
  • Degenerate n2evp_regress · mean: pred_a · outcome: medv · sd: sd_a

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 · 1 column
What happened, in the same units as the predictions.
Predicted meannumeric · 0–1 column
The center of each row's normal predictive distribution (use with the predicted SD, or choose quantile columns instead).
Predicted SDnumeric · 0–1 column
The spread of each row's normal predictive distribution; must be above zero.
Predicted quantilesnumeric · 0–25 columns
One column per predicted quantile, in the order of "Quantile levels" (for example the 5%, 50% and 95% quantiles).

Choices you make

hypothesis

Quantile levelsdefault 0.05, 0.25, 0.5, 0.75, 0.95

The level of each quantile column, in the same order, separated by commas (0.05 is the 5% quantile).

Confidence leveldefault 0.95

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

statistics

PIT binsdefault 10

Equal-width bins of the probability integral transform for the histogram and its uniformity test (normal predictions).

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.

  • Predictions were made without these rows

    Scores on the rows the model was fitted to are too good; use out-of-fold or test-set predictions.

  • Enough rows per PIT bin

    The χ² uniformity test needs about five or more expected rows in every bin or category.

  • Quantiles do not cross

    A higher level should never have a lower quantile; crossing rows are scored as given and counted.

What it reports

  • Tests: The predictive distributions are miscalibrated (PIT not uniform)
n
The rows with an outcome and a complete predictive distribution.
form
normal for a predicted mean and SD; quantile for predicted quantiles, with the number of quantile levels.
n_levels
normal for a predicted mean and SD; quantile for predicted quantiles, with the number of quantile levels.
nll
Mean negative log density of the outcome under each row's normal prediction; lower is better.
crps
Continuous ranked probability score of normal predictions, in the outcome's units; lower is better. Exact, not approximated.
crps_ref
1 − CRPS / CRPS of one normal for every row (the outcome's mean and SD). Above 0 beats that reference.
crps_skill
1 − CRPS / CRPS of one normal for every row (the outcome's mean and SD). Above 0 beats that reference.
mean_sd
Sharpness: the average predicted spread. Narrower is better only when coverage holds.
mean_pinball
The quantile loss averaged over rows and quantile levels; lower is better.
wis
Interval scores of the central intervals (and the median's error), weighted as in Bracher et al. (2021); lower is better.
pit_chi2
χ² test that outcomes fall evenly across the predicted distributions' bins or quantile gaps; small p means miscalibrated.
pit_df
χ² test that outcomes fall evenly across the predicted distributions' bins or quantile gaps; small p means miscalibrated.
pit_p
χ² test that outcomes fall evenly across the predicted distributions' bins or quantile gaps; small p means miscalibrated.
coverage_90
Share of outcomes inside the central 90% interval, with a Wilson interval; empty without a 5%/95% quantile pair.
coverage_90_low
Share of outcomes inside the central 90% interval, with a Wilson interval; empty without a 5%/95% quantile pair.
coverage_90_high
Share of outcomes inside the central 90% interval, with a Wilson interval; empty without a 5%/95% quantile pair.
n_crossing
Rows where a higher quantile level has a lower value than a lower one; scored as given.

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 “Normal default” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Score probabilistic predictions
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.probabilistic 1.0.0 · spec b3574198e5795f82
# Dataset: evp_regress (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import math

import numpy as np
import pandas as pd
from scipy import stats

import codesplash as cs
from codesplash.errors import check_rows
from codesplash.evaluate import coverage as cov  # Wilson intervals (twin: cs_eval_wilson)
from codesplash.evaluate import scores as sc  # CRPS, log score, PIT, pinball, WIS (twin: codesplashr cs_eval_*)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/evp_regress.parquet", columns=["medv", "pred_a", "sd_a"])
n_input = len(df)
df = df.dropna(subset=["medv", "pred_a", "sd_a"])  # listwise deletion over the analysis columns
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["medv", "pred_a", "sd_a"])  # infinite values stop the run (registry/errors.yaml)

# %% Predictions
yc = "medv"
mean_col = "pred_a"
sd_col = "sd_a"
q_cols = []
allowed = "a mean and an SD column, or quantile columns"
if q_cols and (mean_col is not None or sd_col is not None):
    cs.cs_error("CS_E_INVALID_OPTION", option="Prediction columns", allowed=allowed, value="both")
if not q_cols and (mean_col is None or sd_col is None):
    cs.cs_error("CS_E_INVALID_OPTION", option="Prediction columns", allowed=allowed, value="a mean or an SD alone")
form = "quantile" if q_cols else "normal"
y = df[yc].to_numpy(dtype=float)
n = int(y.size)
check_rows(n, 3, "Scoring predictive distributions")
conf = 0.95
bins = int(10)
nll = crps = crps_ref = crps_skill = mean_sd = mean_pinball = wis = None
cov90 = (None, None, None)
n_crossing = None
coverage_rows, reliability_rows = [], []
if form == "normal":
    mu = df[mean_col].to_numpy(dtype=float)
    sd = df[sd_col].to_numpy(dtype=float)
    bad = int(np.sum(sd <= 0))
    if bad:
        cs.cs_error("CS_E_INVALID_VALUES", column=sd_col, requirement="a standard deviation above zero", count=bad)
    n_levels = None
else:
    taus = sc.parse_levels("0.05, 0.25, 0.5, 0.75, 0.95")
    if len(taus) != len(q_cols) or any(not (0 < t < 1) for t in taus) or len(set(taus)) != len(taus):
        cs.cs_error("CS_E_INVALID_OPTION", option="Quantile levels",
                    allowed=f"{len(q_cols)} different levels between 0 and 1, one per quantile column", value="0.05, 0.25, 0.5, 0.75, 0.95")
    order = np.argsort(np.asarray(taus), kind="stable")  # columns sorted by level
    taus = [taus[i] for i in order]
    q = np.column_stack([df[q_cols[i]].to_numpy(dtype=float) for i in order])
    n_levels = len(taus)

# %% Scores
if form == "normal":
    z = (y - mu) / sd
    nll = float(np.mean(sc.nll_normal(y, mu, sd)))
    crps = float(np.mean(sc.crps_normal(y, mu, sd)))
    ybar, sy = float(np.mean(y)), float(np.std(y, ddof=1))
    if sy > 0:
        crps_ref = float(np.mean(sc.crps_normal(y, ybar, sy)))  # one normal for every row: the outcome's mean and SD
        crps_skill = 1 - crps / crps_ref
    mean_sd = float(np.mean(sd))
    pit = stats.norm.cdf(z)
    counts = sc.pit_bins(pit, bins)
    expected = np.full(bins, 1 / bins)
    for lev in sc.LEVELS:
        zq = float(stats.norm.ppf((1 + lev) / 2))
        kc = int(np.sum(np.abs(z) <= zq))
        lw, hg = cov.wilson(kc, n, conf)
        coverage_rows.append({"level": lev, "covered": kc, "coverage": kc / n, "low": lw, "high": hg, "width": float(np.mean(2 * zq * sd))})
else:
    n_crossing = int(np.sum(np.any(q[:, :-1] > q[:, 1:], axis=1))) if n_levels > 1 else 0
    losses = [float(np.mean(sc.pinball(y, q[:, k], taus[k]))) for k in range(n_levels)]
    mean_pinball = float(np.mean(losses))
    pairs = sc.central_pairs(taus)
    if pairs:
        wis = float(np.mean(sc.wis(y, q, taus)))
    cat = np.sum(q < y[:, None], axis=1)  # number of quantiles strictly below the outcome
    counts = np.bincount(cat, minlength=n_levels + 1)
    expected = np.diff(np.concatenate([[0.0], taus, [1.0]]))
    for i, j in pairs:
        kc = int(np.sum((q[:, i] <= y) & (y <= q[:, j])))
        lw, hg = cov.wilson(kc, n, conf)
        coverage_rows.append({"level": 1 - 2 * taus[i], "covered": kc, "coverage": kc / n, "low": lw, "high": hg,
                              "width": float(np.mean(q[:, j] - q[:, i]))})
    for k in range(n_levels):
        kb = int(np.sum(y <= q[:, k]))
        lw, hg = cov.wilson(kb, n, conf)
        reliability_rows.append({"level": taus[k], "below": kb, "share": kb / n, "low": lw, "high": hg, "pinball": losses[k]})
test = sc.chisq(counts, expected)
for r in coverage_rows:
    if abs(r["level"] - 0.9) < 1e-9:
        cov90 = (r["coverage"], r["low"], r["high"])

# %% Assumptions
min_expected = float(np.min(np.asarray(expected) * n))
assumptions = [
    {"key": "held_out", "label": "Predictions were made without these rows", "status": "info",
     "detail": "Use out-of-fold or test-set predictions: scores on the fitted rows are too good."},
    {"key": "pit_bins", "label": "Enough rows per PIT bin", "status": "pass" if min_expected >= 5 else "warn",
     "detail": f"The smallest expected count is {min_expected:.1f}" + ("." if min_expected >= 5 else "; the χ² test is rough below 5 — use fewer bins.")},
]
if form == "quantile":
    assumptions.append({"key": "quantiles_ordered", "label": "Quantiles do not cross", "status": "pass" if n_crossing == 0 else "warn",
                        "detail": "No row has a higher level with a lower quantile." if n_crossing == 0 else f"{n_crossing} row(s) have crossing quantiles; they are scored as given."})

# %% Result
pct = f"{conf:.0%}"
values = {
    "n": n, "form": form, "n_levels": n_levels, "nll": nll, "crps": crps, "crps_ref": crps_ref, "crps_skill": crps_skill,
    "mean_sd": mean_sd, "mean_pinball": mean_pinball, "wis": wis,
    "pit_chi2": test["chi2"], "pit_df": float(test["df"]), "pit_p": test["p"],
    "coverage_90": cov90[0], "coverage_90_low": cov90[1], "coverage_90_high": cov90[2], "n_crossing": n_crossing,
}
charts = []
if form == "normal":
    charts.append(cs.chart("pit", "pit-histogram", f"PIT histogram ({bins} bins)", {"share": cs.col("Share of rows", counts / n)}))
if coverage_rows:
    charts.append(cs.chart("coverage", "interval-coverage", "Central intervals: promised vs observed coverage", {
        "nominal": cs.col("Promised coverage", [r["level"] for r in coverage_rows]),
        "coverage": cs.col("Observed coverage", [r["coverage"] for r in coverage_rows]),
        "width": cs.col("Mean width", [r["width"] for r in coverage_rows])}))
if reliability_rows:
    charts.append(cs.chart("quantiles", "calibration", "How often the outcome falls below each quantile", {
        "predicted": cs.col("Quantile level", [r["level"] for r in reliability_rows]),
        "observed": cs.col("Share of outcomes at or below", [r["share"] for r in reliability_rows]),
        "n": cs.col("n", [n] * len(reliability_rows)),
        "low": cs.col("low", [r["low"] for r in reliability_rows]), "high": cs.col("high", [r["high"] for r in reliability_rows])}))
tables = []
if form == "normal":
    tables.append({"key": "scores", "title": "Scores", "columns": [
        {"key": "score", "label": "Score", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
        {"key": "reference", "label": "Reference forecast", "type": "number"}],
        "rows": [
            {"score": "CRPS (exact, normal)", "value": crps, "reference": crps_ref},
            {"score": "CRPS skill (1 − CRPS / reference)", "value": crps_skill, "reference": None},
            {"score": "Log score (negative log-likelihood)", "value": nll, "reference": None},
            {"score": "Mean predicted SD (sharpness)", "value": mean_sd, "reference": None}],
        "note": "The reference forecast is one normal for every row, with the outcome's mean and SD. Lower CRPS and log score are better."})
else:
    tables.append({"key": "scores", "title": "Scores", "columns": [
        {"key": "score", "label": "Score", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
        "rows": [
            {"score": "Mean pinball loss", "value": mean_pinball},
            {"score": "Weighted interval score", "value": wis},
            {"score": "Rows with crossing quantiles", "value": float(n_crossing)}],
        "note": "Lower is better. The weighted interval score needs pairs of levels that add up to 1 (such as 0.05 and 0.95)."})
    tables.append({"key": "quantiles", "title": "Each quantile", "columns": [
        {"key": "level", "label": "Level", "type": "number"}, {"key": "below", "label": "Outcomes at or below", "type": "integer"},
        {"key": "share", "label": "Share", "type": "number"}, {"key": "low", "label": f"{pct} CI low", "type": "number"},
        {"key": "high", "label": f"{pct} CI high", "type": "number"}, {"key": "pinball", "label": "Pinball loss", "type": "number"}],
        "rows": reliability_rows, "note": "A calibrated quantile at level τ has about τ of the outcomes at or below it."})
if coverage_rows:
    tables.append({"key": "coverage", "title": "Central intervals", "columns": [
        {"key": "level", "label": "Promised", "type": "number"}, {"key": "covered", "label": "Covered", "type": "integer"},
        {"key": "coverage", "label": "Coverage", "type": "number"}, {"key": "low", "label": f"{pct} CI low", "type": "number"},
        {"key": "high", "label": f"{pct} CI high", "type": "number"}, {"key": "width", "label": "Mean width", "type": "number"}],
        "rows": coverage_rows, "note": "Wilson intervals for each coverage share."})
summary = (f"{n} predictive distributions ({form}); PIT uniformity χ²({test['df']}) = {test['chi2']:.2f}, {cs.fmt_p(test['p'])}"
           + (f"; CRPS {crps:.4g} (skill {crps_skill:.1%})." if form == "normal" and crps_skill is not None else
              f"; CRPS {crps:.4g}." if form == "normal" else f"; mean pinball loss {mean_pinball:.4g}."))
cs.publish({
    "method": "evaluate.probabilistic",
    "methodVersion": "1.0.0",
    "title": "Score probabilistic predictions",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "statistics": [
        *([{"key": "crps", "label": "CRPS", "value": crps}, {"key": "nll", "label": "Log score", "value": nll}] if form == "normal" else
          [{"key": "mean_pinball", "label": "Mean pinball loss", "value": mean_pinball}, {"key": "wis", "label": "Weighted interval score", "value": wis}]),
        {"key": "pit_chi2", "label": "PIT χ²", "value": test["chi2"]},
        {"key": "pit_p", "label": "p", "value": test["p"], "format": "p"},
    ],
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"PIT categories tested against their expected shares with χ²({test['df']})."],
    "charts": charts,
    "values": values,
})
R

The exact script CodeSplash ran for example “Normal default” · R version 4.5.1 (2025-06-13)

# Score probabilistic predictions
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.probabilistic 1.0.0 · spec b3574198e5795f82
# Dataset: evp_regress (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_eval_crps_normal, cs_eval_nll_normal, cs_eval_pit_bins, cs_eval_pinball, cs_eval_wis, cs_eval_wilson

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

# %% Predictions
yc <- "medv"
mean_col <- "pred_a"
sd_col <- "sd_a"
q_cols <- c()
allowed <- "a mean and an SD column, or quantile columns"
if (length(q_cols) && (!is.null(mean_col) || !is.null(sd_col))) {
  cs_error("CS_E_INVALID_OPTION", option = "Prediction columns", allowed = allowed, value = "both")
}
if (!length(q_cols) && (is.null(mean_col) || is.null(sd_col))) {
  cs_error("CS_E_INVALID_OPTION", option = "Prediction columns", allowed = allowed, value = "a mean or an SD alone")
}
form <- if (length(q_cols)) "quantile" else "normal"
y <- as.numeric(df[[yc]])
n <- length(y)
cs_check_rows(n, 3, "Scoring predictive distributions")
conf <- 0.95
bins <- as.integer(10)
nll <- crps <- crps_ref <- crps_skill <- mean_sd <- mean_pinball <- wis <- NA_real_
cov90 <- c(NA_real_, NA_real_, NA_real_)
n_crossing <- NA
n_levels <- NA
coverage_rows <- list()
reliability_rows <- list()
if (form == "normal") {
  mu <- as.numeric(df[[mean_col]])
  sd <- as.numeric(df[[sd_col]])
  bad <- sum(sd <= 0)
  if (bad > 0) cs_error("CS_E_INVALID_VALUES", column = sd_col, requirement = "a standard deviation above zero", count = bad)
} else {
  levels_text <- "0.05, 0.25, 0.5, 0.75, 0.95"
  taus <- cs_eval_parse_levels(levels_text)
  if (length(taus) != length(q_cols) || any(!(taus > 0 & taus < 1)) || anyDuplicated(taus) > 0) {
    cs_error("CS_E_INVALID_OPTION", option = "Quantile levels",
             allowed = sprintf("%d different levels between 0 and 1, one per quantile column", length(q_cols)), value = levels_text)
  }
  ord <- order(taus, method = "radix")  # columns sorted by level
  taus <- taus[ord]
  q <- do.call(cbind, lapply(q_cols[ord], function(cn) as.numeric(df[[cn]])))
  n_levels <- length(taus)
}

# %% Scores
if (form == "normal") {
  z <- (y - mu) / sd
  nll <- mean(cs_eval_nll_normal(y, mu, sd))
  crps <- mean(cs_eval_crps_normal(y, mu, sd))
  ybar <- mean(y)
  sy <- stats::sd(y)
  if (sy > 0) {
    crps_ref <- mean(cs_eval_crps_normal(y, ybar, sy))  # one normal for every row: the outcome's mean and SD
    crps_skill <- 1 - crps / crps_ref
  }
  mean_sd <- mean(sd)
  pit <- stats::pnorm(z)
  counts <- cs_eval_pit_bins(pit, bins)
  expected <- rep(1 / bins, bins)
  for (lev in c(0.5, 0.8, 0.9, 0.95)) {
    zq <- stats::qnorm((1 + lev) / 2)
    kc <- sum(abs(z) <= zq)
    w <- cs_eval_wilson(kc, n, conf)
    coverage_rows[[length(coverage_rows) + 1]] <- list(level = lev, covered = kc, coverage = kc / n, low = w[1], high = w[2], width = mean(2 * zq * sd))
  }
} else {
  n_crossing <- if (n_levels > 1) sum(apply(q[, -n_levels, drop = FALSE] > q[, -1, drop = FALSE], 1, any)) else 0L
  losses <- vapply(seq_len(n_levels), function(k) mean(cs_eval_pinball(y, q[, k], taus[k])), numeric(1))
  mean_pinball <- mean(losses)
  pairs <- cs_eval_central_pairs(taus)
  if (length(pairs)) wis <- mean(cs_eval_wis(y, q, taus))
  cat <- rowSums(q < y)  # number of quantiles strictly below the outcome
  counts <- tabulate(cat + 1, nbins = n_levels + 1)
  expected <- diff(c(0, taus, 1))
  for (pr in pairs) {
    kc <- sum(q[, pr[1]] <= y & y <= q[, pr[2]])
    w <- cs_eval_wilson(kc, n, conf)
    coverage_rows[[length(coverage_rows) + 1]] <- list(level = 1 - 2 * taus[pr[1]], covered = kc, coverage = kc / n, low = w[1], high = w[2],
                                                       width = mean(q[, pr[2]] - q[, pr[1]]))
  }
  for (k in seq_len(n_levels)) {
    kb <- sum(y <= q[, k])
    w <- cs_eval_wilson(kb, n, conf)
    reliability_rows[[length(reliability_rows) + 1]] <- list(level = taus[k], below = kb, share = kb / n, low = w[1], high = w[2], pinball = losses[k])
  }
}
test <- cs_eval_chisq(counts, expected)
for (r in coverage_rows) if (abs(r$level - 0.9) < 1e-9) cov90 <- c(r$coverage, r$low, r$high)

# %% Assumptions
min_expected <- min(expected * n)
assumptions <- list(
  list(key = "held_out", label = "Predictions were made without these rows", status = "info",
       detail = "Use out-of-fold or test-set predictions: scores on the fitted rows are too good."),
  list(key = "pit_bins", label = "Enough rows per PIT bin", status = if (min_expected >= 5) "pass" else "warn",
       detail = paste0(sprintf("The smallest expected count is %.1f", min_expected),
                       if (min_expected >= 5) "." else "; the χ² test is rough below 5 — use fewer bins."))
)
if (form == "quantile") {
  assumptions[[3]] <- list(key = "quantiles_ordered", label = "Quantiles do not cross", status = if (n_crossing == 0) "pass" else "warn",
                           detail = if (n_crossing == 0) "No row has a higher level with a lower quantile." else
                             sprintf("%d row(s) have crossing quantiles; they are scored as given.", n_crossing))
}

# %% Result
pct <- sprintf("%.0f%%", conf * 100)
values <- list(
  n = n, form = form, n_levels = n_levels, nll = nll, crps = crps, crps_ref = crps_ref, crps_skill = crps_skill,
  mean_sd = mean_sd, mean_pinball = mean_pinball, wis = wis,
  pit_chi2 = test$chi2, pit_df = test$df, pit_p = test$p,
  coverage_90 = cov90[1], coverage_90_low = cov90[2], coverage_90_high = cov90[3], n_crossing = n_crossing
)
rv <- function(rows, k) vapply(rows, function(r) as.numeric(r[[k]]), numeric(1))
charts <- list()
if (form == "normal") {
  charts[[length(charts) + 1]] <- cs_chart("pit", "pit-histogram", sprintf("PIT histogram (%d bins)", bins), list(share = cs_col("Share of rows", counts / n)))
}
if (length(coverage_rows)) {
  charts[[length(charts) + 1]] <- cs_chart("coverage", "interval-coverage", "Central intervals: promised vs observed coverage",
    list(nominal = cs_col("Promised coverage", rv(coverage_rows, "level")), coverage = cs_col("Observed coverage", rv(coverage_rows, "coverage")),
         width = cs_col("Mean width", rv(coverage_rows, "width"))))
}
if (length(reliability_rows)) {
  charts[[length(charts) + 1]] <- cs_chart("quantiles", "calibration", "How often the outcome falls below each quantile",
    list(predicted = cs_col("Quantile level", rv(reliability_rows, "level")), observed = cs_col("Share of outcomes at or below", rv(reliability_rows, "share")),
         n = cs_col("n", rep(n, length(reliability_rows))), low = cs_col("low", rv(reliability_rows, "low")), high = cs_col("high", rv(reliability_rows, "high"))))
}
tables <- list()
if (form == "normal") {
  tables[[1]] <- list(key = "scores", title = "Scores",
                      columns = list(list(key = "score", label = "Score", type = "string"), list(key = "value", label = "Value", type = "number"),
                                     list(key = "reference", label = "Reference forecast", type = "number")),
                      rows = list(
                        list(score = "CRPS (exact, normal)", value = crps, reference = crps_ref),
                        list(score = "CRPS skill (1 − CRPS / reference)", value = crps_skill, reference = NA),
                        list(score = "Log score (negative log-likelihood)", value = nll, reference = NA),
                        list(score = "Mean predicted SD (sharpness)", value = mean_sd, reference = NA)),
                      note = "The reference forecast is one normal for every row, with the outcome's mean and SD. Lower CRPS and log score are better.")
} else {
  tables[[1]] <- list(key = "scores", title = "Scores",
                      columns = list(list(key = "score", label = "Score", type = "string"), list(key = "value", label = "Value", type = "number")),
                      rows = list(
                        list(score = "Mean pinball loss", value = mean_pinball),
                        list(score = "Weighted interval score", value = wis),
                        list(score = "Rows with crossing quantiles", value = as.numeric(n_crossing))),
                      note = "Lower is better. The weighted interval score needs pairs of levels that add up to 1 (such as 0.05 and 0.95).")
  tables[[2]] <- list(key = "quantiles", title = "Each quantile",
                      columns = list(list(key = "level", label = "Level", type = "number"), list(key = "below", label = "Outcomes at or below", type = "integer"),
                                     list(key = "share", label = "Share", type = "number"), list(key = "low", label = sprintf("%s CI low", pct), type = "number"),
                                     list(key = "high", label = sprintf("%s CI high", pct), type = "number"), list(key = "pinball", label = "Pinball loss", type = "number")),
                      rows = reliability_rows, note = "A calibrated quantile at level τ has about τ of the outcomes at or below it.")
}
if (length(coverage_rows)) {
  tables[[length(tables) + 1]] <- list(key = "coverage", title = "Central intervals",
                                       columns = list(list(key = "level", label = "Promised", type = "number"), list(key = "covered", label = "Covered", type = "integer"),
                                                      list(key = "coverage", label = "Coverage", type = "number"), list(key = "low", label = sprintf("%s CI low", pct), type = "number"),
                                                      list(key = "high", label = sprintf("%s CI high", pct), type = "number"), list(key = "width", label = "Mean width", type = "number")),
                                       rows = coverage_rows, note = "Wilson intervals for each coverage share.")
}
summary <- paste0(sprintf("%d predictive distributions (%s); PIT uniformity χ²(%d) = %.2f, %s", n, form, test$df, test$chi2, cs_fmt_p(test$p)),
                  if (form == "normal" && !is.na(crps_skill)) sprintf("; CRPS %.4g (skill %.1f%%).", crps, 100 * crps_skill) else
                    if (form == "normal") sprintf("; CRPS %.4g.", crps) else sprintf("; mean pinball loss %.4g.", mean_pinball))
stats_rows <- if (form == "normal") list(list(key = "crps", label = "CRPS", value = crps), list(key = "nll", label = "Log score", value = nll)) else
  list(list(key = "mean_pinball", label = "Mean pinball loss", value = mean_pinball), list(key = "wis", label = "Weighted interval score", value = wis))
cs_publish(list(
  method = "evaluate.probabilistic",
  methodVersion = "1.0.0",
  title = "Score probabilistic predictions",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  statistics = c(stats_rows, list(
    list(key = "pit_chi2", label = "PIT χ²", value = test$chi2),
    list(key = "pit_p", label = "p", value = test$p, format = "p")
  )),
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("PIT categories tested against their expected shares with χ²(%d).", test$df)),
  charts = charts,
  values = values
))

Sources

  • Gneiting, T., & Raftery, A. E. (2007). Strictly proper scoring rules, prediction, and estimation. Journal of the American Statistical Association, 102, 359–378.
  • Gneiting, T., Raftery, A. E., Westveld, A. H., & Goldman, T. (2005). Calibrated probabilistic forecasting using ensemble model output statistics and minimum CRPS estimation. Monthly Weather Review, 133, 1098–1118.
  • Gneiting, T., Balabdaoui, F., & Raftery, A. E. (2007). Probabilistic forecasts, calibration and sharpness. Journal of the Royal Statistical Society B, 69, 243–268.
  • Bracher, J., Ray, E. L., Gneiting, T., & Reich, N. G. (2021). Evaluating epidemic forecasts in an interval format. PLOS Computational Biology, 17, e1008618.

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