Skip to content

HEvaluate predictions · evaluate.paired_metric

Compare two models' predictions

Do two models' predictions of the same rows differ on a chosen metric, and by how much?

Scores two prediction columns against the same outcome on one metric (MAE, RMSE, MSE or R² for a numeric outcome; AUC, Brier score, log loss or accuracy for a two-level outcome) and estimates the difference with a paired bootstrap interval. The test flips the sign of each row's loss difference (whole clusters together when a cluster column is set); AUC uses DeLong's paired test.

Verified in Python and R Python and R agree to 6 decimals Seeded

A real result

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

Compare two models' predictionsRecorded · Python and R agreeRecorded 2026-11-17 · 20 values compared
R

RMSE: A 5.05, B 5.592; A − B = -0.5414 (95% CI -0.7563 to -0.3472), p < .001 (sign-flip permutation of squared errors). Model A is better on RMSE.

RMSE, model A
5.050
RMSE, model B
5.592
Difference A − B
−0.5414
p
< .001

Plots

RMSE of each model (95% bootstrap intervals)Do a model's decisions or error rates differ across groups, and by how much?
View data
ModelhighlowMetricRMSE
A: pred_a5.6894.452RMSE5.050
B: pred_b6.1755.030RMSE5.592
Bootstrap differences in RMSE (A − B)How is one numeric variable distributed?
View data
RMSE: A − B
−0.6168
−0.5475
−0.5246
−0.6838
−0.3967
−0.5642
−0.6365
−0.4658
−0.4068
−0.6365
−0.5742
−0.5878
−0.6428
−0.4561
−0.5369
−0.4827
−0.5010
−0.4649
−0.5459
−0.5748
−0.4326
−0.5478
−0.5055
−0.4027
−0.5399
−0.4903
−0.5914
−0.7070
−0.4350
−0.6255
−0.5571
−0.4862
−0.4358
−0.4977
−0.6330
−0.5601
−0.5363
−0.3968
−0.4905
−0.5941
−0.5060
−0.4024
−0.5336
−0.5897
−0.5312
−0.6637
−0.3641
−0.6738
−0.5318
−0.7320
−0.5696
−0.3673
−0.5512
−0.6663
−0.6047
−0.4344
−0.5765
−0.5542
−0.5773
−0.4679

First 60 of 2000 rows.

Assumptions

  • Both models scored the same rows — 506 rows scored by both models. Use out-of-fold or held-out predictions: scores on the training rows flatter both models.
  • Rows or clusters are independent — Rows are resampled one at a time; repeated measurements of the same unit need a cluster column.
  • Enough rows — 506 rows.

RMSE of each model

ModelColumnRMSE95% CI low95% CI high
Apred_a5.0504.4525.689
Bpred_b5.5925.0306.175
A − B−0.5414−0.7563−0.3472

Percentile intervals from 2000 paired bootstrap resamples. Lower is better.

  • Bootstrap SE of the difference 0.1042. Model A does better on 58.3% of rows (ties count half).
Python

RMSE: A 5.05, B 5.592; A − B = -0.5414 (95% CI -0.7563 to -0.3472), p < .001 (sign-flip permutation of squared errors). Model A is better on RMSE.

RMSE, model A
5.050
RMSE, model B
5.592
Difference A − B
−0.5414
p
< .001

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

Assumptions

  • Both models scored the same rows — 506 rows scored by both models. Use out-of-fold or held-out predictions: scores on the training rows flatter both models.
  • Rows or clusters are independent — Rows are resampled one at a time; repeated measurements of the same unit need a cluster column.
  • Enough rows — 506 rows.

RMSE of each model

ModelColumnRMSE95% CI low95% CI high
Apred_a5.0504.4525.689
Bpred_b5.5925.0306.175
A − B−0.5414−0.7563−0.3472

