The Self-Cleaning Oven
Building and checking models
Method or technique
Advanced
A good package should contain the means of its own testing.
What it is
A self-cleaning oven doesn’t need outside help to stay working. Gelman’s point is that statistical software should work the same way. A package that fits a model should include a way to check that it fits the model correctly, typically by simulating fake data from known parameter values, fitting the model, and confirming that the parameters are recovered.
Why it matters
Statistical code fails silently. A wrong standard-error formula, an indexing bug or a mis-specified prior still produces numbers that look plausible. Without a built-in self-test, these errors spread into published results. Fake-data simulation is the cheapest and most general check available, because it compares the code against a case where you know the right answer.
How it works
- Choose true parameter values \(\theta^*\).
- Simulate data \(y^{\text{fake}} \sim p(y \mid \theta^*)\) using the same model the code claims to fit.
- Run the fitting code on \(y^{\text{fake}}\) and record the estimate and interval.
- Repeat many times. Estimates should center on \(\theta^*\), and 95% intervals should cover \(\theta^*\) about 95% of the time.
Simulation-based calibration (SBC) extends this to Bayesian samplers by drawing \(\theta^*\) from the prior.
Simulated example
Our “package” estimates a treatment effect from a two-group experiment and reports a 95% interval. One version has a subtle bug: it forgets one group’s variance when computing the standard error. Run the built-in fake-data check and see whether the bug is caught.
Show simulation code
The R version uses base R, and the Python version uses NumPy and Matplotlib. Where the simulation draws random numbers, each language draws its own, so exact numbers differ slightly but show the same pattern. The numbered markers in the R code are explained under it.
import {rng, range, mean, variance, pct} from "../js/stats.js"
viewof buggy = Inputs.toggle({label: "Introduce the standard-error bug", value: true})
viewof nFake = Inputs.range([50, 1000], {value: 300, step: 50, label: "Fake datasets"})
viewof seed = Inputs.range([1, 500], {value: 18, step: 1, label: "Random seed"})
fakeCheck = {
const r = rng(seed);
const truth = 0.4, n = 50;
return range(nFake).map(k => {
const t = r.normals(n, truth, 1), c = r.normals(n, 0, 1);
const est = mean(t) - mean(c);
const se = buggy ? Math.sqrt(variance(t) / n) : Math.sqrt(variance(t) / n + variance(c) / n);
const lo = est - 1.96 * se, hi = est + 1.96 * se;
return {k, est, lo, hi, covered: lo <= truth && truth <= hi, truth};
});
}
Plot.plot({
ariaLabel: "The Self-Cleaning Oven: simulation chart",
ariaDescription: "Horizontal axis: Fake dataset (first 80 shown). Vertical axis: Estimate with 95% interval. The chart updates with the controls above it, and the summary below the charts states the result in words.",
height: 300,
x: {label: "Fake dataset (first 80 shown)"},
y: {label: "Estimate with 95% interval", grid: true},
marks: [
Plot.ruleX(fakeCheck.slice(0, 80), {x: "k", y1: "lo", y2: "hi", stroke: d => d.covered ? "#2166ac" : "#d6604d"}),
Plot.dot(fakeCheck.slice(0, 80), {x: "k", y: "est", r: 2, fill: "currentColor"}),
Plot.ruleY([0.4], {stroke: "currentColor", strokeDasharray: "4 3"})
]
})# The Self-Cleaning Oven: fake-data simulation catches a bug.
1buggy <- TRUE # introduce the standard-error bug
n_fake <- 300 # fake datasets
2set.seed(18)
truth <- 0.4
n <- 50
3res <- t(replicate(n_fake, {
tr <- rnorm(n, truth, 1)
ct <- rnorm(n, 0, 1)
est <- mean(tr) - mean(ct)
se <- if (buggy) {
4 sqrt(var(tr) / n)
} # bug: forgets the control
else {
sqrt(var(tr) / n + var(ct) / n)
}
c(est = est, lo = est - 1.96 * se, hi = est + 1.96 * se)
}))
5covered <- res[, "lo"] <= truth & truth <= res[, "hi"]
cat("95% intervals cover the true effect ", round(100 * mean(covered)),
"% of the time", if (buggy) " (the bug shows up)" else "", "\n",
sep = ""
)
k <- 1:min(100, n_fake)
6plot(res[k, "est"], k,
pch = 19, cex = 0.5, xlim = range(res[k, -1]),
col = ifelse(covered[k], "#2166ac", "#d6604d"),
xlab = "Estimate with 95% interval", ylab = "Fake dataset"
)
segments(res[k, "lo"], k, res[k, "hi"], k,
col = ifelse(covered[k], "#2166ac", "#d6604d")
)
abline(v = truth, lty = 2)- 1
- The page’s controls: whether to plant the standard-error bug, and how many fake datasets to simulate.
- 2
- Fixes the random numbers so the run is reproducible.
- 3
- Fake-data simulation: generate data from known parameters, run the analysis, and check that it recovers them.
- 4
- The planted bug: the standard error forgets the control group’s variance.
- 5
- Coverage of the nominal 95% intervals. With the bug, it falls well short, and the oven has cleaned itself.
- 6
- Intervals from the first 100 fake datasets, misses in red.
# The Self-Cleaning Oven: fake-data simulation catches a bug.
import numpy as np
import matplotlib.pyplot as plt
buggy = True # introduce the standard-error bug
n_fake = 300 # fake datasets
rng = np.random.default_rng(18)
truth, n = 0.4, 50
t = rng.normal(truth, 1, (n_fake, n))
c = rng.normal(0, 1, (n_fake, n))
est = t.mean(axis=1) - c.mean(axis=1)
if buggy:
se = np.sqrt(t.var(axis=1, ddof=1) / n) # bug: forgets the control
else:
se = np.sqrt(t.var(axis=1, ddof=1) / n + c.var(axis=1, ddof=1) / n)
lo, hi = est - 1.96 * se, est + 1.96 * se
covered = (lo <= truth) & (truth <= hi)
print(f"95% intervals cover the true effect {100 * covered.mean():.0f}% of "
"the time" + (" (the bug shows up)" if buggy else ""))
k = np.arange(min(100, n_fake))
cols = np.where(covered[k], "#2166ac", "#d6604d")
plt.hlines(k, lo[k], hi[k], colors=cols)
plt.scatter(est[k], k, s=8, c=cols)
plt.axvline(truth, color="black", linestyle="--")
plt.xlabel("Estimate with 95% interval")
plt.ylabel("Fake dataset")
plt.show()Key takeaways
- Every model-fitting routine should come with a fake-data check: simulate from known parameters, refit, and confirm recovery.
- Check coverage, not just point estimates. Bugs in uncertainty are the hardest to see.
- Self-testing code makes later changes safe, because you’ll know at once if something broke.
Source
- Andrew Gelman, Style guide for R code (2007).
- Cook, Gelman and Rubin, “Validation of software for Bayesian models using posterior quantiles”, JCGS (2006).