Paired comparisons: bootstrap and sign flips on the right unit
Two models scored on the same cases should be compared case by case. Resample the independent units, not rows inside them, recompute the metric on each resample, and calibrate the p-value with sign flips the design justifies.
What runs in CodeSplash
- EVA053Paired bootstrap for model-comparison uncertainty Runs in CodeSplash
- EVA054Paired randomization and permutation tests Runs in CodeSplash
- Compare two models' predictions Verified in Python and R
- Paired t-test Verified in Python and R
You will be able to
- Build a paired bootstrap interval for a difference in a metric
- Choose the resampling unit from the design, and set it in the app
- Run an exact or Monte Carlo sign-flip test and say what it assumes
- Keep fold, seed and test-unit variation apart
Pair first
ReadWhen models A and B predict the same cases, hard cases are hard for both. Comparing their two averages as if they came from separate samples throws that away. Pair them: compute each case's difference in loss, or recompute the metric for A and B on the same resampled cases, and reason about the difference directly.
That covers two reference entries: the paired bootstrap for an interval, and paired randomization for a p-value.
The paired bootstrap
ReadDraw the evaluation units with replacement, recompute the metric for both models on the same draw, and keep the difference:
Recompute nonlinear metrics on each resample (an AUC or a corpus-level WER can't be averaged from per-case pieces). In the reference's five-difference example, Python's 95% percentile interval runs from 0.020 to 0.166; R's, drawn with a different generator, from 0.026 to 0.166. Same method, different draws: bootstrap ends wobble, so report the number of resamples.
Reference · EVA053 · Runs in CodeSplashPaired bootstrap for model-comparison uncertaintyQuantifies sampling uncertainty in a difference between systems evaluated on the same units.HExplorable · Comparing two models on the same test set
Model B scores a little worse than model A on the same examples. Is the gap real, and how sure can you be?
Which 95% interval for B − A will be narrower: resampling the examples in pairs, or resampling each model's losses separately?
Examples both models are scored on.
How much worse B is on average, in loss units.
Hard examples are hard for both models: this shared part cancels in the paired difference.
Loss variation that differs between the two models.
Bootstrap resamples, and sign-flip permutations.
Resample
Paired resamples examples and keeps both models' losses together.
Points hug the diagonal when examples are hard or easy for both models: that shared part cancels in each example's difference, which is why the paired distribution (blue) is narrower than the unpaired one (orange). Correlation 0.93.
Commit your prediction above to see the result
Make your prediction to see the result.
Resample the unit, not the row
ExploreMAE: A 3.543, B 3.991; A − B = -0.4486 (90% CI -0.6599 to -0.2281), p = .004 (sign-flip permutation over clusters). Model A is better on MAE.
- MAE, model A
- 3.543
- MAE, model B
- 3.991
- Difference A − B
- −0.4486
- p
- .004
Plots
View data
| Model | high | low | Metric | MAE |
|---|---|---|---|---|
| A: pred_a | 3.946 | 3.142 | MAE | 3.543 |
| B: pred_b | 4.439 | 3.554 | MAE | 3.991 |
View data
| MAE: A − B |
|---|
| −0.7370 |
| −0.4434 |
| −0.3340 |
| −0.4490 |
| −0.6824 |
| −0.3165 |
| −0.3236 |
| −0.4541 |
| −0.5806 |
| −0.5967 |
| −0.5128 |
| −0.2500 |
| −0.3213 |
| −0.5625 |
| −0.6272 |
| −0.5985 |
| −0.4906 |
| −0.5457 |
| −0.2724 |
| −0.4782 |
| −0.5559 |
| −0.6556 |
| −0.5466 |
| −0.5979 |
| −0.4610 |
| −0.3299 |
| −0.6002 |
| −0.5359 |
| −0.4909 |
| −0.4595 |
| −0.4259 |
| −0.6061 |
| −0.2462 |
| −0.5175 |
| −0.5181 |
| −0.4447 |
| −0.2813 |
| −0.5088 |
| −0.5181 |
| −0.5196 |
| −0.5276 |
| −0.4206 |
| −0.3780 |
| −0.4303 |
| −0.1181 |
| −0.7226 |
| −0.2616 |
| −0.3014 |
| −0.4783 |
| −0.4429 |
| −0.3909 |
| −0.3115 |
| −0.5169 |
| −0.3607 |
| −0.6447 |
| −0.7837 |
| −0.4696 |
| −0.5197 |
| −0.5253 |
| −0.4655 |
First 60 of 1000 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 — Whole clusters of town are resampled (85 clusters).
- Enough rows — 506 rows, 85 clusters.
MAE of each model
| Model | Column | MAE | 90% CI low | 90% CI high |
|---|---|---|---|---|
| A | pred_a | 3.543 | 3.142 | 3.946 |
| B | pred_b | 3.991 | 3.554 | 4.439 |
| A − B | −0.4486 | −0.6599 | −0.2281 |
Percentile intervals from 1000 paired bootstrap resamples of whole clusters (town). Lower is better.
- Bootstrap SE of the difference 0.1333. Model A does better on 58.3% of rows (ties count half).
The exact R script · R R version 4.5.1 (2025-06-13)
# Compare two models' predictions
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.paired_metric 1.0.0 · spec 434a1a8999cf23a6
# 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", "town")))
n_input <- nrow(df)
df[["town"]] <- factor(df[["town"]], levels = c("t001", "t002", "t003", "t004", "t005", "t006", "t007", "t008", "t009", "t010", "t011", "t012", "t013", "t014", "t015", "t016", "t017", "t018", "t019", "t020", "t021", "t022", "t023", "t024", "t025", "t026", "t027", "t028", "t029", "t030", "t031", "t032", "t033", "t034", "t035", "t036", "t037", "t038", "t039", "t040", "t041", "t042", "t043", "t044", "t045", "t046", "t047", "t048", "t049", "t050", "t051", "t052", "t053", "t054", "t055", "t056", "t057", "t058", "t059", "t060", "t061", "t062", "t063", "t064", "t065", "t066", "t067", "t068", "t069", "t070", "t071", "t072", "t073", "t074", "t075", "t076", "t077", "t078", "t079", "t080", "t081", "t082", "t083", "t084", "t085")) # stored level order
df <- df[stats::complete.cases(df[c("medv", "pred_a", "pred_b", "town")]), , 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", "town")) # infinite values stop the run (registry/errors.yaml)
# %% Predictions
yc <- "medv"
ac <- "pred_a"
bc <- "pred_b"
binary <- FALSE
metric <- "mae"
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 <- "town"
codes <- as.integer(df[[cc]]) # 1-based, stored level order (levels with data)
g <- nlevels(df[[cc]])
cs_check_groups(df[[cc]], cc, minimum = 2)
threshold <- 0.5
reps <- as.integer(1000)
conf <- 0.9
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
))
MAE: A 3.543, B 3.991; A − B = -0.4486 (90% CI -0.6599 to -0.2281), p = .004 (sign-flip permutation over clusters). Model A is better on MAE.
- MAE, model A
- 3.543
- MAE, model B
- 3.991
- Difference A − B
- −0.4486
- p
- .004
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 — Whole clusters of town are resampled (85 clusters).
- Enough rows — 506 rows, 85 clusters.
MAE of each model
| Model | Column | MAE | 90% CI low | 90% CI high |
|---|---|---|---|---|
| A | pred_a | 3.543 | 3.142 | 3.946 |
| B | pred_b | 3.991 | 3.554 | 4.439 |
| A − B | −0.4486 | −0.6599 | −0.2281 |
Percentile intervals from 1000 paired bootstrap resamples of whole clusters (town). Lower is better.
- Bootstrap SE of the difference 0.1333. Model A does better on 58.3% of rows (ties count half).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Compare two models' predictions
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.paired_metric 1.0.0 · spec 434a1a8999cf23a6
# 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", "town"])
n_input = len(df)
df["town"] = pd.Categorical(df["town"], categories=["t001", "t002", "t003", "t004", "t005", "t006", "t007", "t008", "t009", "t010", "t011", "t012", "t013", "t014", "t015", "t016", "t017", "t018", "t019", "t020", "t021", "t022", "t023", "t024", "t025", "t026", "t027", "t028", "t029", "t030", "t031", "t032", "t033", "t034", "t035", "t036", "t037", "t038", "t039", "t040", "t041", "t042", "t043", "t044", "t045", "t046", "t047", "t048", "t049", "t050", "t051", "t052", "t053", "t054", "t055", "t056", "t057", "t058", "t059", "t060", "t061", "t062", "t063", "t064", "t065", "t066", "t067", "t068", "t069", "t070", "t071", "t072", "t073", "t074", "t075", "t076", "t077", "t078", "t079", "t080", "t081", "t082", "t083", "t084", "t085"]) # stored level order
df = df.dropna(subset=["medv", "pred_a", "pred_b", "town"]) # listwise deletion over the analysis columns
df["town"] = df["town"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["medv", "pred_a", "pred_b", "town"]) # infinite values stop the run (registry/errors.yaml)
# %% Predictions
yc, ac, bc = "medv", "pred_a", "pred_b"
binary = False
metric = "mae"
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 = "town"
codes = df[cc].cat.codes.to_numpy().astype(np.int64) # 0-based, stored level order (levels with data)
g = int(len(df[cc].cat.categories))
check_groups(df[cc], cc, minimum=2)
threshold = 0.5
reps = int(1000)
conf = 0.9
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,
})
Two house-price models, 506 rows from 85 towns. Homes in one town share price shocks, so the town is the independent unitEvaluation unitWhat varies independently and must not sit in both training and test data: a patient, molecule, speaker, site or forecast origin., and whole towns are resampled. A's MAE minus B's is −0.449, with a 90% interval from −0.660 to −0.228. Resampling rows one at a time would pretend there are five hundred independent towns and narrow the interval falsely.
Report the number of independent units next to the interval.
Winning most rows isn't winning
PredictPredict first
Model A has the lower Brier score on most rows. Is A the better model?
Reveal
Brier score: A 0.1504, B 0.1576; A − B = -0.007169 (95% CI -0.01833 to 0.004522), p = .202 (sign-flip permutation). Neither model is better at this sample size.
- Brier score, model A
- 0.1504
- Brier score, model B
- 0.1576
- Difference A − B
- −0.0072
- p
- .202
Plots
View data
| Model | high | low | Metric | Brier score |
|---|---|---|---|---|
| A: p_overfit | 0.1737 | 0.1294 | Brier score | 0.1504 |
| B: p_base | 0.1773 | 0.1385 | Brier score | 0.1576 |
View data
| Brier score: A − B |
|---|
| −0.0115 |
| −0.0029 |
| −0.0027 |
| −0.0101 |
| −0.0091 |
| −0.0150 |
| 0.0007 |
| −0.0092 |
| −0.0098 |
| −0.0211 |
| −0.0144 |
| −0.0101 |
| −0.0189 |
| −0.0173 |
| 0.0024 |
| −0.0114 |
| −0.0007 |
| −0.0065 |
| −0.0003 |
| −0.0015 |
| −0.0098 |
| −0.0052 |
| −0.0065 |
| −0.0064 |
| −0.0083 |
| 0.0002 |
| −0.0125 |
| −0.0097 |
| −0.0091 |
| −0.0116 |
| −0.0044 |
| −0.0098 |
| −0.0079 |
| −0.0011 |
| −0.0044 |
| −0.0078 |
| −0.0029 |
| −0.0089 |
| 0.0027 |
| −0.0052 |
| −0.0061 |
| −0.0002 |
| −0.0055 |
| −0.0020 |
| −0.0012 |
| −0.0076 |
| −0.0115 |
| −0.0019 |
| −0.0136 |
| −3.627e-5 |
| −0.0142 |
| −0.0092 |
| −0.0034 |
| −0.0048 |
| −0.0119 |
| −0.0025 |
| −0.0086 |
| −0.0092 |
| −0.0134 |
| −0.0033 |
First 60 of 1000 rows.
Assumptions
- Both models scored the same rows — 532 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 — 532 rows, 177 events.
Brier score of each model
| Model | Column | Brier score | 95% CI low | 95% CI high |
|---|---|---|---|---|
| A | p_overfit | 0.1504 | 0.1294 | 0.1737 |
| B | p_base | 0.1576 | 0.1385 | 0.1773 |
| A − B | −0.0072 | −0.0183 | 0.0045 |
Percentile intervals from 1000 paired bootstrap resamples. Lower is better.
- Bootstrap SE of the difference 0.005857. Model A does better on 75.4% of rows (ties count half).
- Event: type = Yes.
The exact R script · R R version 4.5.1 (2025-06-13)
# Compare two models' predictions
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.paired_metric 1.0.0 · spec 8022800a30c64a8e
# Dataset: s5_risk (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/s5_risk.parquet", col_select = c("type", "p_overfit", "p_base")))
n_input <- nrow(df)
df[["type"]] <- factor(df[["type"]], levels = c("No", "Yes")) # stored level order
df <- df[stats::complete.cases(df[c("type", "p_overfit", "p_base")]), , 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("type", "p_overfit", "p_base")) # infinite values stop the run (registry/errors.yaml)
# %% Predictions
yc <- "type"
ac <- "p_overfit"
bc <- "p_base"
binary <- TRUE
metric <- "brier"
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 <- "Yes"
if (!(event %in% present)) cs_error("CS_E_NOT_A_LEVEL", level = event, column = yc)
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(1000)
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
))
Brier score: A 0.1504, B 0.1576; A − B = -0.007169 (95% CI -0.01833 to 0.004522), p = .202 (sign-flip permutation). Neither model is better at this sample size.
- Brier score, model A
- 0.1504
- Brier score, model B
- 0.1576
- Difference A − B
- −0.0072
- p
- .202
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Both models scored the same rows — 532 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 — 532 rows, 177 events.
Brier score of each model
| Model | Column | Brier score | 95% CI low | 95% CI high |
|---|---|---|---|---|
| A | p_overfit | 0.1504 | 0.1294 | 0.1737 |
| B | p_base | 0.1576 | 0.1385 | 0.1773 |
| A − B | −0.0072 | −0.0183 | 0.0045 |
Percentile intervals from 1000 paired bootstrap resamples. Lower is better.
- Bootstrap SE of the difference 0.005857. Model A does better on 75.4% of rows (ties count half).
- Event: type = Yes.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Compare two models' predictions
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.paired_metric 1.0.0 · spec 8022800a30c64a8e
# Dataset: s5_risk (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/s5_risk.parquet", columns=["type", "p_overfit", "p_base"])
n_input = len(df)
df["type"] = pd.Categorical(df["type"], categories=["No", "Yes"]) # stored level order
df = df.dropna(subset=["type", "p_overfit", "p_base"]) # listwise deletion over the analysis columns
df["type"] = df["type"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["type", "p_overfit", "p_base"]) # infinite values stop the run (registry/errors.yaml)
# %% Predictions
yc, ac, bc = "type", "p_overfit", "p_base"
binary = True
metric = "brier"
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 = "Yes"
if event not in present:
cs.cs_error("CS_E_NOT_A_LEVEL", level=event, column=yc)
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(1000)
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,
})
Not yet. A wins on 75.4% of rows, but the difference in Brier score is −0.0072, with an interval from −0.0183 to 0.0045 and p = .202. Many small wins can be outweighed by a few large losses.
Sign flips
ReadIf the two models are interchangeable, each case's loss difference is as likely to be positive as negative. Flip the signs and recompute the statistic: with few cases, every one of the patterns (exact); otherwise random patterns, with
The exact version enumerates every pattern, the observed one included, so it adds no extra one. In the reference's four-difference example, the exact two-sided p-value is 0.25: with four cases the smallest possible p is two in sixteen.
Reference · EVA054 · Runs in CodeSplashPaired randomization and permutation testsCalibrates a system-comparison statistic by transformations justified under a specified null.Raise the shared difficulty below: the two models agree on more rows, and at the same accuracies the p-value falls.
BExplorable · Paired permutation test for two models
Two models were scored on the same test rows. Is the difference in their accuracy more than the luck of these rows?
Data
Simulated predictions follow the settings below. The lesson's example is the data the engines ran, as recorded; the settings don't change it.
On this share of rows both models face the same draw, so they agree whenever their accuracies allow. The accuracies stay as set; only the rows where the models disagree carry evidence.
Random sign patterns; the smallest possible p is 1/(B + 1).
Your data
Simulated with known accuracies| B right | B wrong | |
|---|---|---|
| A right | 122 | 34 |
| A wrong | 12 | 32 |
200 rows: A is right on 0.780 of them and B on 0.670. Only the 46 rows where they disagree (bold) can flip sign; d̄ = (34 − 12) / 200.
If H₀ were true
- The reference: how d̄ varies across samples when H₀ is true, 500 random sign flips of the row differences (sign-flip permutation: each row's difference keeps or flips its sign at random (seed 43); only the 46 rows where the models disagree can move).
- Your statistic, from the data above.
- The p-value: the area at least as extreme as yours (p = .006).
- The hatched rejection region at α = .050: statistics landing here reject H₀.
The formula
With your numbers
- 1 if model A is right on row i, else 0
- the mean difference after flipping the sign of each row's difference at random
The verdict
d̄ = 0.11, p = .006
p ≤ α = .050: reject H₀
Under H0 the two models are exchangeable on every row, so each row's difference is as likely to be positive as negative. Rows where both models agree add nothing: raise the shared difficulty and the same accuracies become easier to tell apart. The lesson's example gives the recorded result.
- Statistic
- 0.110
- p-value
- 0.0060
Paired permutation test for two models on 200 rows scored by both models (1 = right): d̄ = 0.11, p = .006. The p-value is below α = .050, so the data are hard to reconcile with H₀.
What the flips assume
ReadThe null must make each flip an equally likely dataset. In a randomized design (which system handled which query was assigned at random), that follows from the design. In observational comparisons it is an assumption about symmetry, stronger than "equal average performance". Flip whole units: all of a town's rows together, all of a speaker's clips.
t(9) = −4.06, p = .003, g_z = −1.17, 95% CI [−1.94, −0.38]
- t
- −4.062
- df
- 9
- p
- .003
- Mean difference (drug1 − drug2)
- −1.580
- 95% CI
- [−2.460, −0.7001]
- Sign-flip p
- .004
Effect size
- Hedges' g_z −1.174 95% CI [−1.936, −0.3789] · large
Plots
View data
| Measurement | Row | Value |
|---|---|---|
| drug1 | 1 | 0.7000 |
| drug1 | 2 | −1.600 |
| drug1 | 3 | −0.2000 |
| drug1 | 4 | −1.200 |
| drug1 | 5 | −0.1000 |
| drug1 | 6 | 3.400 |
| drug1 | 7 | 3.700 |
| drug1 | 8 | 0.8000 |
| drug1 | 9 | 0 |
| drug1 | 10 | 2 |
| drug2 | 1 | 1.900 |
| drug2 | 2 | 0.8000 |
| drug2 | 3 | 1.100 |
| drug2 | 4 | 0.1000 |
| drug2 | 5 | −0.1000 |
| drug2 | 6 | 4.400 |
| drug2 | 7 | 5.500 |
| drug2 | 8 | 1.600 |
| drug2 | 9 | 4.600 |
| drug2 | 10 | 3.400 |
View data
| Density | Observed | Σ (difference − μ₀) |
|---|---|---|
| 0.0025 | −15.800 | −15.405 |
| 0 | −15.800 | −14.615 |
| 0.0049 | −15.800 | −13.825 |
| 0.0099 | −15.800 | −13.035 |
| 0.0049 | −15.800 | −12.245 |
| 0.0173 | −15.800 | −11.455 |
| 0.0223 | −15.800 | −10.665 |
| 0.0173 | −15.800 | −9.875 |
| 0.0297 | −15.800 | −9.085 |
| 0.0371 | −15.800 | −8.295 |
| 0.0297 | −15.800 | −7.505 |
| 0.0470 | −15.800 | −6.715 |
| 0.0470 | −15.800 | −5.925 |
| 0.0470 | −15.800 | −5.135 |
| 0.0544 | −15.800 | −4.345 |
| 0.0494 | −15.800 | −3.555 |
| 0.0544 | −15.800 | −2.765 |
| 0.0544 | −15.800 | −1.975 |
| 0.0494 | −15.800 | −1.185 |
| 0.0544 | −15.800 | −0.3950 |
| 0.0544 | −15.800 | 0.3950 |
| 0.0494 | −15.800 | 1.185 |
| 0.0544 | −15.800 | 1.975 |
| 0.0544 | −15.800 | 2.765 |
| 0.0494 | −15.800 | 3.555 |
| 0.0544 | −15.800 | 4.345 |
| 0.0470 | −15.800 | 5.135 |
| 0.0470 | −15.800 | 5.925 |
| 0.0470 | −15.800 | 6.715 |
| 0.0297 | −15.800 | 7.505 |
| 0.0371 | −15.800 | 8.295 |
| 0.0297 | −15.800 | 9.085 |
| 0.0173 | −15.800 | 9.875 |
| 0.0223 | −15.800 | 10.665 |
| 0.0173 | −15.800 | 11.455 |
| 0.0049 | −15.800 | 12.245 |
| 0.0099 | −15.800 | 13.035 |
| 0.0049 | −15.800 | 13.825 |
| 0 | −15.800 | 14.615 |
| 0.0025 | −15.800 | 15.405 |
Assumptions
- Normality of the differences — Differences: Shapiro–Wilk p = .033 with fewer than 30 pairs; consider the Wilcoxon signed-rank test.
Descriptives
| Measurement | n | Mean | SD | Median |
|---|---|---|---|---|
| drug1 | 10 | 0.7500 | 1.789 | 0.3500 |
| drug2 | 10 | 2.330 | 2.002 | 1.750 |
| drug1 − drug2 | 10 | −1.580 | 1.230 | −1.300 |
- Difference = drug1 − drug2; alternative: two-sided; H0 difference = 0. Correlation between the measurements r = 0.80.
- Sign-flip p: the statistic Σ(difference − 0) against its values under every sign pattern (exact, p = share at least as extreme) or 1,024 random patterns from the shared seeded stream (seed 42, p = (1 + count) / (B + 1)); valid when the differences are symmetric about 0 under H0.
The exact R script · R R version 4.5.1 (2025-06-13)
# Paired t-test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ttest.paired 1.3.0 · spec 0aa6fcaaab31220a
# Dataset: sleep_wide (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/sleep_wide.parquet", col_select = c("drug1", "drug2")))
n_input <- nrow(df)
df <- df[stats::complete.cases(df[c("drug1", "drug2")]), , 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("drug1", "drug2")) # infinite values stop the run (registry/errors.yaml)
# Normality assumption: the test the dialog selected (`normality_test`). Shapiro-Wilk keeps the
# method's own row; any other choice replaces it (cs_normality_test; a simulated p such as
# Filliben's uses the fixed seed 42, so Python draws the same stream).
normality_test <- "shapiro_wilk"
normality_selected <- function(samples, row_label, small) {
res <- lapply(samples, function(s) cs_normality_test(as.numeric(s), normality_test, 42, 1999))
ok <- Filter(function(r) is.finite(r$p), res)
label <- res[[1]]$label
symbol <- res[[1]]$symbol
if (!length(ok)) {
return(list(row = list(key = "normality", label = row_label, status = "info",
detail = sprintf("%s is not available for these sample sizes.", label)), p = NULL))
}
ps <- vapply(ok, function(r) r$p, 0)
p_min <- min(ps)
bad <- sum(ps < 0.05)
status <- if (bad) (if (small) "warn" else "info") else "pass"
tail <- if (status == "warn") "; consider a rank-based or robust method." else "."
row <- if (length(samples) == 1) {
list(key = "normality", label = row_label, status = status, statistic = ok[[1]]$statistic, p = ok[[1]]$p,
detail = paste0(sprintf("%s %s = %.3f, %s", label, symbol, ok[[1]]$statistic, cs_fmt_p(ok[[1]]$p)), tail))
} else {
list(key = "normality", label = row_label, status = status,
detail = paste0(if (bad) sprintf("%s: p < .05 in %d of %d groups (smallest %s)", label, bad, length(ok), cs_fmt_p(p_min))
else sprintf("%s: p ≥ .05 in every group", label), tail))
}
list(row = row, p = p_min)
}
# %% Helpers
ncp_ci <- function(t, df, conf) {
# CI for the noncentrality parameter of an observed t (Steiger & Fouladi 1997)
solve <- function(prob) {
# P(T <= t | ncp) falls as ncp grows: widen a bracket around t until it straddles prob.
f <- function(ncp) suppressWarnings(pt(t, df, ncp)) - prob
lo <- t - 1
hi <- t + 1
step <- 1
while (f(lo) < 0) {
lo <- lo - step
step <- step * 2
}
step <- 1
while (f(hi) > 0) {
hi <- hi + step
step <- step * 2
}
uniroot(f, c(lo, hi), tol = 1e-12)$root
}
alpha <- 1 - conf
c(solve(1 - alpha / 2), solve(alpha / 2))
}
hedges_j <- function(df) {
# Exact small-sample correction J = gamma(df/2) / (sqrt(df/2) * gamma((df - 1)/2))
exp(lgamma(df / 2) - log(sqrt(df / 2)) - lgamma((df - 1) / 2))
}
magnitude <- function(x, cuts, labels = c("negligible", "small", "medium", "large")) {
# Benchmark label for an effect size (rule set named in the result)
if (is.null(x) || !is.finite(x)) return("undetermined")
labels[findInterval(abs(x), cuts) + 1]
}
# %% Test
a <- "drug1"
b <- "drug2"
x1 <- df[[a]]
x2 <- df[[b]]
n <- length(x1)
alternative <- "two-sided"
conf <- 0.95
mu <- 0 # hypothesized mean difference (first - second)
if (n < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "A paired t-test", min = 2, n = n)
if (all(x1 == x2)) cs_error("CS_E_ALL_ZERO_DIFFERENCES")
if (length(unique(x1 - x2)) < 2) cs_error("CS_E_CONSTANT", column = sprintf("%s − %s", a, b)) # t is undefined
res <- t.test(x1, x2, paired = TRUE, mu = mu, alternative = sub("-", ".", alternative, fixed = TRUE), conf.level = conf)
t <- unname(res$statistic)
dof <- unname(res$parameter)
p <- res$p.value
diffs <- x1 - x2
mean_d <- mean(diffs)
sd_d <- sd(diffs)
ci_low <- res$conf.int[1]
ci_high <- res$conf.int[2]
# The correlation is undefined when a measurement doesn't vary: NA (published as null).
r <- if (length(unique(x1)) > 1 && length(unique(x2)) > 1) cor(x1, x2) else NA_real_
# Effect size: d_z = mean difference / SD of differences; g_z with the exact J; noncentral-t CI.
dz <- mean_d / sd_d
nc <- ncp_ci(dz * sqrt(n), n - 1, conf)
j <- hedges_j(n - 1)
gz <- dz * j
gz_low <- nc[1] / sqrt(n) * j
gz_high <- nc[2] / sqrt(n) * j
# %% Assumptions
sw <- if (n >= 3 && n <= 5000 && diff(range(diffs)) > 0) shapiro.test(diffs) else NULL
if (is.null(sw)) {
status <- "info"
detail <- "Shapiro–Wilk needs 3–5,000 differences that are not all equal; inspect a Q–Q plot."
} else if (sw$p.value < 0.05 && n < 30) {
status <- "warn"
detail <- sprintf("Differences: Shapiro–Wilk %s with fewer than 30 pairs; consider the Wilcoxon signed-rank test.", cs_fmt_p(sw$p.value))
} else if (sw$p.value < 0.05) {
status <- "info"
detail <- sprintf("Differences: Shapiro–Wilk %s, but with %d pairs the t-test is robust.", cs_fmt_p(sw$p.value), n)
} else {
status <- "pass"
detail <- sprintf("Differences: Shapiro–Wilk W = %.3f, %s.", sw$statistic, cs_fmt_p(sw$p.value))
}
assumptions <- list(list(key = "normality", label = "Normality of the differences", status = status, detail = detail))
if (n < 5) warnings <- c(warnings, "Fewer than 5 pairs; estimates are unstable.")
normality_p <- NULL
if (normality_test != "shapiro_wilk") {
ns_ <- normality_selected(list(diffs), "Normality of the differences", n < 30)
normality_p <- ns_$p
assumptions <- lapply(assumptions, function(a) if (a$key == "normality") ns_$row else a)
}
# %% Result
alpha <- 1 - conf
pct <- sprintf("%.0f%%", conf * 100)
size <- magnitude(gz, c(0.2, 0.5, 0.8))
significance <- if (p < alpha) {
sprintf("The change is statistically significant (%s).", cs_fmt_p(p))
} else {
sprintf("The data are compatible with no change (%s).", cs_fmt_p(p))
}
summary <- sprintf("Across %d pairs, %s − %s averaged %.2f (SD %.2f), %s CI [%.2f, %.2f]. %s The standardized change is %s (g_z = %.2f).",
n, a, b, mean_d, sd_d, pct, ci_low, ci_high, significance, size, gz)
# Lens (equivalence / minimal effect / non-inferiority) on the mean difference, at alpha = 1 - confidence.
lens_kind <- "none"
lens <- NULL
if (lens_kind != "none") lens <- cs_lens(lens_kind, mean_d, sd_d / sqrt(n), dof, NULL, NULL, 1 - conf)
if (!is.null(lens)) summary <- paste(summary, sprintf("Lens (%s): %s (%s).", gsub("_", " ", lens_kind), lens$lens_verdict, cs_fmt_p(lens$lens_p)))
# Optional sign-flip randomization p (Stage 12.7): exact over all 2^n sign patterns for <= 16 pairs, else
# random sign patterns from the shared Wichmann-Hill stream; needs symmetric differences, not normal ones.
perm <- NULL
if ("sign_flip" == "sign_flip") perm <- cs_signflip_test(diffs, mu, alternative, as.integer(9999), 42)
if (!is.null(perm)) {
perm_how <- if (perm$kind == "exact") sprintf("exact over all %s sign patterns", format(perm$b, big.mark = ",")) else sprintf("%s random sign patterns", format(perm$b, big.mark = ","))
summary <- paste(summary, sprintf("Sign-flip randomization test: %s (%s).", cs_fmt_p(perm$p), perm_how))
}
values <- list(
t = t, df = dof, p = p, n = n, mean_diff = mean_d, sd_diff = sd_d, ci_low = ci_low, ci_high = ci_high,
mean_1 = mean(x1), mean_2 = mean(x2), r = r,
d_z = dz, g_z = gz, gz_ci_low = gz_low, gz_ci_high = gz_high,
sw_p = if (is.null(sw)) NULL else sw$p.value, mu = mu
)
if (!is.null(lens)) values <- c(values, lens)
if (!is.null(normality_p)) values$normality_p <- normality_p
if (!is.null(perm)) values <- c(values, list(perm_p = perm$p, perm_kind = perm$kind, perm_b = perm$b))
nn <- length(x1)
cs_publish(list(
method = "ttest.paired",
methodVersion = "1.3.0",
title = "Paired t-test",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("t(%.0f) = %s, %s, g_z = %s, %s CI [%s, %s]", dof, cs_fmt_num(t), cs_fmt_p(p), cs_fmt_num(gz), pct, cs_fmt_num(gz_low), cs_fmt_num(gz_high)),
statistics = c(list(
list(key = "t", label = "t", value = t),
list(key = "df", label = "df", value = dof),
list(key = "p", label = "p", value = p, format = "p"),
list(key = "mean_diff", label = sprintf("Mean difference (%s − %s)", a, b), value = mean_d),
list(key = "ci", label = paste(pct, "CI"), value = c(ci_low, ci_high))),
if (!is.null(lens)) list(list(key = "lens_p", label = sprintf("Lens p (%s)", gsub("_", " ", lens_kind)), value = lens$lens_p, format = "p")) else list(),
if (!is.null(perm)) list(list(key = "perm_p", label = "Sign-flip p", value = perm$p, format = "p")) else list()
),
tables = list(list(
key = "descriptives", title = "Descriptives",
columns = list(list(key = "variable", label = "Measurement", type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "mean", label = "Mean", type = "number"), list(key = "sd", label = "SD", type = "number"),
list(key = "median", label = "Median", type = "number")),
rows = data.frame(variable = c(a, b, sprintf("%s − %s", a, b)), n = n,
mean = c(mean(x1), mean(x2), mean_d), sd = c(sd(x1), sd(x2), sd_d),
median = c(median(x1), median(x2), median(diffs)))
)),
effectSizes = list(list(key = "g_z", label = "Hedges' g_z", value = gz, ciLow = gz_low, ciHigh = gz_high, ciLevel = conf,
method = "mean difference / SD of differences, exact J, noncentral-t interval", magnitude = size, ruleSet = "Cohen (1988)")),
assumptions = assumptions,
warnings = warnings,
notes = c(list(sprintf("Difference = %s − %s; alternative: %s; H0 difference = %s. Correlation between the measurements r = %s.",
a, b, alternative, format(mu), if (is.na(r)) "undefined" else sprintf("%.2f", r))),
if (!is.null(lens)) list(sprintf("The lens interval [%.3g, %.3g] is the %.0f%% interval for the mean difference.", lens$lens_ci_low, lens$lens_ci_high, (1 - 2 * (1 - conf)) * 100)) else list(),
if (!is.null(perm)) list(sprintf("Sign-flip p: the statistic Σ(difference − %s) against its values under every sign pattern (exact, p = share at least as extreme) or %s random patterns from the shared seeded stream (seed 42, p = (1 + count) / (B + 1)); valid when the differences are symmetric about %s under H0.", format(mu), format(perm$b, big.mark = ","), format(mu))) else list()),
values = values,
charts = c(list(cs_chart("pairs", "paired-lines", sprintf("%s and %s per row", a, b), list(
subject = cs_col("Row", rep(as.character(seq_len(min(nn, 2500))), 2), "categorical"),
condition = cs_col("Measurement", rep(c(a, b), each = min(nn, 2500)), "categorical", levels = c(a, b)),
value = cs_col("Value", c(head(x1, 2500), head(x2, 2500)), "numeric")))),
if (!is.null(perm)) {
nc <- cs_signflip_null_curve(perm$null)
list(cs_chart("null", "null-distribution", "Sum of the differences under sign flips", list(
x = cs_col("Σ (difference − μ₀)", nc$x), density = cs_col("Density", nc$density),
observed = cs_col("Observed", rep(perm$statistic, length(nc$x)))), controls = list(alternative = alternative)))
} else list())
))
t(9) = −4.06, p = .003, g_z = −1.17, 95% CI [−1.94, −0.38]
- t
- −4.062
- df
- 9
- p
- .003
- Mean difference (drug1 − drug2)
- −1.580
- 95% CI
- [−2.460, −0.7001]
- Sign-flip p
- .004
Effect size
- Hedges' g_z −1.174 95% CI [−1.936, −0.3789] · large
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Normality of the differences — Differences: Shapiro–Wilk p = .033 with fewer than 30 pairs; consider the Wilcoxon signed-rank test.
Descriptives
| Measurement | n | Mean | SD | Median |
|---|---|---|---|---|
| drug1 | 10 | 0.7500 | 1.789 | 0.3500 |
| drug2 | 10 | 2.330 | 2.002 | 1.750 |
| drug1 − drug2 | 10 | −1.580 | 1.230 | −1.300 |
- Difference = drug1 − drug2; alternative: two-sided; H0 difference = 0. Correlation between the measurements r = 0.80.
- Sign-flip p: the statistic Σ(difference − 0) against its values under every sign pattern (exact, p = share at least as extreme) or 1,024 random patterns from the shared seeded stream (seed 42, p = (1 + count) / (B + 1)); valid when the differences are symmetric about 0 under H0.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Paired t-test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method ttest.paired 1.3.0 · spec 0aa6fcaaab31220a
# Dataset: sleep_wide (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
from scipy import optimize, special, stats
import codesplash as cs
from codesplash.stats import means as csm
# %% Data
df = pd.read_parquet("tests/parity/fixtures/sleep_wide.parquet", columns=["drug1", "drug2"])
n_input = len(df)
df = df.dropna(subset=["drug1", "drug2"]) # 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, ["drug1", "drug2"]) # infinite values stop the run (registry/errors.yaml)
# Normality assumption: the test the dialog selected (`normality_test`). Shapiro–Wilk keeps the
# method's own row; any other choice replaces it (codesplash.stats.normality.normality_test; a
# simulated p such as Filliben's uses the fixed seed 42, so R draws the same stream).
normality_test = "shapiro_wilk"
def normality_selected(samples, row_label, small):
from codesplash.stats import normality as csn
res = [csn.normality_test(np.asarray(s, dtype=float), normality_test, 42, 1999) for s in samples]
ok = [r for r in res if np.isfinite(r["p"])]
label, symbol = res[0]["label"], res[0]["symbol"]
if not ok:
return {"key": "normality", "label": row_label, "status": "info", "detail": f"{label} is not available for these sample sizes."}, None
p_min = min(r["p"] for r in ok)
bad = sum(r["p"] < 0.05 for r in ok)
status = ("warn" if small else "info") if bad else "pass"
row = {"key": "normality", "label": row_label, "status": status}
if len(samples) == 1:
row.update({"statistic": ok[0]["statistic"], "p": ok[0]["p"],
"detail": f"{label} {symbol} = {ok[0]['statistic']:.3f}, {cs.fmt_p(ok[0]['p'])}" + ("; consider a rank-based or robust method." if status == "warn" else ".")})
else:
row["detail"] = (f"{label}: p < .05 in {bad} of {len(ok)} groups (smallest {cs.fmt_p(p_min)})" if bad
else f"{label}: p ≥ .05 in every group") + ("; consider a rank-based or robust method." if status == "warn" else ".")
return row, p_min
# %% Helpers
def ncp_ci(t, df, conf):
"""CI for the noncentrality parameter of an observed t (Steiger & Fouladi 1997)."""
def solve(prob):
# P(T <= t | ncp) falls as ncp grows: widen a bracket around t until it straddles prob.
f = lambda ncp: stats.nct.cdf(t, df, ncp) - prob # noqa: E731
lo, hi, step = t - 1.0, t + 1.0, 1.0
while f(lo) < 0:
lo, step = lo - step, step * 2
step = 1.0
while f(hi) > 0:
hi, step = hi + step, step * 2
return optimize.brentq(f, lo, hi, xtol=1e-12)
alpha = 1 - conf
return solve(1 - alpha / 2), solve(alpha / 2)
def hedges_j(df):
"""Exact small-sample correction J = Γ(df/2) / (√(df/2) · Γ((df − 1)/2))."""
return float(np.exp(special.gammaln(df / 2) - np.log(np.sqrt(df / 2)) - special.gammaln((df - 1) / 2)))
def magnitude(x, cuts, labels=("negligible", "small", "medium", "large")):
"""Benchmark label for an effect size (rule set named in the result)."""
if x is None or not np.isfinite(x):
return "undetermined"
for cut, label in zip(cuts, labels):
if abs(x) < cut:
return label
return labels[-1]
# %% Test
a, b = "drug1", "drug2"
x1 = df[a].to_numpy(dtype=float)
x2 = df[b].to_numpy(dtype=float)
n = len(x1)
alternative = "two-sided"
conf = 0.95
mu = 0 # hypothesized mean difference (first − second)
if n < 2:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="A paired t-test", min=2, n=n)
if np.all(x1 == x2):
cs.cs_error("CS_E_ALL_ZERO_DIFFERENCES")
if len(np.unique(x1 - x2)) < 2: # the differences don't vary: t is undefined
cs.cs_error("CS_E_CONSTANT", column=f"{a} − {b}")
# scipy tests mean(x1 − x2) = 0, so shift x1 by mu and shift the interval back.
res = stats.ttest_rel(x1 - mu, x2, alternative=alternative)
ci = res.confidence_interval(confidence_level=conf)
t, dof, p = float(res.statistic), float(res.df), float(res.pvalue)
diffs = x1 - x2
mean_d, sd_d = diffs.mean(), diffs.std(ddof=1)
ci_low, ci_high = float(ci.low) + mu, float(ci.high) + mu
# The correlation is undefined when a measurement doesn't vary: null, as R's cor() gives NA.
r = float(np.corrcoef(x1, x2)[0, 1]) if len(np.unique(x1)) > 1 and len(np.unique(x2)) > 1 else None
# Effect size: d_z = mean difference / SD of differences; g_z with the exact J; noncentral-t CI.
dz = mean_d / sd_d
nc_low, nc_high = ncp_ci(dz * np.sqrt(n), n - 1, conf)
j = hedges_j(n - 1)
gz, gz_low, gz_high = dz * j, nc_low / np.sqrt(n) * j, nc_high / np.sqrt(n) * j
# Lens (equivalence / minimal effect / non-inferiority) on the mean difference, at α = 1 − confidence.
lens_kind = "none"
lens = None
if lens_kind != "none":
lens = csm.lens(lens_kind, mean_d, sd_d / np.sqrt(n), dof, None, None, 1 - conf)
# Optional sign-flip randomization p (Stage 12.7): exact over all 2ⁿ sign patterns for ≤ 16 pairs, else
# random sign patterns from the shared Wichmann–Hill stream; needs symmetric differences, not normal ones.
perm = None
if "sign_flip" == "sign_flip":
from codesplash.stats import signflip
perm = signflip.signflip_test(diffs, mu, alternative, int(9999), 42)
# %% Assumptions
assumptions = []
sw = stats.shapiro(diffs) if 3 <= n <= 5000 and np.ptp(diffs) > 0 else None
if sw is None:
status, detail = "info", "Shapiro–Wilk needs 3–5,000 differences that are not all equal; inspect a Q–Q plot."
elif sw.pvalue < 0.05 and n < 30:
status, detail = "warn", f"Differences: Shapiro–Wilk {cs.fmt_p(sw.pvalue)} with fewer than 30 pairs; consider the Wilcoxon signed-rank test."
elif sw.pvalue < 0.05:
status, detail = "info", f"Differences: Shapiro–Wilk {cs.fmt_p(sw.pvalue)}, but with {n} pairs the t-test is robust."
else:
status, detail = "pass", f"Differences: Shapiro–Wilk W = {sw.statistic:.3f}, {cs.fmt_p(sw.pvalue)}."
assumptions.append({"key": "normality", "label": "Normality of the differences", "status": status, "detail": detail})
if n < 5:
warnings.append("Fewer than 5 pairs; estimates are unstable.")
normality_p = None
if normality_test != "shapiro_wilk":
_row, normality_p = normality_selected([diffs], "Normality of the differences", n < 30)
assumptions = [_row if a["key"] == "normality" else a for a in assumptions]
# %% Result
alpha = 1 - conf
size = magnitude(gz, (0.2, 0.5, 0.8))
significance = (
f"The change is statistically significant ({cs.fmt_p(p)})." if p < alpha
else f"The data are compatible with no change ({cs.fmt_p(p)})."
)
summary = (
f"Across {n} pairs, {a} − {b} averaged {mean_d:.2f} (SD {sd_d:.2f}), {conf:.0%} CI [{ci_low:.2f}, {ci_high:.2f}]. "
f"{significance} The standardized change is {size} (g_z = {gz:.2f})."
)
if lens:
summary += f" Lens ({lens_kind.replace('_', ' ')}): {lens['lens_verdict']} ({cs.fmt_p(lens['lens_p'])})."
if perm:
perm_how = f"exact over all {perm['b']:,} sign patterns" if perm["kind"] == "exact" else f"{perm['b']:,} random sign patterns"
summary += f" Sign-flip randomization test: {cs.fmt_p(perm['p'])} ({perm_how})."
cs.publish({
"method": "ttest.paired",
"methodVersion": "1.3.0",
"title": "Paired t-test",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"t({dof:.0f}) = {cs.fmt_num(t)}, {cs.fmt_p(p)}, g_z = {cs.fmt_num(gz)}, {conf:.0%} CI [{cs.fmt_num(gz_low)}, {cs.fmt_num(gz_high)}]",
"statistics": [
{"key": "t", "label": "t", "value": t},
{"key": "df", "label": "df", "value": dof},
{"key": "p", "label": "p", "value": p, "format": "p"},
{"key": "mean_diff", "label": f"Mean difference ({a} − {b})", "value": mean_d},
{"key": "ci", "label": f"{conf:.0%} CI", "value": [ci_low, ci_high]},
] + ([{"key": "lens_p", "label": f"Lens p ({lens_kind.replace('_', ' ')})", "value": lens["lens_p"], "format": "p"}] if lens else [])
+ ([{"key": "perm_p", "label": "Sign-flip p", "value": perm["p"], "format": "p"}] if perm else []),
"tables": [{
"key": "descriptives", "title": "Descriptives",
"columns": [{"key": "variable", "label": "Measurement", "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "mean", "label": "Mean", "type": "number"}, {"key": "sd", "label": "SD", "type": "number"},
{"key": "median", "label": "Median", "type": "number"}],
"rows": [
{"variable": a, "n": n, "mean": float(x1.mean()), "sd": float(x1.std(ddof=1)), "median": float(np.quantile(x1, 0.5))},
{"variable": b, "n": n, "mean": float(x2.mean()), "sd": float(x2.std(ddof=1)), "median": float(np.quantile(x2, 0.5))},
{"variable": f"{a} − {b}", "n": n, "mean": float(mean_d), "sd": float(sd_d), "median": float(np.quantile(diffs, 0.5))},
],
}],
"effectSizes": [{"key": "g_z", "label": "Hedges' g_z", "value": gz, "ciLow": gz_low, "ciHigh": gz_high, "ciLevel": conf,
"method": "mean difference / SD of differences, exact J, noncentral-t interval", "magnitude": size, "ruleSet": "Cohen (1988)"}],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Difference = {a} − {b}; alternative: {alternative}; H0 difference = {mu:g}. Correlation between the measurements r = {'undefined' if r is None else format(r, '.2f')}."]
+ ([f"The lens interval [{lens['lens_ci_low']:.3g}, {lens['lens_ci_high']:.3g}] is the {1 - 2 * (1 - conf):.0%} interval for the mean difference."] if lens else [])
+ ([f"Sign-flip p: the statistic Σ(difference − {mu:g}) against its values under every sign pattern (exact, p = share at least as extreme) or {perm['b']:,} random patterns from the shared seeded stream (seed 42, p = (1 + count) / (B + 1)); valid when the differences are symmetric about {mu:g} under H0."] if perm else []),
"values": {
"t": t, "df": dof, "p": p, "n": n, "mean_diff": mean_d, "sd_diff": sd_d, "ci_low": ci_low, "ci_high": ci_high,
"mean_1": float(x1.mean()), "mean_2": float(x2.mean()), "r": r,
"d_z": dz, "g_z": gz, "gz_ci_low": gz_low, "gz_ci_high": gz_high,
"sw_p": None if sw is None else float(sw.pvalue), "mu": mu,
**(lens or {}),
**({"normality_p": normality_p} if normality_p is not None else {}),
**({"perm_p": perm["p"], "perm_kind": perm["kind"], "perm_b": perm["b"]} if perm else {}),
},
"charts": [cs.chart("pairs", "paired-lines", f"{a} and {b} per row", {
"subject": cs.col("Row", [str(i + 1) for i in range(min(n, 2500))] * 2, "categorical"),
"condition": cs.col("Measurement", [a] * min(n, 2500) + [b] * min(n, 2500), "categorical", levels=[a, b]),
"value": cs.col("Value", np.concatenate([x1[:2500], x2[:2500]]), "numeric")})]
+ ([cs.chart("null", "null-distribution", "Sum of the differences under sign flips", {
"x": cs.col("Σ (difference − μ₀)", signflip.null_curve(perm["null"])[0]),
"density": cs.col("Density", signflip.null_curve(perm["null"])[1]),
"observed": cs.col("Observed", np.full(40, perm["statistic"]))}, controls={"alternative": alternative})] if perm else []),
})
On ten paired sleep measurements, the exact sign-flip test over 1,024 patterns gives p = .004, next to the paired t test's p = .003.
Folds, seeds and units are different things
ReadThree sources of spread get mixed up:
- cross-validation folds overlap in their training rows, so fold scores aren't independent;
- seeds measure the training procedure's randomness;
- test units measure sampling: how the score would move on a new sample.
The paired bootstrap and sign flips over test units answer the third. They don't replace seed repeats, and fold scores don't replace them. A percentile interval isn't an exact test, either; report it as an interval.
Compare models in CodeSplash
In the appIn Predict's Leaderboard step, tick two or more runs and choose Compare. The comparison pairs them on the same folds, and once the test set is visible it adds a "Sign-flip test on the test rows" on per-row losses (squared or absolute error, log loss, Brier score or 0/1 error). The leaderboard marks runs whose paired difference from the leader is within noise as "≈ leader".
For predictions made anywhere, open Analyze → Evaluate predictions → Compare two models' predictions, bind the outcome and the two prediction columns, and set a Cluster column when rows come in groups. Two identical prediction columns give a difference of exactly 0 and p = 1.000, a quick check that the pairing is right.
Check: paired comparisons
CheckpointCheck yourself
Why recompute both models' metric on the same bootstrap resample?
Show the answer
Answer: a
Hard cases raise both models' errors. Pairing removes that shared variation from the difference.
Check yourself
You compare two speech systems by corpus word error rate. How should each bootstrap resample be scored?
Show the answer
Answer: b
Corpus WER is a ratio of totals, so it must be recomputed on each resample. Speakers are the independent units.
Check yourself
Test rows are video frames, about 300 frames from each of 40 videos. What should the paired bootstrap resample?
Show the answer
Answer: b
Frames of one video share content. Resampling frames treats 12,000 correlated rows as independent and gives an interval far too narrow.
Check yourself
With 4 paired differences, what is the smallest possible exact two-sided sign-flip p-value? Give a decimal.
Show the answer
Answer: 0.125
There are sign patterns. The observed pattern and its mirror image are always at least as extreme, so p ≥ 2/16 = 0.125.
Check yourself
Why does a Monte Carlo permutation p-value add 1 to the count and to B?
Show the answer
Answer: b
treats the observed data as one of the draws. Exact enumeration already includes it, so it adds nothing extra.
Check yourself
Two fixed retrieval systems were compared on queries, with no randomization. What does a sign-flip test on per-query differences assume?
Show the answer
Answer: c
Without randomization, the flips rest on a symmetry assumption, which is stronger than equal means.
Check yourself
Model A wins on 75% of rows, but the paired interval for the metric difference includes zero. What do you report?
Show the answer
Answer: a
Row win rates ignore the size of each win and loss. The paired interval for the metric is the comparison that answers the question.
Recap
Recap- Pair models on the same cases; recompute nonlinear metrics on each resample.
- Resample and flip independent units (towns, speakers, videos), and report how many there are.
- Sign flips are exact by enumeration for small n, otherwise ; both need symmetry under the null.
- Folds, seeds and test units are three different kinds of spread.
- Predict's Compare runs and Analyze's Evaluate predictions both pair, with a cluster column for grouped rows.
Concepts in this lesson