Percentile intervals from 2000 paired bootstrap resamples. Lower is better.

  • Bootstrap SE of the difference 0.1042. Model A does better on 58.3% of rows (ties count half).

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

  • Regression rmseevp_regress · outcome: medv · pred_a: pred_a · pred_b: pred_b
  • Regression mae clusterevp_regress · cluster: town · outcome: medv · pred_a: pred_a · pred_b: pred_b
  • Regression r2 missingevp_regress · outcome: medv · pred_a: pred_a · pred_b: pred_b_gaps
  • Binary aucs5_risk · outcome: diabetic · pred_a: risk score · pred_b: p_base
  • Binary briers5_risk · outcome: type · pred_a: p_overfit · pred_b: p_base
  • Binary log losss5_risk · outcome: diabetic · pred_a: risk score · pred_b: p_base
  • Binary accuracys5_risk · outcome: diabetic · pred_a: risk score · pred_b: p_overfit
  • Identical modelsevp_regress · outcome: medv · pred_a: pred_b · pred_b: pred_b

In the guides

Where it sits in the decision guides

  • Robust, permutation and exact methods · Statistics Guide · Step 3 — If assumptions are violated
  • Bootstrap · Statistics Guide · Step 3 — If assumptions are violated
  • 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 MAE, RMSE, MSE and R²; two levels for AUC, Brier score, log loss and accuracy.
Model A predictionsnumeric · 1 column
The first model's prediction for each row (for a two-level outcome, its predicted probability of the event).
Model B predictionsnumeric · 1 column
The second model's prediction for the same rows, on the same scale as model A.
Resampling cluster (optional)categorical · 0–1 column
Rows that belong together (a patient, store or day). Whole clusters are resampled and flipped together, so the interval respects the grouping.

Choices you make

hypothesis

Metricdefault auto

The yardstick both models are scored on. Automatic uses RMSE for a numeric outcome and AUC for a two-level outcome.

  • Automatic(default) — RMSE for a numeric outcome, AUC for a two-level outcome.
  • Mean absolute error (MAE) — Average size of the errors, in the outcome's units; lower is better.
  • Root mean squared error (RMSE) — Like MAE but large errors count more; lower is better.
  • Mean squared error (MSE) — The square of RMSE; lower is better.
  • R² (share of variance explained) — 1 minus squared error over the outcome's spread; higher is better.
  • AUC (area under the ROC curve) — How well the scores rank events above non-events; higher is better.
  • Brier score — Mean squared difference between predicted probability and outcome; lower is better.
  • Log loss — Penalizes confident wrong probabilities heavily; lower is better.
  • Accuracy at a threshold — Share of rows classified correctly when p ≥ the threshold means event; higher is better.
Event leveldefault —

The outcome level the predicted probabilities refer to (default the last stored level — true for true/false columns).

Classification thresholddefault 0.5

A predicted probability at or above this counts as the event.

Confidence leveldefault 0.95

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

statistics

Resamples and permutationsdefault 2000

Bootstrap resamples for the intervals and sign flips for the test; more gives steadier interval ends.

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.

  • Both models scored the same rows

    Each row is one case predicted by both models, never seen by either during training (out-of-fold or held-out predictions).

  • Rows or clusters are independent

    Resampling treats rows as independent unless a cluster column groups them; repeated measurements need the cluster column.

  • Enough rows

    With fewer than 30 rows (or 10 clusters) bootstrap intervals are rough; the AUC also needs at least 10 events and 10 non-events.

What it reports

  • Tests: The two models' metric differs
