Watching a Bayes factor grow
Read a sequential Bayes factor, see what stopping early does and doesn't change, and plan a study with a design analysis instead of hoping.
What runs in CodeSplash
- STAT311Jeffreys–Zellner–Siow Bayesian t test Runs in CodeSplash
- Bayesian t-test (JZS Bayes factor) Verified in Python and R
- Bayes factor design analysis (t-test) Verified in Python and R
You will be able to
- Read a sequential Bayes factor chart and spot how row order affects it
- State what optional stopping does to a Bayes factor's meaning and to its long-run errors
- Set a stopping rule and report it
Evidence as rows arrive
ReadA Bayes factor can be recomputed after each row. The sequential Bayes factorSequential Bayes factorThe Bayes factor recomputed as observations accumulate; with a fixed prior it can be monitored without an α penalty. chart plots that path on a log scale.
- A path climbing away from 1 means evidence building for .
- A path falling below 1 means evidence building for .
- A path wandering near 1 means little information yet.
CodeSplash uses the rows in the dataset's order. If that order means nothing, a different order would give a different path, with the same end point.
Read a path
In the appBF₁₀ = 18.42 (JZS, r = 1), δ = -1.14, 95% CrI [-2.01, -0.34]
- BF₁₀ (δ ≠ 0 vs δ = 0)
- 18.415
- BF₀₁
- 0.0543
- δ (posterior median)
- −1.139
- 95% credible interval
- [−2.013, −0.3423]
- t
- −4.062
- df
- 9
Effect size
- δ (posterior median) −1.139 95% CI [−2.013, −0.3423]
Plots
View data
| curve | density | δ (standardized effect) |
|---|---|---|
| Prior | 0.0211 | −3.750 |
| Prior | 0.0215 | −3.719 |
| Prior | 0.0218 | −3.688 |
| Prior | 0.0222 | −3.656 |
| Prior | 0.0225 | −3.625 |
| Prior | 0.0229 | −3.594 |
| Prior | 0.0232 | −3.563 |
| Prior | 0.0236 | −3.531 |
| Prior | 0.0240 | −3.500 |
| Prior | 0.0244 | −3.469 |
| Prior | 0.0248 | −3.438 |
| Prior | 0.0253 | −3.406 |
| Prior | 0.0257 | −3.375 |
| Prior | 0.0261 | −3.344 |
| Prior | 0.0266 | −3.313 |
| Prior | 0.0271 | −3.281 |
| Prior | 0.0275 | −3.250 |
| Prior | 0.0280 | −3.219 |
| Prior | 0.0285 | −3.188 |
| Prior | 0.0290 | −3.156 |
| Prior | 0.0296 | −3.125 |
| Prior | 0.0301 | −3.094 |
| Prior | 0.0307 | −3.063 |
| Prior | 0.0312 | −3.031 |
| Prior | 0.0318 | −3 |
| Prior | 0.0324 | −2.969 |
| Prior | 0.0331 | −2.938 |
| Prior | 0.0337 | −2.906 |
| Prior | 0.0344 | −2.875 |
| Prior | 0.0350 | −2.844 |
| Prior | 0.0357 | −2.813 |
| Prior | 0.0364 | −2.781 |
| Prior | 0.0372 | −2.750 |
| Prior | 0.0379 | −2.719 |
| Prior | 0.0387 | −2.688 |
| Prior | 0.0395 | −2.656 |
| Prior | 0.0403 | −2.625 |
| Prior | 0.0412 | −2.594 |
| Prior | 0.0421 | −2.563 |
| Prior | 0.0430 | −2.531 |
| Prior | 0.0439 | −2.500 |
| Prior | 0.0449 | −2.469 |
| Prior | 0.0459 | −2.438 |
| Prior | 0.0469 | −2.406 |
| Prior | 0.0479 | −2.375 |
| Prior | 0.0490 | −2.344 |
| Prior | 0.0501 | −2.313 |
| Prior | 0.0513 | −2.281 |
| Prior | 0.0525 | −2.250 |
| Prior | 0.0537 | −2.219 |
| Prior | 0.0550 | −2.188 |
| Prior | 0.0563 | −2.156 |
| Prior | 0.0577 | −2.125 |
| Prior | 0.0591 | −2.094 |
| Prior | 0.0606 | −2.063 |
| Prior | 0.0621 | −2.031 |
| Prior | 0.0637 | −2 |
| Prior | 0.0653 | −1.969 |
| Prior | 0.0670 | −1.938 |
| Prior | 0.0687 | −1.906 |
First 60 of 482 rows.
View data
| BF₁₀ | prior width r |
|---|---|
| 3.076 | 0.0500 |
| 3.304 | 0.0557 |
| 3.556 | 0.0621 |
| 3.834 | 0.0692 |
| 4.140 | 0.0771 |
| 4.476 | 0.0859 |
| 4.845 | 0.0958 |
| 5.249 | 0.1067 |
| 5.691 | 0.1189 |
| 6.172 | 0.1325 |
| 6.694 | 0.1477 |
| 7.258 | 0.1646 |
| 7.866 | 0.1834 |
| 8.518 | 0.2044 |
| 9.211 | 0.2278 |
| 9.945 | 0.2538 |
| 10.715 | 0.2828 |
| 11.515 | 0.3152 |
| 12.337 | 0.3513 |
| 13.172 | 0.3914 |
| 14.005 | 0.4362 |
| 14.823 | 0.4861 |
| 15.606 | 0.5417 |
| 16.335 | 0.6037 |
| 16.989 | 0.6727 |
| 17.259 | 0.7071 |
| 17.547 | 0.7497 |
| 17.988 | 0.8354 |
| 18.294 | 0.9310 |
| 18.415 | 1 |
| 18.451 | 1.037 |
| 18.449 | 1.156 |
| 18.284 | 1.288 |
| 18.015 | 1.414 |
| 17.961 | 1.436 |
| 17.487 | 1.600 |
View data
| BF₁₀ | rows |
|---|---|
| 2.785 | 3 |
| 7.304 | 4 |
| 3.258 | 5 |
| 6.447 | 6 |
| 16.902 | 7 |
| 30.984 | 8 |
| 9.744 | 9 |
| 18.415 | 10 |
Assumptions
- Normality — Shapiro–Wilk p < .05 for drug1 − drug2 with fewer than 30 values; the normal likelihood may misstate the evidence.
- Independent observations — Each row should be a separate subject (pairs share a row).
Descriptives
| Sample | n | Mean | SD |
|---|---|---|---|
| drug1 − drug2 | 10 | −1.580 | 1.230 |
Evidence
| Quantity | Value |
|---|---|
| BF₁₀ (chosen alternative) | 18.415 |
| BF₁₀ (two-sided) | 18.415 |
| P(H₁ | data), equal prior odds | 0.9485 |
| Posterior mean of δ | −1.149 |
| Numerical error of BF (%) | 3.628e-9 |
- Effect: drug1 − drug2; prior δ ~ Cauchy(0, 1).
- Evidence: strong evidence for H₁. With equal prior odds, P(H₁ | data) = 0.948.
- A Bayes factor compares how well two hypotheses predicted the data; it is not a p-value and is not entered in the multiple-testing ledger.
The exact R script · R R version 4.5.1 (2025-06-13)
# Bayesian t-test (JZS Bayes factor)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bayes.ttest 1.0.1 · spec 2e59ac09d1c0d00f
# 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) # cs_bayes_ttest, cs_bayes_prior_scale, cs_bayes_evidence_label (twins of codesplash.stats.bayes)
# %% 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)
# %% Design
y <- "drug1"
r <- cs_bayes_prior_scale("t", "custom", 1)
alternative <- "two-sided"
mu <- 0
cred <- 0.95
design <- "paired"
y2 <- "drug2"
x1 <- as.numeric(df[[y]])
x2 <- as.numeric(df[[y2]])
if (length(x1) < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "A paired Bayesian t-test", min = 2, n = length(x1))
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", y, y2)) # t is undefined
res <- cs_bayes_ttest(x1, x2, paired = TRUE, mu = mu, r = r, alternative = alternative, cred = cred,
robustness = TRUE, sequential = TRUE)
n1 <- length(x1)
n2 <- NULL
mean_diff <- mean(x1 - x2)
groups <- list(list(name = sprintf("%s − %s", y, y2), v = x1 - x2))
effect_text <- sprintf("%s − %s", y, y2)
n <- if (design == "two-sample") n1 + n2 else n1
bf10 <- res$bf10
post <- res$post
# %% Assumptions
assumptions <- list()
sizes <- vapply(groups, function(gr) length(gr$v), numeric(1))
bad <- character(0)
for (gr in groups) if (length(gr$v) >= 3 && length(gr$v) <= 5000 && stats::shapiro.test(gr$v)$p.value < 0.05) bad <- c(bad, gr$name)
if (any(sizes < 3 | sizes > 5000)) {
status <- "info"
detail <- "Too few (or too many) values for Shapiro–Wilk; inspect the distribution."
} else if (length(bad) && min(sizes) < 30) {
status <- "warn"
detail <- sprintf("Shapiro–Wilk p < .05 for %s with fewer than 30 values; the normal likelihood may misstate the evidence.", paste(bad, collapse = ", "))
} else if (length(bad)) {
status <- "info"
detail <- sprintf("Shapiro–Wilk p < .05 for %s, but with 30 or more values the t likelihood is robust.", paste(bad, collapse = ", "))
} else {
status <- "pass"
detail <- "Shapiro–Wilk p ≥ .05."
}
assumptions[[length(assumptions) + 1]] <- list(key = "normality", label = "Normality", status = status, detail = detail)
if (design == "two-sample") {
dev <- lapply(groups, function(gr) abs(gr$v - stats::median(gr$v)))
grand <- mean(unlist(dev))
ssb <- sum(vapply(dev, function(d) length(d) * (mean(d) - grand)^2, numeric(1)))
ssw <- sum(vapply(dev, function(d) sum((d - mean(d))^2), numeric(1)))
bf_f <- if (ssw > 0) (ssb / 1) / (ssw / (n - 2)) else Inf
bf_p <- stats::pf(bf_f, 1, n - 2, lower.tail = FALSE)
vars <- vapply(groups, function(gr) stats::var(gr$v), numeric(1))
ratio <- max(vars) / max(min(vars), 1e-300)
status <- if (bf_p < 0.05 && ratio > 2) "warn" else if (bf_p < 0.05) "info" else "pass"
assumptions[[length(assumptions) + 1]] <- list(key = "equal_variance", label = "Equal variances", status = status,
detail = sprintf("Brown–Forsythe F = %.2f, %s; variance ratio %.2f. The JZS model has one common variance.", bf_f, cs_fmt_p(bf_p), ratio),
statistic = bf_f, p = bf_p)
}
assumptions[[length(assumptions) + 1]] <- list(key = "independence", label = "Independent observations", status = "info",
detail = "Each row should be a separate subject (pairs share a row).")
# %% Result
label <- cs_bayes_evidence_label(bf10)
direction <- switch(alternative, "two-sided" = "δ ≠ 0", greater = "δ > 0", less = "δ < 0")
summary <- sprintf(
"BF₁₀ = %s: the data are %s times more likely under %s than under %s — %s (Cauchy prior on δ, r = %s). Under the alternative, δ is most likely near %.2f (%s credible interval [%.2f, %.2f]).",
cs_fmt_num(bf10), cs_fmt_num(if (bf10 >= 1) bf10 else 1 / bf10),
if (bf10 >= 1) sprintf("the alternative (%s)", direction) else "the null (δ = 0)",
if (bf10 >= 1) "the null" else "the alternative", label, format(signif(r, 3)),
post$median, sprintf("%.0f%%", 100 * cred), post$low, post$high)
desc <- lapply(groups, function(gr) list(group = gr$name, n = length(gr$v), mean = mean(gr$v), sd = if (length(gr$v) > 1) stats::sd(gr$v) else NULL))
grid <- res$grid
charts <- list(cs_chart("prior_posterior", "prior-posterior", "Prior and posterior of δ",
list(x = cs_col("δ (standardized effect)", c(grid, grid)),
density = cs_col("density", c(res$prior_density, res$posterior_density)),
curve = cs_col("curve", c(rep("Prior", length(grid)), rep("Posterior", length(grid))), levels = c("Prior", "Posterior"))),
controls = list(point = 0, ci_low = post$low, ci_high = post$high, cred = cred, bf10 = bf10)))
if (!is.null(res$robust_r)) {
charts[[length(charts) + 1]] <- cs_chart("robustness", "bf-robustness", "Bayes factor across prior widths",
list(x = cs_col("prior width r", res$robust_r), bf = cs_col("BF₁₀", res$robust_bf)), controls = list(chosen = r))
}
if (!is.null(res$seq_n) && length(res$seq_n) >= 2) {
charts[[length(charts) + 1]] <- cs_chart("sequential", "bf-sequential", "Bayes factor as rows accumulate",
list(n = cs_col("rows", as.numeric(res$seq_n)), bf = cs_col("BF₁₀", res$seq_bf)))
}
cs_publish(list(
method = "bayes.ttest",
methodVersion = "1.0.1",
title = switch(design, "two-sample" = "Bayesian two-sample t-test", paired = "Bayesian paired t-test", "one-sample" = "Bayesian one-sample t-test"),
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = sprintf("BF₁₀ = %s (JZS, r = %s), δ = %.2f, %s CrI [%.2f, %.2f]", cs_fmt_num(bf10), format(signif(r, 3)), post$median,
sprintf("%.0f%%", 100 * cred), post$low, post$high),
statistics = list(
list(key = "bf10", label = sprintf("BF₁₀ (%s vs δ = 0)", direction), value = bf10),
list(key = "bf01", label = "BF₀₁", value = 1 / bf10),
list(key = "delta", label = "δ (posterior median)", value = post$median),
list(key = "cri", label = sprintf("%.0f%% credible interval", 100 * cred), value = c(post$low, post$high)),
list(key = "t", label = "t", value = res$t),
list(key = "df", label = "df", value = res$df)
),
tables = list(
list(key = "descriptives", title = "Descriptives",
columns = list(list(key = "group", label = "Sample", type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "mean", label = "Mean", type = "number"), list(key = "sd", label = "SD", type = "number")),
rows = desc),
list(key = "evidence", title = "Evidence",
columns = list(list(key = "quantity", label = "Quantity", type = "string"), list(key = "value", label = "Value", type = "number")),
rows = list(list(quantity = "BF₁₀ (chosen alternative)", value = bf10),
list(quantity = "BF₁₀ (two-sided)", value = res$bf10_two_sided),
list(quantity = "P(H₁ | data), equal prior odds", value = bf10 / (1 + bf10)),
list(quantity = "Posterior mean of δ", value = post$mean),
list(quantity = "Numerical error of BF (%)", value = 100 * res$error)))
),
effectSizes = list(list(key = "delta", label = "δ (posterior median)", value = post$median, ciLow = post$low, ciHigh = post$high, ciLevel = cred,
method = "posterior under H₁ (JZS), equal-tailed credible interval")),
assumptions = assumptions,
warnings = warnings,
notes = list(
sprintf("Effect: %s; prior δ ~ Cauchy(0, %s)%s.", effect_text, format(signif(r, 3)), if (alternative == "two-sided") "" else paste0(", restricted to ", direction)),
sprintf("Evidence: %s. With equal prior odds, P(H₁ | data) = %.3f.", label, bf10 / (1 + bf10)),
"A Bayes factor compares how well two hypotheses predicted the data; it is not a p-value and is not entered in the multiple-testing ledger."
),
values = list(
bf10 = bf10, bf01 = 1 / bf10, log_bf10 = res$log_bf10, bf10_two_sided = res$bf10_two_sided, p_h1 = bf10 / (1 + bf10),
t = res$t, df = res$df, n_eff = res$n_eff, r = r,
delta_mean = post$mean, delta_median = post$median, delta_low = post$low, delta_high = post$high,
n = n, n_1 = n1, n_2 = n2, mean_diff = mean_diff, error_pct = 100 * res$error,
bf_robust_min = if (!is.null(res$robust_bf)) min(res$robust_bf) else NULL,
bf_robust_max = if (!is.null(res$robust_bf)) max(res$robust_bf) else NULL, design = design
),
charts = charts
))
BF₁₀ = 18.42 (JZS, r = 1), δ = -1.14, 95% CrI [-2.01, -0.34]
- BF₁₀ (δ ≠ 0 vs δ = 0)
- 18.415
- BF₀₁
- 0.0543
- δ (posterior median)
- −1.139
- 95% credible interval
- [−2.013, −0.3423]
- t
- −4.062
- df
- 9
Effect size
- δ (posterior median) −1.139 95% CI [−2.013, −0.3423]
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Normality — Shapiro–Wilk p < .05 for drug1 − drug2 with fewer than 30 values; the normal likelihood may misstate the evidence.
- Independent observations — Each row should be a separate subject (pairs share a row).
Descriptives
| Sample | n | Mean | SD |
|---|---|---|---|
| drug1 − drug2 | 10 | −1.580 | 1.230 |
Evidence
| Quantity | Value |
|---|---|
| BF₁₀ (chosen alternative) | 18.415 |
| BF₁₀ (two-sided) | 18.415 |
| P(H₁ | data), equal prior odds | 0.9485 |
| Posterior mean of δ | −1.149 |
| Numerical error of BF (%) | 3.628e-9 |
- Effect: drug1 − drug2; prior δ ~ Cauchy(0, 1).
- Evidence: strong evidence for H₁. With equal prior odds, P(H₁ | data) = 0.948.
- A Bayes factor compares how well two hypotheses predicted the data; it is not a p-value and is not entered in the multiple-testing ledger.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Bayesian t-test (JZS Bayes factor)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bayes.ttest 1.0.1 · spec 2e59ac09d1c0d00f
# 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 math
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import bayes as bf # JZS Bayes factor, posterior of δ (twin of R cs_bayes_*)
# %% 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)
# %% Design
y = "drug1"
r = bf.prior_scale("t", "custom", 1)
alternative = "two-sided"
mu = 0
cred = 0.95
design = "paired"
y2 = "drug2"
x1 = df[y].to_numpy(dtype=float)
x2 = df[y2].to_numpy(dtype=float)
if len(x1) < 2:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="A paired Bayesian t-test", min=2, n=len(x1))
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"{y} − {y2}")
res = bf.ttest_bf(x1, x2, paired=True, mu=mu, r=r, alternative=alternative, cred=cred,
robustness=True, sequential=True)
n1, n2 = len(x1), None
mean_diff = float((x1 - x2).mean())
groups = [(f"{y} − {y2}", x1 - x2)]
effect_text = f"{y} − {y2}"
n = int(sum(len(v) for _, v in groups)) if design == "two-sample" else int(n1)
bf10 = res["bf10"]
post = res["post"]
# %% Assumptions (the t likelihood: normal data; two groups: one common variance)
assumptions = []
bad = [lv for lv, v in groups if 3 <= len(v) <= 5000 and stats.shapiro(v).pvalue < 0.05]
small = min(len(v) for _, v in groups) < 30
if any(not (3 <= len(v) <= 5000) for _, v in groups):
status, detail = "info", "Too few (or too many) values for Shapiro–Wilk; inspect the distribution."
elif bad and small:
status, detail = "warn", f"Shapiro–Wilk p < .05 for {', '.join(bad)} with fewer than 30 values; the normal likelihood may misstate the evidence."
elif bad:
status, detail = "info", f"Shapiro–Wilk p < .05 for {', '.join(bad)}, but with 30 or more values the t likelihood is robust."
else:
status, detail = "pass", "Shapiro–Wilk p ≥ .05."
assumptions.append({"key": "normality", "label": "Normality", "status": status, "detail": detail})
if design == "two-sample":
dev = [np.abs(v - np.median(v)) for _, v in groups] # Brown–Forsythe: one-way ANOVA on |x − median|
grand = np.concatenate(dev).mean()
ssb = sum(len(d) * (d.mean() - grand) ** 2 for d in dev)
ssw = sum(((d - d.mean()) ** 2).sum() for d in dev)
bf_f = (ssb / 1) / (ssw / (n - 2)) if ssw > 0 else math.inf
bf_p = float(stats.f.sf(bf_f, 1, n - 2))
ratio = max(groups[0][1].var(ddof=1), groups[1][1].var(ddof=1)) / max(min(groups[0][1].var(ddof=1), groups[1][1].var(ddof=1)), 1e-300)
status = "warn" if bf_p < 0.05 and ratio > 2 else "info" if bf_p < 0.05 else "pass"
assumptions.append({"key": "equal_variance", "label": "Equal variances", "status": status,
"detail": f"Brown–Forsythe F = {bf_f:.2f}, {cs.fmt_p(bf_p)}; variance ratio {ratio:.2f}. The JZS model has one common variance.",
"statistic": float(bf_f), "p": bf_p})
assumptions.append({"key": "independence", "label": "Independent observations", "status": "info",
"detail": "Each row should be a separate subject (pairs share a row)."})
# %% Result
label = bf.evidence_label(bf10)
direction = {"two-sided": "δ ≠ 0", "greater": "δ > 0", "less": "δ < 0"}[alternative]
summary = (
f"BF₁₀ = {cs.fmt_num(bf10)}: the data are {cs.fmt_num(bf10 if bf10 >= 1 else 1 / bf10)} times more likely under "
f"{'the alternative (' + direction + ')' if bf10 >= 1 else 'the null (δ = 0)'} than under {'the null' if bf10 >= 1 else 'the alternative'} — {label} "
f"(Cauchy prior on δ, r = {r:.3g}). Under the alternative, δ is most likely near {post['median']:.2f} "
f"({cred:.0%} credible interval [{post['low']:.2f}, {post['high']:.2f}])."
)
prior_odds_note = f"With equal prior odds, P(H₁ | data) = {bf10 / (1 + bf10):.3f}."
desc = [{"group": lv, "n": len(v), "mean": float(v.mean()), "sd": float(v.std(ddof=1)) if len(v) > 1 else None} for lv, v in groups]
grid = res["grid"]
charts = [cs.chart(
"prior_posterior", "prior-posterior", "Prior and posterior of δ",
{"x": cs.col("δ (standardized effect)", np.concatenate([grid, grid])),
"density": cs.col("density", np.concatenate([res["prior_density"], res["posterior_density"]])),
"curve": cs.col("curve", ["Prior"] * len(grid) + ["Posterior"] * len(grid), levels=["Prior", "Posterior"])},
controls={"point": 0, "ci_low": post["low"], "ci_high": post["high"], "cred": cred, "bf10": bf10},
)]
if "robust_r" in res:
charts.append(cs.chart("robustness", "bf-robustness", "Bayes factor across prior widths",
{"x": cs.col("prior width r", res["robust_r"]), "bf": cs.col("BF₁₀", res["robust_bf"])}, controls={"chosen": r}))
if "seq_n" in res and len(res["seq_n"]) >= 2:
charts.append(cs.chart("sequential", "bf-sequential", "Bayes factor as rows accumulate",
{"n": cs.col("rows", res["seq_n"]), "bf": cs.col("BF₁₀", res["seq_bf"])}))
cs.publish({
"method": "bayes.ttest",
"methodVersion": "1.0.1",
"title": {"two-sample": "Bayesian two-sample t-test", "paired": "Bayesian paired t-test", "one-sample": "Bayesian one-sample t-test"}[design],
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": f"BF₁₀ = {cs.fmt_num(bf10)} (JZS, r = {r:.3g}), δ = {post['median']:.2f}, {cred:.0%} CrI [{post['low']:.2f}, {post['high']:.2f}]",
"statistics": [
{"key": "bf10", "label": f"BF₁₀ ({direction} vs δ = 0)", "value": bf10},
{"key": "bf01", "label": "BF₀₁", "value": 1 / bf10},
{"key": "delta", "label": "δ (posterior median)", "value": post["median"]},
{"key": "cri", "label": f"{cred:.0%} credible interval", "value": [post["low"], post["high"]]},
{"key": "t", "label": "t", "value": res["t"]},
{"key": "df", "label": "df", "value": res["df"]},
],
"tables": [
{"key": "descriptives", "title": "Descriptives",
"columns": [{"key": "group", "label": "Sample", "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "mean", "label": "Mean", "type": "number"}, {"key": "sd", "label": "SD", "type": "number"}],
"rows": desc},
{"key": "evidence", "title": "Evidence",
"columns": [{"key": "quantity", "label": "Quantity", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
"rows": [{"quantity": "BF₁₀ (chosen alternative)", "value": bf10},
{"quantity": "BF₁₀ (two-sided)", "value": res["bf10_two_sided"]},
{"quantity": "P(H₁ | data), equal prior odds", "value": bf10 / (1 + bf10)},
{"quantity": "Posterior mean of δ", "value": post["mean"]},
{"quantity": "Numerical error of BF (%)", "value": 100 * res["error"]}]},
],
"effectSizes": [
{"key": "delta", "label": "δ (posterior median)", "value": post["median"], "ciLow": post["low"], "ciHigh": post["high"], "ciLevel": cred,
"method": "posterior under H₁ (JZS), equal-tailed credible interval"},
],
"assumptions": assumptions,
"warnings": warnings,
"notes": [
f"Effect: {effect_text}; prior δ ~ Cauchy(0, {r:.3g}){'' if alternative == 'two-sided' else ', restricted to ' + direction}.",
f"Evidence: {label}. {prior_odds_note}",
"A Bayes factor compares how well two hypotheses predicted the data; it is not a p-value and is not entered in the multiple-testing ledger.",
],
"values": {
"bf10": bf10, "bf01": 1 / bf10, "log_bf10": res["log_bf10"], "bf10_two_sided": res["bf10_two_sided"], "p_h1": bf10 / (1 + bf10),
"t": res["t"], "df": res["df"], "n_eff": res["n_eff"], "r": r,
"delta_mean": post["mean"], "delta_median": post["median"], "delta_low": post["low"], "delta_high": post["high"],
"n": n, "n_1": n1, "n_2": n2, "mean_diff": mean_diff, "error_pct": 100 * res["error"],
"bf_robust_min": float(np.min(res["robust_bf"])) if "robust_bf" in res else None,
"bf_robust_max": float(np.max(res["robust_bf"])) if "robust_bf" in res else None, "design": design,
},
"charts": charts,
})
Find Bayes factor as rows accumulate. The final value is = 18.4 from 10 pairs.
Was the path a steady climb, or did a few rows do most of the work? With so few rows, what would you say about the early part?
Peek at a p-value first
ExploreBExplorable · Optional stopping
What happens to the false-positive rate if you check the p-value as data arrive and stop when it is significant?
With this peeking schedule, what share of no-effect studies will end 'significant'?
Commit your prediction above to see the result
Make your prediction to see the result.
The false-positive rate climbs well past 5%, and the p-value you end on doesn't warn you. Keep that picture in mind as you read on.
Does stopping break a Bayes factor?
PredictPredict first
You stop collecting data when passes 10. What does that do?
Reveal
The Bayes factor's meaning holds: it still states the ratio of predictions for these data, and with the same priors, the posterior stays valid (Rouder, 2014). But stopping at a threshold still has costs. Effect estimates at the stopping point tend to be too large, and the chance of misleading evidence depends on your thresholds and your prior.
Plan, don't hope
ReflectA Bayes factor design analysisBayes factor design analysisPlans a study by the chance its Bayes factor reaches a threshold: for H₁ when the effect is real, and for H₀. works out, before you collect data, how often a design reaches your evidence threshold, and how often it reaches the wrong one.
For = 0.5 and a threshold of 3, two groups of 91 reach it with probability 0.80, and mislead with probability 0.02.
Method guide · power.bayesBayes factor design analysis (t-test)How many participants does a Bayesian t-test need to reach compelling evidence?Write your rule down in advance. What would you say if you reached your maximum without the threshold?
Evidence may not arrive
ReadEven with a fair rule, data can stay undecided. With 60 rows of ToothGrowth, = 0.99, so the data barely distinguish the two hypotheses.
Report this. "Inconclusive" is a real result, and it should stop you from claiming either that a difference exists or that it doesn't.
Check your understanding
CheckpointCheck yourself
You reorder the rows at random and rerun. What happens?
Show the answer
Answer: a
The final value uses all the rows. Only the route depends on their order.
Check yourself
You stopped at = 10 after 45 rows. What belongs in the report?
Show the answer
Answer: b
The rule is part of the design. A p-value computed as if the sample were fixed would be wrong after stopping at a threshold.
Check yourself
Why can an effect estimate be too large when you stop at a Bayes factor threshold?
Show the answer
Answer: b
Stopping on a run of favorable noise selects for high estimates. It is the same winner's curse as in frequentist stopping.
Do it in CodeSplash
In the appSequential Bayes factor is on by default, under the method's advanced options. Sort your data by arrival time before running, so the path means something.
import numpy as np
import pingouin as pg
from scipy import stats
diff = np.array([-1.2, -2.4, -1.3, -1.3, 0.0, -1.0, -1.8, -0.8, -4.6, -1.4])
for n in range(3, len(diff) + 1):
t = stats.ttest_1samp(diff[:n], 0).statistic
print(n, pg.bayesfactor_ttest(t, n, r=1))# install.packages("BayesFactor")
library(BayesFactor)
d <- with(sleep, extra[group == 1] - extra[group == 2])
for (n in 3:length(d)) {
print(c(n, extractBF(ttestBF(d[1:n], rscale = 1))$bf))
}Recap
Recap- A sequential chart shows how evidence built up. Its shape depends on the row order, and its end point doesn't.
- Stopping at a threshold doesn't change what a Bayes factor means, but it does raise estimates, and its error rates depend on the rule.
- Plan with a design analysis, and report the rule, the maximum and the prior.
- "Inconclusive" is a result.
Concepts in this lesson