n
The rows both models scored after rows with a missing outcome or prediction were removed.
n_clusters
How many clusters the bootstrap and the sign flips resampled whole; empty when rows were resampled one at a time.
metric
The metric both models were scored on (mae, rmse, mse, r2, auc, brier, log_loss or accuracy) and its name in words.
metric_label
The metric both models were scored on (mae, rmse, mse, r2, auc, brier, log_loss or accuracy) and its name in words.
lower_is_better
True for losses (MAE, RMSE, MSE, Brier score, log loss); false for AUC, R² and accuracy, where higher is better.
positive_level
The outcome level the predicted probabilities refer to; empty for a numeric outcome.
metric_a
Model A's score on all compared rows, with a percentile bootstrap interval from the same paired resamples.
metric_a_low
Model A's score on all compared rows, with a percentile bootstrap interval from the same paired resamples.
metric_a_high
Model A's score on all compared rows, with a percentile bootstrap interval from the same paired resamples.
metric_b
Model B's score on the same rows, with a percentile bootstrap interval from the same paired resamples.
metric_b_low
Model B's score on the same rows, with a percentile bootstrap interval from the same paired resamples.
metric_b_high
Model B's score on the same rows, with a percentile bootstrap interval from the same paired resamples.
diff
Model A's metric minus model B's, with a paired percentile bootstrap interval. Read the sign with 'lower is better'.
diff_low
Model A's metric minus model B's, with a paired percentile bootstrap interval. Read the sign with 'lower is better'.
diff_high
Model A's metric minus model B's, with a paired percentile bootstrap interval. Read the sign with 'lower is better'.
boot_se
The standard deviation of the difference across the paired bootstrap resamples.
p_value
From flipping the sign of each row's (or cluster's) loss difference; for AUC, DeLong's paired test or a bootstrap z test.
p_method
From flipping the sign of each row's (or cluster's) loss difference; for AUC, DeLong's paired test or a bootstrap z test.
row_win_a
How often model A's row loss beats B's (ties count half). Empty for AUC, which is not a row-by-row score.
reps_used
Bootstrap resamples with a defined value; an AUC resample with only one outcome class is left out.

Python and R

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

Default traps between the two languages

  • Bootstrap and sign-flip draws come from the shared Wichmann–Hill stream, so both engines resample the same rows; replicate sums can differ in the last bits (summation order), which moves the interval ends by about 1e-12.
Python

The exact script CodeSplash ran for example “Regression rmse” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

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

# %% Setup
import math

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

import codesplash as cs
from codesplash.errors import check_groups, check_not_constant, check_rows
from codesplash.evaluate import paired as pm  # paired bootstrap and sign flips (twin: codesplashr cs_eval_paired_*)
from codesplash.stats import roc  # DeLong's paired AUC test (twin: cs_delong_paired)

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

# %% Predictions
yc, ac, bc = "medv", "pred_a", "pred_b"
binary = False
metric = "auto"
if metric == "auto":
    metric = "auc" if binary else "rmse"  # the usual yardstick for each kind of outcome
if binary and metric in pm.NUMERIC:
    cs.cs_error("CS_E_INVALID_OPTION", option="Metric", allowed="AUC, Brier score, log loss or accuracy for a two-level outcome", value=metric)
if not binary and metric in pm.BINARY:
    cs.cs_error("CS_E_INVALID_OPTION", option="Metric", allowed="MAE, RMSE, MSE or R² for a numeric outcome", value=metric)
event = None
if binary:
    present = [str(v) for v in df[yc].cat.categories]  # levels with data, in stored order
    check_groups(df[yc], yc, minimum=2, exactly=2)
    event = present[-1]  # default: the last level ("true")
    y = (df[yc].astype(str) == event).to_numpy().astype(float)
else:
    y = df[yc].to_numpy(dtype=float)
pa = df[ac].to_numpy(dtype=float)
pb = df[bc].to_numpy(dtype=float)
n = int(y.size)
check_rows(n, 3, "A paired comparison")
if metric == "r2":
    check_not_constant(y, yc)  # R² divides by the outcome's spread
if metric in ("brier", "log_loss"):
    for c, v in ((ac, pa), (bc, pb)):
        bad = int(np.sum((v < 0) | (v > 1)))
        if bad:
            cs.cs_error("CS_E_INVALID_VALUES", column=c, requirement="a probability between 0 and 1", count=bad)
cc, codes, g = None, None, n
threshold = 0.5
reps = int(2000)
conf = 0.95
seed = 42  # portable Wichmann–Hill streams: R draws the same resamples and flips

# %% Metric
la = pm.row_losses(metric, y, pa, threshold)  # per-row loss (accuracy: 1 = correct); None for AUC
lb = pm.row_losses(metric, y, pb, threshold)
yc0 = y - y.mean()  # R² sums use the centered outcome (exact for any shift, and stable)
if metric == "auc":
    ma, mb = pm.auc(y, pa), pm.auc(y, pb)
else:
    ma = float(pm.from_sums(metric, la.sum(), n, yc0.sum(), (yc0 * yc0).sum()))
    mb = float(pm.from_sums(metric, lb.sum(), n, yc0.sum(), (yc0 * yc0).sum()))
diff = ma - mb

# %% Paired bootstrap
boot = pm.bootstrap(metric, y, pa, pb, codes, g, reps, seed, threshold)  # replicate values of A, B and A − B
valid = ~np.isnan(boot["diff"])
reps_used = int(valid.sum())
diff_low, diff_high = pm.percentile(boot["diff"], conf)
a_low, a_high = pm.percentile(boot["a"], conf)
b_low, b_high = pm.percentile(boot["b"], conf)
boot_se = float(np.std(boot["diff"][valid], ddof=1)) if reps_used >= 2 else math.nan

# %% Test
if metric == "auc":
    if codes is None:
        dl = roc.delong_paired(pa[y == 1], pa[y == 0], pb[y == 1], pb[y == 0], conf)
        p_value, p_method = dl["p"], "DeLong's paired test"
    else:
        z = diff / boot_se if boot_se > 0 else math.nan
        p_value = float(2 * stats.norm.sf(abs(z))) if boot_se > 0 else math.nan
        p_method = "bootstrap z test over clusters"
    row_win = None
else:
    d = la - lb
    du = np.bincount(codes, weights=d, minlength=g) if codes is not None else d
    p_value = pm.sign_flip(du, n, reps, seed + 1)["p"]
    p_method = "sign-flip permutation" + (" of squared errors" if metric in ("rmse", "mse", "r2") else "") + (" over clusters" if codes is not None else "")
    row_win = pm.row_win_share(metric, la, lb)

# %% Assumptions
lower = pm.LOWER_IS_BETTER[metric]
label = pm.LABELS[metric]
n_events = int(y.sum()) if binary else None
small = n < 30 or (codes is not None and g < 10) or (metric == "auc" and min(n_events, n - n_events) < 10)
assumptions = [
    {"key": "paired", "label": "Both models scored the same rows", "status": "info",
     "detail": f"{n} rows scored by both models. Use out-of-fold or held-out predictions: scores on the training rows flatter both models."},
    {"key": "independence", "label": "Rows or clusters are independent", "status": "info",
     "detail": (f"Whole clusters of {cc} are resampled ({g} clusters)." if codes is not None
                else "Rows are resampled one at a time; repeated measurements of the same unit need a cluster column.")},
    {"key": "sample_size", "label": "Enough rows", "status": "warn" if small else "pass",
     "detail": (f"{n} rows" + (f", {g} clusters" if codes is not None else "") + (f", {n_events} events" if binary else "")
                + ("; intervals are rough with this few." if small else "."))},
]
if reps_used < reps:
    warnings.append(f"{reps - reps_used} resamples had only one outcome class (AUC undefined) and were left out.")
better = None if diff == 0 or math.isnan(diff) else ("A" if (diff < 0) == lower else "B")

# %% Result
pct = f"{conf:.0%}"
values = {
    "n": n, "n_clusters": g if codes is not None else None, "metric": metric, "metric_label": label,
    "lower_is_better": lower, "positive_level": event,
    "metric_a": ma, "metric_a_low": a_low, "metric_a_high": a_high,
    "metric_b": mb, "metric_b_low": b_low, "metric_b_high": b_high,
    "diff": diff, "diff_low": diff_low, "diff_high": diff_high, "boot_se": boot_se,
    "p_value": p_value, "p_method": p_method, "row_win_a": row_win, "reps_used": reps_used,
}
charts = [
    cs.chart("models", "group-metrics", f"{label} of each model ({pct} bootstrap intervals)", {
        "group": cs.col("Model", [f"A: {ac}", f"B: {bc}"], "categorical"),
        "metric": cs.col("Metric", [label, label], "categorical"),
        "value": cs.col(label, [ma, mb]), "low": cs.col("low", [a_low, b_low]), "high": cs.col("high", [a_high, b_high])},
        controls={"reference": None, "band_low": 0, "band_high": 0}),
    cs.chart("differences", "histogram", f"Bootstrap differences in {label} (A − B)", {
        "x": cs.col(f"{label}: A − B", boot["diff"][valid])}),
]
verdict = ("Neither model is better at this sample size." if not (p_value < 1 - conf)
           else f"Model {better} is better on {label}.")
summary = (f"{label}: A {ma:.4g}, B {mb:.4g}; A − B = {diff:.4g} ({pct} CI {diff_low:.4g} to {diff_high:.4g}), "
           f"{cs.fmt_p(p_value)} ({p_method}). {verdict}")
cs.publish({
    "method": "evaluate.paired_metric",
    "methodVersion": "1.0.0",
    "title": "Compare two models' predictions",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "statistics": [
        {"key": "metric_a", "label": f"{label}, model A", "value": ma},
        {"key": "metric_b", "label": f"{label}, model B", "value": mb},
        {"key": "diff", "label": "Difference A − B", "value": diff},
        {"key": "p_value", "label": "p", "value": p_value, "format": "p"},
    ],
    "tables": [
        {"key": "comparison", "title": f"{label} of each model", "columns": [
            {"key": "model", "label": "Model", "type": "string"}, {"key": "column", "label": "Column", "type": "string"},
            {"key": "value", "label": label, "type": "number"},
            {"key": "low", "label": f"{pct} CI low", "type": "number"}, {"key": "high", "label": f"{pct} CI high", "type": "number"}],
         "rows": [
            {"model": "A", "column": ac, "value": ma, "low": a_low, "high": a_high},
            {"model": "B", "column": bc, "value": mb, "low": b_low, "high": b_high},
            {"model": "A − B", "column": "", "value": diff, "low": diff_low, "high": diff_high}],
         "note": f"Percentile intervals from {reps_used} paired bootstrap resamples" + (f" of whole clusters ({cc})." if codes is not None else ".")
                 + (" Lower is better." if lower else " Higher is better.")},
    ],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [
        f"Bootstrap SE of the difference {boot_se:.4g}." + (f" Model A does better on {row_win:.1%} of rows (ties count half)." if row_win is not None else ""),
        *([f"Event: {yc} = {event}."] if binary else []),
    ],
    "charts": charts,
    "values": values,
})
R

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

# Compare two models' predictions
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.paired_metric 1.0.0 · spec 887d286cb16f0390
# Dataset: evp_regress (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_eval_paired_* (paired bootstrap, sign flips), cs_delong_paired

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

# %% Predictions
yc <- "medv"
ac <- "pred_a"
bc <- "pred_b"
binary <- FALSE
metric <- "auto"
if (metric == "auto") metric <- if (binary) "auc" else "rmse"  # the usual yardstick for each kind of outcome
if (binary && metric %in% c("mae", "rmse", "mse", "r2")) {
  cs_error("CS_E_INVALID_OPTION", option = "Metric", allowed = "AUC, Brier score, log loss or accuracy for a two-level outcome", value = metric)
}
if (!binary && metric %in% c("auc", "brier", "log_loss", "accuracy")) {
  cs_error("CS_E_INVALID_OPTION", option = "Metric", allowed = "MAE, RMSE, MSE or R² for a numeric outcome", value = metric)
}
event <- NA_character_
if (binary) {
  present <- levels(df[[yc]])  # levels with data, in stored order
  cs_check_groups(df[[yc]], yc, minimum = 2, exactly = 2)
  event <- present[length(present)]  # default: the last level ("true")
  y <- as.numeric(as.character(df[[yc]]) == event)
} else {
  y <- as.numeric(df[[yc]])
}
pa <- as.numeric(df[[ac]])
pb <- as.numeric(df[[bc]])
n <- length(y)
cs_check_rows(n, 3, "A paired comparison")
if (metric == "r2") cs_check_not_constant(y, yc)  # R2 divides by the outcome's spread
if (metric %in% c("brier", "log_loss")) {
  for (cv in list(list(ac, pa), list(bc, pb))) {
    bad <- sum(cv[[2]] < 0 | cv[[2]] > 1)
    if (bad > 0) cs_error("CS_E_INVALID_VALUES", column = cv[[1]], requirement = "a probability between 0 and 1", count = bad)
  }
}
cc <- NULL
codes <- NULL
g <- n
threshold <- 0.5
reps <- as.integer(2000)
conf <- 0.95
seed <- 42  # portable Wichmann-Hill streams: Python draws the same resamples and flips

# %% Metric
la <- cs_eval_paired_losses(metric, y, pa, threshold)  # per-row loss (accuracy: 1 = correct); NULL for AUC
lb <- cs_eval_paired_losses(metric, y, pb, threshold)
yc0 <- y - mean(y)  # R2 sums use the centered outcome (exact for any shift, and stable)
if (metric == "auc") {
  ma <- cs_eval_auc(y, pa)
  mb <- cs_eval_auc(y, pb)
} else {
  ma <- cs_eval_paired_from_sums(metric, sum(la), n, sum(yc0), sum(yc0 * yc0))
  mb <- cs_eval_paired_from_sums(metric, sum(lb), n, sum(yc0), sum(yc0 * yc0))
}
diff <- ma - mb

# %% Paired bootstrap
boot <- cs_eval_paired_bootstrap(metric, y, pa, pb, codes, g, reps, seed, threshold)  # replicate values of A, B and A - B
valid <- !is.na(boot$diff)
reps_used <- sum(valid)
dci <- cs_eval_percentile(boot$diff, conf)
aci <- cs_eval_percentile(boot$a, conf)
bci <- cs_eval_percentile(boot$b, conf)
boot_se <- if (reps_used >= 2) stats::sd(boot$diff[valid]) else NaN

# %% Test
row_win <- NA_real_
if (metric == "auc") {
  if (is.null(codes)) {
    dl <- cs_delong_paired(pa[y == 1], pa[y == 0], pb[y == 1], pb[y == 0], conf)
    p_value <- dl$p
    p_method <- "DeLong's paired test"
  } else {
    p_value <- if (isTRUE(boot_se > 0)) 2 * stats::pnorm(-abs(diff / boot_se)) else NaN
    p_method <- "bootstrap z test over clusters"
  }
} else {
  d <- la - lb
  du <- if (is.null(codes)) d else as.numeric(vapply(split(d, factor(codes, levels = seq_len(g))), sum, numeric(1)))
  p_value <- cs_eval_sign_flip(du, n, reps, seed + 1)$p
  p_method <- paste0("sign-flip permutation", if (metric %in% c("rmse", "mse", "r2")) " of squared errors" else "",
                     if (!is.null(codes)) " over clusters" else "")
  row_win <- cs_eval_row_win_share(metric, la, lb)
}

# %% Assumptions
lower <- cs_eval_paired_lower_is_better[[metric]]
label <- cs_eval_paired_labels[[metric]]
n_events <- if (binary) sum(y) else NA
small <- n < 30 || (!is.null(codes) && g < 10) || (metric == "auc" && min(n_events, n - n_events) < 10)
assumptions <- list(
  list(key = "paired", label = "Both models scored the same rows", status = "info",
       detail = sprintf("%d rows scored by both models. Use out-of-fold or held-out predictions: scores on the training rows flatter both models.", n)),
  list(key = "independence", label = "Rows or clusters are independent", status = "info",
       detail = if (!is.null(codes)) sprintf("Whole clusters of %s are resampled (%d clusters).", cc, g) else
         "Rows are resampled one at a time; repeated measurements of the same unit need a cluster column."),
  list(key = "sample_size", label = "Enough rows", status = if (small) "warn" else "pass",
       detail = paste0(sprintf("%d rows", n), if (!is.null(codes)) sprintf(", %d clusters", g) else "",
                       if (binary) sprintf(", %d events", n_events) else "",
                       if (small) "; intervals are rough with this few." else "."))
)
if (reps_used < reps) warnings <- c(warnings, sprintf("%d resamples had only one outcome class (AUC undefined) and were left out.", reps - reps_used))
better <- if (is.na(diff) || diff == 0) NA_character_ else if ((diff < 0) == lower) "A" else "B"

# %% Result
pct <- sprintf("%.0f%%", conf * 100)
values <- list(
  n = n, n_clusters = if (!is.null(codes)) g else NA, metric = metric, metric_label = label,
  lower_is_better = lower, positive_level = event,
  metric_a = ma, metric_a_low = aci[1], metric_a_high = aci[2],
  metric_b = mb, metric_b_low = bci[1], metric_b_high = bci[2],
  diff = diff, diff_low = dci[1], diff_high = dci[2], boot_se = boot_se,
  p_value = p_value, p_method = p_method, row_win_a = row_win, reps_used = reps_used
)
charts <- list(
  cs_chart("models", "group-metrics", sprintf("%s of each model (%s bootstrap intervals)", label, pct),
           list(group = cs_col("Model", c(paste0("A: ", ac), paste0("B: ", bc)), "categorical"),
                metric = cs_col("Metric", c(label, label), "categorical"),
                value = cs_col(label, c(ma, mb)), low = cs_col("low", c(aci[1], bci[1])), high = cs_col("high", c(aci[2], bci[2]))),
           controls = list(reference = NA, band_low = 0, band_high = 0)),
  cs_chart("differences", "histogram", sprintf("Bootstrap differences in %s (A − B)", label),
           list(x = cs_col(sprintf("%s: A − B", label), boot$diff[valid])))
)
verdict <- if (!isTRUE(p_value < 1 - conf)) "Neither model is better at this sample size." else sprintf("Model %s is better on %s.", better, label)
summary <- sprintf("%s: A %.4g, B %.4g; A − B = %.4g (%s CI %.4g to %.4g), %s (%s). %s",
                   label, ma, mb, diff, pct, dci[1], dci[2], cs_fmt_p(p_value), p_method, verdict)
notes <- list(paste0(sprintf("Bootstrap SE of the difference %.4g.", boot_se),
                     if (!is.na(row_win)) sprintf(" Model A does better on %.1f%% of rows (ties count half).", 100 * row_win) else ""))
if (binary) notes[[length(notes) + 1]] <- sprintf("Event: %s = %s.", yc, event)
cs_publish(list(
  method = "evaluate.paired_metric",
  methodVersion = "1.0.0",
  title = "Compare two models' predictions",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  statistics = list(
    list(key = "metric_a", label = paste0(label, ", model A"), value = ma),
    list(key = "metric_b", label = paste0(label, ", model B"), value = mb),
    list(key = "diff", label = "Difference A − B", value = diff),
    list(key = "p_value", label = "p", value = p_value, format = "p")
  ),
  tables = list(
    list(key = "comparison", title = paste0(label, " of each model"),
         columns = list(list(key = "model", label = "Model", type = "string"), list(key = "column", label = "Column", type = "string"),
                        list(key = "value", label = label, type = "number"),
                        list(key = "low", label = sprintf("%s CI low", pct), type = "number"), list(key = "high", label = sprintf("%s CI high", pct), type = "number")),
         rows = list(
           list(model = "A", column = ac, value = ma, low = aci[1], high = aci[2]),
           list(model = "B", column = bc, value = mb, low = bci[1], high = bci[2]),
           list(model = "A − B", column = "", value = diff, low = dci[1], high = dci[2])),
         note = paste0(sprintf("Percentile intervals from %d paired bootstrap resamples", reps_used),
                       if (!is.null(codes)) sprintf(" of whole clusters (%s).", cc) else ".",
                       if (lower) " Lower is better." else " Higher is better."))
  ),
  assumptions = assumptions,
  warnings = warnings,
  notes = notes,
  charts = charts,
  values = values
))

Sources

  • Efron, B., & Tibshirani, R. J. (1993). An Introduction to the Bootstrap. Chapman & Hall.
  • DeLong, E. R., DeLong, D. M., & Clarke-Pearson, D. L. (1988). Comparing the areas under two or more correlated receiver operating characteristic curves: a nonparametric approach. Biometrics, 44, 837–845.
  • Field, C. A., & Welsh, A. H. (2007). Bootstrapping clustered data. Journal of the Royal Statistical Society B, 69, 369–390.
  • Good, P. (2005). Permutation, Parametric and Bootstrap Tests of Hypotheses (3rd ed.). Springer.

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