Inference and computation / E131

Trust the likelihood a little less: power posteriors, three ways to set the power, and when to fix the model instead

Type
Advanced worked example - read, run, modify
Data
Simulated: a calibration line with a known slope, 200 standards, under two kinds of noise the Gaussian model does not have (heavy tails; heavy tails whose scale grows with the signal). Real: the Hertzsprung-Russell diagram of the star cluster CYG OB1 (Rousseeuw and Leroy 1987, from the R package robustbase, GPL-2 or GPL-3), 47 stars of which four are documented giants
You will learn
What a wrong likelihood does to a posterior interval, and when it does nothing · the power posterior (the likelihood raised to a power $\eta$) in closed form and with pm.Potential · coverage against $\eta$ over thousands of repeated datasets · three ways to set $\eta$ from the data - SafeBayes, information matching (Lyddon, Holmes and Walker) and matching a bootstrap spread - and what each one is really for · the loss-likelihood bootstrap · the alternative of fixing the model (a Student-t likelihood, a model for the noise scale, a second population), and how to tell which problem to name

The question

A laboratory calibrates an instrument. It runs 200 standards of known concentration through it, reads the response, and fits a straight line. The slope is the instrument's sensitivity, and what the lab reports is the slope with a 90% interval. The model everyone reaches for says that the readings scatter around the line with Gaussian noise of one fixed size. Real instruments are not that polite: now and then a reading is far off, and the scatter usually grows with the signal. So the model is wrong, the lab knows it is wrong, and the question is what that does to the interval.

Bayesian inference has a clear answer for the case where the model is right, and a less comfortable one for the case where it is not. With a wrong model the posterior still settles down as the data grow, around the parameter value that makes the model least wrong (the one closest to the truth in Kullback-Leibler divergence). Two things can then go wrong, and they are different problems. The centre can be in the wrong place, if the least-wrong value is not the quantity we care about. And the width can be wrong even when the centre is right: the posterior's spread comes from the curvature of the model's own log-likelihood, which describes how much the estimate would vary if the model were true. How much it really varies from one dataset to the next is given by a different formula, the sandwich covariance of Huber (1967), and the two agree only when the model is right. Kleijn and van der Vaart (2012) made this precise, and the consequence is blunt: a 90% credible interval from a wrong model can cover the least-wrong value far less than 90% of the time.

One repair keeps the model and trusts it less. Raise the likelihood to a power $\eta$ before multiplying by the prior,

$$\pi_\eta(\theta \mid y) \;\propto\; \pi(\theta)\,\prod_{i=1}^n p(y_i \mid \theta)^{\eta},$$

and with $\eta < 1$ every observation counts as a fraction of one. The posterior keeps its centre and grows wider. The idea is old (Walker and Hjort 2001; Zhang 2006), it has a decision-theoretic derivation in which $\eta$ is the scale of a loss (Bissiri, Holmes and Walker 2016), and it goes by several names: power posterior, fractional posterior, tempered or generalised posterior, with $\eta$ called the learning rate. It leaves one question open, and that question is most of the subject: what should $\eta$ be? We try a fixed value, and three ways to set it from the data: SafeBayes (Grünwald and van Ommen 2017), the information-matching rule of Lyddon, Holmes and Walker (2019), and matching the spread of a bootstrap, a simple relative of the calibration of Syring and Martin (2019). The rules were designed with different aims, which a head-to-head comparison by Wu and Martin (2020) already showed, and we will see the same thing here.

The other repair is to fix the model: if the noise has heavy tails, say so with a Student-t likelihood; if its scale grows with the signal, model the scale. The lesson we expected to find was that tempering widens intervals and restores coverage, and that fixing the model is better when the problem can be named. The second half holds up well. The first half needs three corrections, and they are the most useful things in this notebook.

Everything is measured against a known answer. In the simulations the true slope is 2, so we can count how often each method's 90% interval contains it. For the stars the documentation says which four are giants, so the fit to the other 43 is the reference.

part question tool
1 What does the Gaussian model say about one dataset? the conjugate posterior in closed form, checked with NUTS
2 How often is its interval right? 4,000 repeated datasets in two worlds; the sandwich
3 What does the power $\eta$ do? coverage against $\eta$, exact
4 Can the data set $\eta$? SafeBayes, information matching, a bootstrap spread, the bootstrap itself
5 What if we fix the model instead? Student-t likelihood, a model for the scale, predictive checks
6 Who wins, at what cost? the scoreboard
7 Where does SafeBayes earn its place? a ridge regression with fifty regressors and "easy" points
8 Does any of it survive real outliers? the star cluster CYG OB1
9 Which method for which failure? a table of everything measured

A word on what is computed how. A Gaussian linear model with a conjugate prior has a power posterior in closed form, so every tempered fit here, including the 320,000 behind the coverage curves and the sequential fits SafeBayes needs, is exact and takes microseconds. NUTS is used where there is no closed form: the Student-t models, 4,000 refits on repeated datasets (1,000 of them a check of the Gaussian model against its closed form), the mixture for the stars, and one check that the closed form and pm.Potential agree.

import os

for name in ("OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS"):
    os.environ.setdefault(name, "1")  # before NumPy: one BLAS thread per chain

import logging
import sys
import time
import warnings

import arviz as az
import matplotlib.pyplot as plt
import nutpie
import numpy as np
import pandas as pd
import pymc as pm
import pytensor.tensor as pt
from scipy import special, stats

from pymc_challenges import data
from pymc_challenges.scoreboard import Scoreboard

sys.modules.pop("jax", None)   # ArviZ's lazy JAX stub; nothing here uses JAX

RANDOM_SEED = 131
az.style.use("arviz-variat")
plt.rcParams.update({"axes.labelsize": 10, "xtick.labelsize": 9, "ytick.labelsize": 9})
logging.getLogger("pymc").setLevel(logging.WARNING)
warnings.filterwarnings("ignore", category=RuntimeWarning)
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning)
pd.set_option("display.width", 170)
pd.set_option("display.max_columns", 30)
pd.set_option("display.float_format", lambda v: f"{v:.3g}")
T_START = time.time()

INK, MUTED, LIGHT, GRID = "#222222", "#8a8a8a", "#d9d9d9", "#e1e0d9"
BLUE, ORANGE, AQUA, YELLOW, MAGENTA, GREEN, VIOLET, RED = (
    "#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300", "#6250d6", "#e34948")


def tidy(ax, grid="y"):
    ax.spines[["top", "right"]].set_visible(False)
    ax.grid(False)
    if grid:
        ax.grid(axis=grid, color=GRID, lw=0.6)
    ax.set_axisbelow(True)

1 · Two worlds and one wrong model

The lab's standards are not spread evenly: there are many at low concentrations and a few at high ones, which we draw from a Gamma(2, 1) distribution (mean 2, a long right tail). The response is $y = \alpha + \beta x + \text{noise}$ with $\alpha = 1$ and $\beta = 2$, and the noise is where the two worlds differ.

  • World A, heavy tails. The noise is a Student-t with 3 degrees of freedom times a constant scale. This is the case the title of the notebook had in mind.
  • World B, heavy tails whose scale grows with the signal. The same Student-t noise, times $0.5\,(1 + x)$: a standard at concentration 5 is six times as noisy as a blank.

The constant scale of world A is chosen so that both worlds have the same noise variance on average. In both, the noise is symmetric around the line, so the least-wrong Gaussian model has the true line as its centre: only the width is in question. (Outliers that fall on one side move the centre, and that is a different notebook; the stars of part 8 give a taste.)

A_TRUE, B_TRUE = 1.0, 2.0
TRUTH = np.array([A_TRUE, B_TRUE])
N, NU_TRUE, S0_TRUE = 200, 3.0, 0.5
CI = 0.90
REPS_EXACT = 4000     # repeated datasets for the coverage curves, where the posterior is in closed form
REPS = 1000           # the first 1,000 of them: every method is run on these, NUTS included
COEF = ["intercept", "slope"]


def simulate(rng, reps, n, world):
    """`reps` datasets of `n` standards. World A: constant noise scale. World B: scale 0.5 (1 + x)."""
    x = rng.gamma(2.0, 1.0, size=(reps, n))
    # E[(1 + x)^2] = 11 for a Gamma(2, 1), so both worlds have the same average noise variance
    scale = S0_TRUE * (1 + x) if world == "B" else np.full_like(x, S0_TRUE * np.sqrt(11.0))
    return x, A_TRUE + B_TRUE * x + scale * rng.standard_t(NU_TRUE, size=(reps, n))


BIG = {w: simulate(np.random.default_rng([RANDOM_SEED, k]), REPS_EXACT, N, w) for k, w in enumerate("AB")}
SIM = {w: (BIG[w][0][:REPS], BIG[w][1][:REPS]) for w in "AB"}
BENCH = {w: (SIM[w][0][0], SIM[w][1][0]) for w in "AB"}       # the dataset on the bench: the first one

fig, axes = plt.subplots(1, 2, figsize=(12.5, 4.2), sharey=True)
grid_x = np.linspace(0, 9.5, 50)
for ax, w, title in zip(axes, "AB", ("World A: heavy tails, constant scale", "World B: heavy tails, scale grows with x")):
    xb, yb = BENCH[w]
    ax.scatter(xb, yb, s=14, color=BLUE, alpha=0.65, lw=0)
    ax.plot(grid_x, A_TRUE + B_TRUE * grid_x, color=INK, lw=1.3, label="true line")
    ols = np.polyfit(xb, yb, 1)
    ax.plot(grid_x, np.polyval(ols, grid_x), color=ORANGE, lw=1.3, ls="--", label=f"least squares, slope {ols[0]:.2f}")
    ax.set_xlabel("concentration of the standard, x")
    ax.set_title(title, loc="left")
    ax.legend(frameon=False, fontsize=9, loc="upper left")
    ax.set_xlim(0, 9.6)
    tidy(ax)
axes[0].set_ylabel("instrument response, y")
lim = np.abs(np.concatenate([BENCH[w][1] - A_TRUE - B_TRUE * BENCH[w][0] for w in "AB"])).max()
print(f"largest residual from the true line on the two benches: {lim:.1f}; "
      f"points outside the plotted range: {sum(int(((BENCH[w][1] < -8) | (BENCH[w][1] > 32)).sum()) for w in 'AB')}")
axes[0].set_ylim(-8, 32);
largest residual from the true line on the two benches: 13.5; points outside the plotted range: 0
Figure

Each panel is one dataset of 200 standards, the one we keep "on the bench" for single fits. In world A the stray readings are scattered along the whole line. In world B the points fan out to the right, and the few standards at high concentration, which have the most say about the slope, are also the noisiest.

The Gaussian model, in closed form

The model is $y_i \sim \mathcal N(\alpha + \beta x_i, \sigma^2)$. With the conjugate prior $(\alpha, \beta) \mid \sigma^2 \sim \mathcal N(0, \sigma^2 v_0 I)$ and $\sigma^2 \sim \text{Inv-Gamma}(a_0, b_0)$, the power posterior has the same form, with the data's sufficient statistics multiplied by $\eta$:

$$V_\eta = \big(I/v_0 + \eta X^\top X\big)^{-1}, \quad m_\eta = \eta V_\eta X^\top y, \quad a_\eta = a_0 + \tfrac{\eta n}{2}, \quad b_\eta = b_0 + \tfrac12\big(\eta\, y^\top y - m_\eta^\top V_\eta^{-1} m_\eta\big).$$

The coefficients then follow a multivariate Student-t with $2a_\eta$ degrees of freedom, centre $m_\eta$ and scale matrix $(b_\eta/a_\eta) V_\eta$. Two things can be read off. The centre $m_\eta$ is the least-squares line whatever $\eta$ is (the prior is weak: $v_0 = 100$, $a_0 = b_0 = 2$). And the scale matrix is the ordinary one divided by $\eta$, so intervals are wider by $1/\sqrt\eta$: $\eta = 0.25$ doubles them. Setting $\eta = 1$ gives the standard posterior.

PRIOR = dict(v0=100.0, a0=2.0, b0=2.0)


def design(x):
    return np.stack([np.ones_like(x), x], axis=-1)


def nig(XtX, Xty, yty, n, eta, v0, a0, b0):
    """Power posterior of a Gaussian linear model under the conjugate prior, from sufficient statistics.

    Returns m, V, a, b with beta | sigma2 ~ N(m, sigma2 V) and sigma2 ~ Inv-Gamma(a, b). Every
    argument may carry leading batch axes (datasets, or prefixes of one dataset)."""
    eta = np.asarray(eta, float)
    P = np.eye(XtX.shape[-1]) / v0 + eta[..., None, None] * XtX
    V = np.linalg.inv(P)
    m = np.einsum("...ij,...j->...i", V, eta[..., None] * Xty)
    a = a0 + eta * n / 2
    b = b0 + 0.5 * (eta * yty - np.einsum("...i,...ij,...j->...", m, P, m))
    return m, V, a, b


def power_posterior(x, y, eta=1.0, prior=PRIOR):
    """The eta-power posterior of the straight-line model for one dataset or a batch (eta per dataset)."""
    X = design(x)
    eta = np.broadcast_to(np.asarray(eta, float), x.shape[:-1])
    return nig(np.einsum("...ni,...nj->...ij", X, X), np.einsum("...ni,...n->...i", X, y),
               np.einsum("...n,...n->...", y, y), x.shape[-1], eta, **prior)


def coef_interval(post, prob=CI):
    """Centre and half-width of the central interval of each coefficient (exact Student-t quantiles)."""
    m, V, a, b = post
    scale = np.sqrt(np.asarray(b / a)[..., None] * np.einsum("...ii->...i", V))
    return m, np.asarray(stats.t.ppf(0.5 + prob / 2, 2 * a))[..., None] * scale


def coef_draws(post, rng, size):
    """Exact draws of the coefficients, shape (size, ..., 2)."""
    m, V, a, b = post
    L = np.linalg.cholesky(np.asarray(b / a)[..., None, None] * V)
    z = rng.standard_normal((size, *m.shape))
    g = rng.chisquare(2 * a, size=(size, *np.shape(a))) / (2 * a)
    return m + np.einsum("...ij,s...j->s...i", L, z) / np.sqrt(g)[..., None]


def covers(post, prob=CI):
    """Per dataset and coefficient: does the central interval hold the truth? Also the interval widths."""
    m, half = coef_interval(post, prob)
    return np.abs(m - TRUTH) <= half, 2 * half


sb = Scoreboard(truth={"slope": np.full(REPS, B_TRUE)}, ci_prob=CI)
x_b, y_b = BENCH["B"]
with sb.track("Gaussian, standard (closed form)"):
    post_b = power_posterior(x_b, y_b)
    m_b, half_b = coef_interval(post_b)
for k, name in enumerate(COEF):
    print(f"world B, bench dataset, {name:9s}: {m_b[k]:.3f}, 90% interval [{m_b[k] - half_b[k]:.3f}, {m_b[k] + half_b[k]:.3f}]"
          f"   (truth {TRUTH[k]:.0f})")
world B, bench dataset, intercept: 0.382, 90% interval [-0.046, 0.809]   (truth 1)
world B, bench dataset, slope    : 2.389, 90% interval [2.197, 2.581]   (truth 2)

On this dataset the interval for the slope runs from 2.20 to 2.58 and does not contain the true value of 2, and the intercept's does not contain 1. A 90% interval is allowed to miss one time in ten, so one miss proves nothing. Part 2 counts.

The same thing with pm.Potential

Outside conjugate models there is no closed form, and the power posterior is written in PyMC by adding the tempered log-likelihood as a potential: pm.Potential("name", eta * logp). A potential is simply a term added to the log-density, so NUTS samples $\log \pi(\theta) + \eta \sum_i \log p(y_i \mid \theta)$. We check that this gives the closed-form answer, at $\eta = 1$ and at $\eta = 0.5$. (E116 tempers a likelihood the same way, child by child, to allow for a known kind of dependence between test items.)

def power_model(x, y, eta, prior=PRIOR):
    """The same conjugate prior, with the Gaussian log-likelihood raised to the power eta."""
    with pm.Model() as model:
        xd, yd = pm.Data("x", x), pm.Data("y", y)
        sigma2 = pm.InverseGamma("sigma2", alpha=prior["a0"], beta=prior["b0"])
        a = pm.Normal("a", 0.0, pt.sqrt(sigma2 * prior["v0"]))
        b = pm.Normal("b", 0.0, pt.sqrt(sigma2 * prior["v0"]))
        loglik = pm.logp(pm.Normal.dist(a + b * xd, pt.sqrt(sigma2)), yd).sum()
        pm.Potential("tempered_loglik", eta * loglik)
    return model


def diagnose(idata, names):
    ds = idata.posterior.to_dataset()[list(names)]
    rhat = max(float(v.max()) for v in az.rhat(ds).data_vars.values())
    ess = min(float(v.min()) for v in az.ess(ds, method="bulk").data_vars.values())
    div = int(idata.sample_stats["diverging"].sum())
    return rhat, ess, div


IDATA, ESS = {}, {}
for eta in (1.0, 0.5):
    label = "Gaussian, standard (NUTS)" if eta == 1.0 else "power 0.5 (NUTS check)"
    if eta == 1.0:
        with sb.track(label):
            idata = pm.sample(model=power_model(x_b, y_b, eta), random_seed=RANDOM_SEED, progressbar=False)
    else:
        idata = pm.sample(model=power_model(x_b, y_b, eta), random_seed=RANDOM_SEED, progressbar=False)
    rhat, ess, div = diagnose(idata, ["a", "b", "sigma2"])
    IDATA[label], ESS[label] = idata, float(az.ess(idata.posterior["b"].to_dataset(), method="bulk")["b"])
    m, half = coef_interval(power_posterior(x_b, y_b, eta))
    q = np.quantile(idata.posterior["b"].values, [0.05, 0.5, 0.95])
    print(f"eta = {eta:.1f}: slope 5% / 50% / 95%   closed form {m[1] - half[1]:.3f} / {m[1]:.3f} / {m[1] + half[1]:.3f}"
          f"   NUTS {q[0]:.3f} / {q[1]:.3f} / {q[2]:.3f}   (r_hat {rhat:.3f}, smallest bulk ESS {ess:.0f}, "
          f"{div} divergences, {idata.posterior.sizes['chain']} chains x {idata.posterior.sizes['draw']} draws)")
print(f"interval width at eta = 0.5 over width at eta = 1: "
      f"{coef_interval(power_posterior(x_b, y_b, 0.5))[1][1] / half_b[1]:.3f}   (1/sqrt(0.5) = {1 / np.sqrt(0.5):.3f})")
eta = 1.0: slope 5% / 50% / 95%   closed form 2.197 / 2.389 / 2.581   NUTS 2.195 / 2.379 / 2.582   (r_hat 1.002, smallest bulk ESS 1363, 0 divergences, 4 chains x 1000 draws)
eta = 0.5: slope 5% / 50% / 95%   closed form 2.118 / 2.389 / 2.659   NUTS 2.121 / 2.383 / 2.651   (r_hat 1.003, smallest bulk ESS 1406, 0 divergences, 4 chains x 1000 draws)
interval width at eta = 0.5 over width at eta = 1: 1.410   (1/sqrt(0.5) = 1.414)

The quantiles agree to about 0.01, which is the Monte Carlo error of 4,000 draws, with no divergences. Halving $\eta$ leaves the median where it was and widens the interval by $\sqrt 2$.

The choice. A conjugate Gaussian model, so that every tempered posterior is exact and cheap, with pm.Potential shown as the general route. Rejected: independent priors with a half-normal on $\sigma$, which are what one would normally write, at the price of an MCMC run for each of the 320,000 fits behind the next two parts. What would change our mind: a model that is not conjugate, which is most models; then the coverage curve of part 3 costs a refit per dataset and per $\eta$, and one would use far fewer of both.

2 · How often is the interval right?

A 90% interval is a promise about repetition, so we repeat: 4,000 datasets from each world, the standard posterior for each (in closed form), and a count of how often the interval contains the truth. We look at more than the slope: the intercept, the noise standard deviation (against the true standard deviation of the noise, which is what the Gaussian model's $\sigma$ converges to), and a predictive interval for one new reading.

SD_NOISE = S0_TRUE * np.sqrt(11.0) * np.sqrt(NU_TRUE / (NU_TRUE - 2))     # sd of the noise, averaged over x

rows, ZSCORE = {}, {}
rng = np.random.default_rng([RANDOM_SEED, 20])
for w in "AB":
    x, y = BIG[w]
    post = power_posterior(x, y)
    m, V, a, b = post
    hit, width = covers(post)
    ZSCORE[w] = (m[:, 1] - B_TRUE) / np.sqrt(b / (a - 1) * V[:, 1, 1])        # error over posterior sd
    s_lo, s_hi = (np.sqrt(stats.invgamma.ppf(q, a, scale=b)) for q in (0.05, 0.95))
    x_new, y_new = simulate(rng, REPS_EXACT, 1, w)
    x_new, y_new = x_new[:, 0], y_new[:, 0]
    pred_sd = np.sqrt(b / a * (1 + V[:, 0, 0] + 2 * x_new * V[:, 0, 1] + x_new**2 * V[:, 1, 1]))
    pred_err = np.abs(y_new - m[:, 0] - m[:, 1] * x_new)
    rows[f"world {w}"] = {
        "slope": hit[:, 1].mean(), "intercept": hit[:, 0].mean(),
        "noise sd": np.mean((s_lo <= SD_NOISE) & (SD_NOISE <= s_hi)),
        "new reading, 50%": np.mean(pred_err <= stats.t.ppf(0.75, 2 * a) * pred_sd),
        "new reading, 90%": np.mean(pred_err <= stats.t.ppf(0.95, 2 * a) * pred_sd),
        "new reading, 99%": np.mean(pred_err <= stats.t.ppf(0.995, 2 * a) * pred_sd),
        "sd of slope error / posterior sd": ZSCORE[w].std(),
    }
print("share of 4,000 datasets in which the interval holds the truth (90% intervals unless stated)")
pd.DataFrame(rows).T.round(3)
share of 4,000 datasets in which the interval holds the truth (90% intervals unless stated)
slope intercept noise sd new reading, 50% new reading, 90% new reading, 99% sd of slope error / posterior sd
world A 0.906 0.903 0.33 0.656 0.92 0.976 0.995
world B 0.68 0.862 0.28 0.702 0.922 0.972 1.67
fig, axes = plt.subplots(1, 2, figsize=(12, 3.6), sharey=True)
zz = np.linspace(-5, 5, 300)
for ax, w in zip(axes, "AB"):
    ax.hist(ZSCORE[w], bins=np.linspace(-5, 5, 61), density=True, color=BLUE, alpha=0.55,
            label=f"4,000 datasets (sd {ZSCORE[w].std():.2f})")
    ax.plot(zz, stats.norm.pdf(zz), color=INK, lw=1.4, label="what the posterior expects: sd 1")
    ax.axvspan(-1.645, 1.645, color=LIGHT, alpha=0.35, lw=0)
    ax.set_xlabel("(posterior mean of the slope - true slope) / posterior sd")
    ax.set_title(f"World {w}", loc="left")
    ax.legend(frameon=False, fontsize=9, loc="upper left")
    ax.set_ylim(0, 0.62)
    tidy(ax)
axes[0].set_ylabel("density");
Figure

The first row is the surprise, and the first correction to what we expected. In world A, the heavy tails that give this notebook its question cost the slope's interval nothing: it covers 91% of the time and the intercept's 90%. The reason is that least squares does not need Gaussian noise to have the variance the model computes; it needs noise of constant variance, unrelated to $x$. Then the model's formula $\sigma^2 (X^\top X)^{-1}$ is the right one, and $\sigma^2$ is estimated by the residual variance whatever the shape of the noise. The left histogram shows it: the slope's error, measured in posterior standard deviations, has the spread the posterior expects. Wu and Martin (2020) saw the same in their regression experiments with Student-t errors: three of the four learning-rate rules they compared selected values between about 0.9 and 1, with coverage at the nominal level.

Heavy tails do break things in world A, just not that. The interval for the noise standard deviation is right in a third of the datasets, because a sample variance of heavy-tailed data is far more variable than the Gaussian model believes. And the predictive intervals have the wrong shape: the 50% interval is too wide (it catches about 66% of new readings) and the 99% interval too narrow. Tempering does not touch the shape of the predictive distribution, so it has nothing to offer there.

World B is the case that matters for the slope. The 90% interval contains the truth 68% of the time, and the right histogram shows why: the slope's real errors are about 1.7 times as large as the posterior thinks. The grey band, where the posterior puts 90% of its mass, holds much less.

The sandwich says how much

For least squares the two variances can be written down. The model's is $\Sigma = \bar s^2 A^{-1}/n$ with $A = E[\mathbf x \mathbf x^\top]$, $\mathbf x = (1, x)$ and $\bar s^2$ the average noise variance. The real one is the sandwich $S = A^{-1} B A^{-1}/n$ with $B = E[s^2(x)\,\mathbf x \mathbf x^\top]$, which weights each point's leverage by its own noise variance. If the noise variance does not depend on $x$, then $B = \bar s^2 A$ and the two are equal. For a Gamma(2, 1) design the moments are factorials, so both matrices are exact.

mom = lambda k: float(special.factorial(k + 1))                  # E[x^k] for x ~ Gamma(2, 1)
A_mat = np.array([[1.0, mom(1)], [mom(1), mom(2)]])
B_mat = np.array([[1 + 2 * mom(1) + mom(2), mom(1) + 2 * mom(2) + mom(3)],
                  [mom(1) + 2 * mom(2) + mom(3), mom(2) + 2 * mom(3) + mom(4)]])     # E[(1 + x)^2 x x']
Sigma_model = B_mat[0, 0] * np.linalg.inv(A_mat)                 # both up to the same factor
S_sandwich = np.linalg.inv(A_mat) @ B_mat @ np.linalg.inv(A_mat)
ratio = np.diag(S_sandwich) / np.diag(Sigma_model)
z90 = stats.norm.ppf(0.95)
for k, name in enumerate(COEF):
    print(f"world B, {name:9s}: real variance / model variance = {ratio[k]:.2f}; large-sample coverage of the 90% interval "
          f"{2 * stats.norm.cdf(z90 / np.sqrt(ratio[k])) - 1:.3f}; power that would repair it, 1 / ratio = {1 / ratio[k]:.2f}")
world B, intercept: real variance / model variance = 1.36; large-sample coverage of the 90% interval 0.841; power that would repair it, 1 / ratio = 0.73
world B, slope    : real variance / model variance = 3.00; large-sample coverage of the 90% interval 0.658; power that would repair it, 1 / ratio = 0.33

In world B the slope's real variance is three times what the model computes, and the intercept's is 1.36 times. A 90% interval that is too narrow by $\sqrt 3$ covers 66% in large samples, close to the 68% we counted at $n = 200$. These ratios already say what tempering would have to do, and they raise a difficulty: the slope asks for $\eta = 1/3$ and the intercept for $\eta = 0.73$. One number cannot be both.

The choice. Two worlds, because the one the question named turned out not to have the problem. Symmetric heavy tails of constant scale leave the coefficient intervals honest; what makes them dishonest is a noise scale that depends on $x$. Rejected: making world A look worse with 2 degrees of freedom or fewer, where the noise has no variance and the Gaussian model's $\sigma$ has nothing to converge to; that is a different problem from the one studied here. What would change our mind: a quantity of interest other than the line. For $\sigma$ or for a prediction, world A is badly wrong and stays wrong at any $\eta$.

3 · The dial: coverage against $\eta$

Now the picture the notebook is built around. For each of 40 values of $\eta$ between 0.05 and 2.5 we recompute the power posterior on all 4,000 datasets of each world and count coverage. Since the posterior is in closed form this is exact: there is no sampling error inside a fit, only the counting error of 4,000 datasets (half a percentage point at 90%).

ETA_GRID = np.exp(np.linspace(np.log(0.05), np.log(2.5), 40))


def coverage_curve(x, y, etas):
    return np.array([covers(power_posterior(x, y, eta))[0].mean(axis=0) for eta in etas])   # (eta, coefficient)


CURVE = {w: coverage_curve(*BIG[w], ETA_GRID) for w in "AB"}
ETA_ORACLE = {w: [float(np.interp(CI, CURVE[w][::-1, k], ETA_GRID[::-1])) for k in range(2)] for w in "AB"}

fig, axes = plt.subplots(1, 2, figsize=(12.5, 4.3), sharey=True)
for ax, w in zip(axes, "AB"):
    for k, (name, color) in enumerate(zip(COEF, (AQUA, BLUE))):
        ax.plot(ETA_GRID, CURVE[w][:, k], color=color, lw=2, label=f"{name} (90% at $\\eta$ = {ETA_ORACLE[w][k]:.2f})")
        ax.plot([ETA_ORACLE[w][k]], [CI], "o", color=color, ms=6)
    ax.axhline(CI, color=INK, lw=1, ls="--")
    ax.axvline(1.0, color=MUTED, lw=1, ls=":")
    ax.text(1.03, 0.42, "standard\nposterior", fontsize=8.5, color=MUTED, va="bottom")
    ax.set_xscale("log")
    ax.set_xticks([0.05, 0.1, 0.25, 0.5, 1, 2], ["0.05", "0.1", "0.25", "0.5", "1", "2"])
    ax.set_xlabel("power $\\eta$ on the likelihood")
    ax.set_title(f"World {w}", loc="left")
    ax.legend(frameon=False, fontsize=9, loc="lower left")
    ax.set_ylim(0.4, 1.01)
    tidy(ax)
axes[0].set_ylabel("coverage of the 90% interval, 4,000 datasets")
fig.suptitle("Coverage against the power: where the curve crosses 90% is the power the data needed", x=0.01, ha="left", fontsize=11)

cov_half = {w: covers(power_posterior(*BIG[w], 0.5)) for w in "AB"}
for w in "AB":
    print(f"world {w}: power needed for 90%: intercept {ETA_ORACLE[w][0]:.2f}, slope {ETA_ORACLE[w][1]:.2f};   "
          f"at eta = 0.5 coverage is intercept {cov_half[w][0][:, 0].mean():.3f}, slope {cov_half[w][0][:, 1].mean():.3f}")
print(f"world B: at the slope's power the intercept's interval covers {np.interp(ETA_ORACLE['B'][1], ETA_GRID, CURVE['B'][:, 0]):.3f}; "
      f"at the intercept's power the slope's covers {np.interp(ETA_ORACLE['B'][0], ETA_GRID, CURVE['B'][:, 1]):.3f}")
with sb.track("power 0.5 (fixed)"):
    post_half = power_posterior(x_b, y_b, 0.5)
    coef_interval(post_half)
with sb.track("power at the oracle value"):
    coef_interval(power_posterior(x_b, y_b, ETA_ORACLE["B"][1]))
world A: power needed for 90%: intercept 1.02, slope 1.04;   at eta = 0.5 coverage is intercept 0.977, slope 0.980
world B: power needed for 90%: intercept 0.81, slope 0.36;   at eta = 0.5 coverage is intercept 0.959, slope 0.842
world B: at the slope's power the intercept's interval covers 0.981; at the intercept's power the slope's covers 0.738
Figure

The curves fall from left to right: a smaller power means a wider interval and more coverage. The dot on each curve is where it crosses 90%, the power that world needed.

In world A both curves cross at $\eta = 1$ (1.02 and 1.04, which is 1 within the counting error). The standard posterior was already right, and any tempering only wastes information: at $\eta = 0.5$ the intervals are 41% wider and cover 98%.

In world B the slope's curve crosses 90% at $\eta = 0.36$ and the intercept's at 0.81, close to the large-sample values of 0.33 and 0.73 that the sandwich gave. So tempering can restore the slope's coverage, which is the lesson we set out to show, with a qualification the picture makes plain: one dial serves one parameter. At the power that is right for the slope the intercept's interval covers 98%, and at the power that is right for the intercept the slope's covers 74%. A fixed $\eta = 0.5$, the kind of round "half-trust" value one might pick without looking, is right for neither world: too cautious in A, not cautious enough for the slope in B (84%).

The dots are an oracle. They come from knowing the truth and repeating the experiment 4,000 times, which no analyst can do. The practical question is whether a single dataset can find them.

The choice. We read the needed power off the slope's curve, since the slope is what the lab reports, and carry it forward as an oracle row: the best that tempering could do if someone told us $\eta$. Rejected: a single "coverage" averaged over both coefficients, which would hide the fact that they disagree. What would change our mind: a problem where the model's and the real covariance differ by one common factor (overdispersed counts are the textbook case); then one $\eta$ repairs every parameter at once.

4 · Setting the dial from the data

SafeBayes

Grünwald and van Ommen (2017) choose $\eta$ by prediction. Go through the data in order; before seeing observation $i$, form the $\eta$-posterior from the first $i - 1$ observations, draw a parameter from it, and score how well that single draw predicts $y_i$ with the log loss. The expected score, summed over the data,

$$\sum_{i=1}^{n} E_{\theta \sim \pi_\eta(\cdot \mid y_{1:i-1})}\big[-\log p(y_i \mid x_i, \theta)\big],$$

is computed for each $\eta$ on a grid $1, 2^{-1/2}, 2^{-1}, \dots$ and the smallest wins (they call this version R-log-SafeBayes). The point of predicting with a draw instead of the posterior predictive is that a posterior which is too spread out is punished for it. For our conjugate model each term has a closed form:

$$\tfrac12 \log 2\pi b_\eta - \tfrac12 \psi(a_\eta) + \tfrac12 \frac{(y_i - \mathbf x_i^\top m_\eta)^2}{b_\eta / a_\eta} + \tfrac12\, \mathbf x_i^\top V_\eta\, \mathbf x_i ,$$

with all four quantities taken from the posterior of the first $i - 1$ observations and $\psi$ the digamma function. The paper also defines an "in-model" variant (I-log) that predicts with the posterior means of the coefficients and of $\sigma^2$: the last term disappears and the first two are evaluated at the posterior mean of $\sigma^2$.

SB_GRID = 2.0 ** (-np.arange(0, 17) / 2)          # 1, 0.71, 0.5, ..., 1/256


def prequential(X, y, eta, v0, a0, b0):
    """Log losses of predicting each y_i from the eta-posterior of the observations before it.

    X has shape (..., n, p). Returns the R-log loss (expected loss of a posterior draw) and the
    I-log loss (loss at the posterior means), each of shape (..., n)."""
    n = X.shape[-2]

    def before(c, axis):     # running sums over the first i observations, i = 0 .. n - 1
        return np.concatenate([np.zeros_like(np.take(c, [0], axis=axis)), np.delete(c, -1, axis=axis)], axis=axis)

    XX = before(np.cumsum(X[..., :, None] * X[..., None, :], axis=-3), -3)
    Xy = before(np.cumsum(X * y[..., None], axis=-2), -2)
    yy = before(np.cumsum(y**2, axis=-1), -1)
    m, V, a, b = nig(XX, Xy, yy, np.arange(n), np.full(y.shape, eta), v0, a0, b0)
    res2 = (y - np.einsum("...i,...i->...", X, m)) ** 2
    r_log = (0.5 * np.log(2 * np.pi * b) - 0.5 * special.digamma(a) + 0.5 * res2 * a / b
             + 0.5 * np.einsum("...i,...ij,...j->...", X, V, X))
    s2_bar = b / (a - 1)
    i_log = 0.5 * np.log(2 * np.pi * s2_bar) + 0.5 * res2 / s2_bar
    return r_log, i_log


def safebayes_losses(x, y, prior=PRIOR, grid=SB_GRID):
    """One-step-ahead losses for every eta of the grid: two arrays (eta, ..., n), R-log and I-log."""
    r_log, i_log = zip(*(prequential(design(x), y, eta, **prior) for eta in grid))
    return np.array(r_log), np.array(i_log)


def safebayes_pick(losses, grid=SB_GRID, skip=0):
    """The eta with the smallest summed loss (ties: the largest eta); `skip` leaves out the first observations."""
    return grid[losses[..., skip:].sum(axis=-1).argmin(axis=0)]


def safebayes(x, y, prior=PRIOR):
    """R-log-SafeBayes: the chosen power, for one dataset or one per dataset of a batch."""
    return safebayes_pick(safebayes_losses(x, y, prior)[0])


# a check of the closed form: the R-log loss of one step against a Monte Carlo average over posterior draws
rng = np.random.default_rng([RANDOM_SEED, 30])
i_chk, eta_chk = 60, 0.5
m, V, a, b = power_posterior(x_b[:i_chk], y_b[:i_chk], eta_chk)
s2 = b / rng.gamma(a, size=400_000)
beta = m + np.sqrt(s2)[:, None] * (rng.standard_normal((400_000, 2)) @ np.linalg.cholesky(V).T)
mc = np.mean(0.5 * np.log(2 * np.pi * s2) + 0.5 * (y_b[i_chk] - beta[:, 0] - beta[:, 1] * x_b[i_chk]) ** 2 / s2)
print(f"R-log loss of observation {i_chk + 1} at eta = {eta_chk}: closed form "
      f"{prequential(design(x_b), y_b, eta_chk, **PRIOR)[0][i_chk]:.4f}, Monte Carlo over 400,000 draws {mc:.4f}")

ETA_RULE = {w: {} for w in "AB"}
with sb.track("power set by SafeBayes"):
    eta_bench = safebayes(x_b, y_b)
    coef_interval(power_posterior(x_b, y_b, eta_bench))
for w in "AB":
    r_loss, i_loss = safebayes_losses(*SIM[w])
    r_pick, i_pick, i_late = safebayes_pick(r_loss), safebayes_pick(i_loss), safebayes_pick(i_loss, skip=10)
    ETA_RULE[w]["SafeBayes"] = r_pick
    print(f"world {w}: R-log SafeBayes picks eta = 1 in {np.mean(r_pick == 1):.0%} of {REPS} datasets (median {np.median(r_pick):.2f}, "
          f"smallest {r_pick.min():.2f});  I-log picks eta = 1 in {np.mean(i_pick == 1):.0%} (median {np.median(i_pick):.2f}), "
          f"and in {np.mean(i_late == 1):.0%} once the first ten observations are left out of its sum")
print(f"bench dataset of world B: SafeBayes picks eta = {eta_bench:.2f}")
r_mean = r_loss.sum(axis=-1).mean(axis=1)
del r_loss, i_loss
print("world B, mean summed R-log loss above its minimum, by eta:",
      ", ".join(f"{e:.2f}: {v - r_mean.min():.1f}" for e, v in zip(SB_GRID[:7], r_mean[:7])))
R-log loss of observation 61 at eta = 0.5: closed form 2.7494, Monte Carlo over 400,000 draws 2.7468
world A: R-log SafeBayes picks eta = 1 in 81% of 1000 datasets (median 1.00, smallest 0.04);  I-log picks eta = 1 in 3% (median 0.25), and in 80% once the first ten observations are left out of its sum
world B: R-log SafeBayes picks eta = 1 in 82% of 1000 datasets (median 1.00, smallest 0.09);  I-log picks eta = 1 in 3% (median 0.18), and in 73% once the first ten observations are left out of its sum
bench dataset of world B: SafeBayes picks eta = 1.00
world B, mean summed R-log loss above its minimum, by eta: 1.00: 0.0, 0.71: 1.8, 0.50: 7.2, 0.35: 16.4, 0.25: 30.2, 0.18: 49.4, 0.12: 75.5

SafeBayes keeps $\eta = 1$ in more than four datasets out of five, in world B as in world A. The summed loss rises steadily as $\eta$ falls: a wider posterior predicts worse with a single draw, and nothing in world B pays that back. So here SafeBayes leaves the standard posterior alone, and the slope's interval stays as overconfident as it was (the figure below puts its coverage at 71%).

This is not a malfunction. SafeBayes asks whether a smaller power would make the posterior predict better, which happens when the standard posterior fails to concentrate on the best parameter; we will build such a case in part 7. In world B the posterior concentrates exactly where it should. Its width is wrong, and width in the sense of repeated-sampling coverage is not what the criterion measures. Wu and Martin (2020) found the same in their regression example with noise that depends on a predictor: as the misspecification grew, intervals tempered by SafeBayes fell below the nominal level, and only the rule built around coverage (Syring and Martin 2019) held it.

The in-model variant behaves differently here, and for a poor reason. It picks a small power in both worlds (it keeps $\eta = 1$ in 3% of datasets), including world A where nothing needed repair. When the first ten observations are left out of its sum it goes back to $\eta = 1$ in three datasets out of four. So under our weak prior its choice is driven by the first handful of predictions, each made from a posterior based on a few points, and not by the 190 that follow. We do not use it further.

Information matching (Lyddon, Holmes and Walker)

Lyddon, Holmes and Walker (2019) start from a different idea of what the right spread is. Take the weighted likelihood bootstrap of Newton and Raftery (1994): draw random weights for the observations from a Dirichlet distribution, maximise the weighted likelihood, repeat. They show that these draws are an exact posterior under a nonparametric model of the data, they extend it to any loss (the loss-likelihood bootstrap), and they show that in large samples the draws have the sandwich covariance $J^{-1} I J^{-1}/n$, where $J$ is the expected Hessian of the loss and $I$ the expected outer product of its gradient. The power posterior has covariance $J^{-1}/(\eta n)$. A scalar cannot equate two matrices, so they equate one number, the trace of the inverse covariance (the Fisher information number), which gives

$$\hat\eta = \frac{\operatorname{tr}\big(J I^{-1} J\big)}{\operatorname{tr}(J)} = \frac{\operatorname{tr}\big(S^{-1}\big)}{\operatorname{tr}\big(\Sigma^{-1}\big)},$$

with $J$ and $I$ estimated at the fitted parameters. We apply it to the two coefficients, with $\sigma^2$ at its estimate; then $S$ is the usual sandwich estimate with squared residuals in the middle and $\Sigma$ the model's covariance. Since part 2 gave us both matrices exactly for world B, we can first ask what the rule is aiming at.

def lhw_population(D):
    """The trace rule when the coefficients are rescaled by the diagonal matrix D (a change of units)."""
    return np.trace(np.linalg.inv(D @ S_sandwich @ D)) / np.trace(np.linalg.inv(D @ Sigma_model @ D))


print(f"world B, population value of the trace rule: {lhw_population(np.eye(2)):.2f}   "
      f"(the slope alone needs {1 / ratio[1]:.2f}, the intercept alone {1 / ratio[0]:.2f})")
precision_ratio = np.diag(np.linalg.inv(S_sandwich)) / np.diag(np.linalg.inv(Sigma_model))
print(f"   diagonal of the inverse sandwich over diagonal of the inverse model covariance: "
      f"intercept {precision_ratio[0]:.2f}, slope {precision_ratio[1]:.2f}")
print(f"   the same data with x recorded in units ten times smaller (slope ten times smaller): {lhw_population(np.diag([1.0, 0.1])):.2f}")
print(f"   the same data with x recorded in units ten times larger (slope ten times larger): {lhw_population(np.diag([1.0, 10.0])):.2f}")


def eta_information(x, y):
    """Lyddon-Holmes-Walker plug-in for the coefficients, and the sandwich ratio of the slope alone."""
    X = design(x)
    XtX = np.einsum("...ni,...nj->...ij", X, X)
    beta = np.linalg.solve(XtX, np.einsum("...ni,...n->...i", X, y)[..., None])[..., 0]
    e2 = (y - np.einsum("...ni,...i->...n", X, beta)) ** 2
    s2 = e2.mean(axis=-1)
    meat = np.einsum("...n,...ni,...nj->...ij", e2, X, X)                 # n I s2^2, with J = XtX / (n s2)
    trace_rule = s2 * np.einsum("...ij,...ji->...", XtX @ np.linalg.inv(meat), XtX) / np.einsum("...ii->...", XtX)
    bread = np.linalg.inv(XtX)
    slope_rule = s2 * bread[..., 1, 1] / (bread @ meat @ bread)[..., 1, 1]
    return trace_rule, slope_rule


with sb.track("power set by information matching"):
    coef_interval(power_posterior(x_b, y_b, eta_information(x_b, y_b)[0]))
for w in "AB":
    ETA_RULE[w]["information matching"], sandwich_slope = eta_information(*SIM[w])
    q = np.quantile(ETA_RULE[w]["information matching"], [0.1, 0.5, 0.9])
    print(f"world {w}: plug-in trace rule over {REPS} datasets, 10% / median / 90%: {q[0]:.2f} / {q[1]:.2f} / {q[2]:.2f}")
world B, population value of the trace rule: 0.82   (the slope alone needs 0.33, the intercept alone 0.73)
   diagonal of the inverse sandwich over diagonal of the inverse model covariance: intercept 1.54, slope 0.70
   the same data with x recorded in units ten times smaller (slope ten times smaller): 0.70
   the same data with x recorded in units ten times larger (slope ten times larger): 1.50
world A: plug-in trace rule over 1000 datasets, 10% / median / 90%: 0.82 / 1.08 / 1.58
world B: plug-in trace rule over 1000 datasets, 10% / median / 90%: 0.75 / 0.82 / 1.03

Even with the true matrices, the trace rule asks for $\eta = 0.82$ in world B, when the slope needs 0.33. The rule compares the diagonals of the two inverse covariance matrices, which say how well each coefficient is known when the other is held fixed. On that scale the model and the sandwich differ much less than the variances do: by a factor 0.70 for the slope, and for the intercept the sandwich is even the more informative of the two, by 1.54. The plug-in estimate lands on the same 0.82, so this is the rule doing what it says, not an estimation problem. The authors are open about it: a scalar cannot match a covariance matrix, and they describe the result as calibrated to "asymptotic posterior information, as opposed to coverage".

The two extra lines show something that follows from the same formula. A trace of an information matrix adds quantities in different units, so it changes when the units do. Record the same concentrations in units ten times smaller and the rule says 0.70; in units ten times larger it says 1.50, which would narrow the intervals. Nothing about the data or the model has changed. Before using the rule on a model with parameters on different scales, standardise the predictors or decide which parameter the calibration is for.

In world A the rule centres a little above 1 (median 1.08) with a wide spread, from 0.8 to 1.6 for the middle 80% of datasets: the variance of a sandwich estimate rests on fourth moments of the noise, and Student-t noise with 3 degrees of freedom does not have them. Wu and Martin (2020) also found this rule selecting powers above 1 for heavy-tailed errors.

Matching the bootstrap spread of the slope

If one number is all we have, we can spend it on the parameter we report. Run the loss-likelihood bootstrap itself, which for squared-error loss is weighted least squares under Dirichlet weights, and choose $\eta$ so that the posterior variance of the slope equals the variance of the bootstrap slopes: $\hat\eta = \text{Var}_{\text{post}}(\beta) / \text{Var}_{\text{boot}}(\beta)$. This is our own targeted reading of the idea, not a rule from the paper; Syring and Martin (2019) develop the more careful version, which tunes $\eta$ until bootstrap intervals have the nominal coverage. The bootstrap draws are also a posterior in their own right, with no $\eta$ at all, so they get a row of their own.

def llb_draws(x, y, rng, B):
    """Loss-likelihood bootstrap of the least-squares line: (B, ..., 2) draws, one per Dirichlet weight vector."""
    X = design(x)
    n = x.shape[-1]
    out = np.empty((B, *x.shape[:-1], 2))
    step = max(1, 4_000_000 // (B * n))                       # datasets per chunk: weights stay under 32 MB
    flat_x, flat_y, flat_out = X.reshape(-1, n, 2), y.reshape(-1, n), out.reshape(B, -1, 2)
    for i in range(0, flat_x.shape[0], step):
        Xc, yc = flat_x[i:i + step], flat_y[i:i + step]
        wts = rng.dirichlet(np.ones(n), size=(B, Xc.shape[0])) * n
        WXX = np.einsum("brn,rni,rnj->brij", wts, Xc, Xc)
        WXy = np.einsum("brn,rni,rn->bri", wts, Xc, yc)
        flat_out[:, i:i + step] = np.linalg.solve(WXX, WXy[..., None])[..., 0]
    return out


def eta_bootstrap(x, y, draws):
    """Power that makes the posterior variance of the slope equal to its bootstrap variance."""
    m, V, a, b = power_posterior(x, y)
    return b / (a - 1) * V[..., 1, 1] / draws[..., 1].var(axis=0, ddof=1)


B_BOOT = 1000
rng = np.random.default_rng([RANDOM_SEED, 40])
with sb.track("loss-likelihood bootstrap (no power)"):
    bench_boot = llb_draws(x_b, y_b, rng, B_BOOT)
with sb.track("power matched to the bootstrap spread of the slope"):
    eta_boot_bench = eta_bootstrap(x_b, y_b, llb_draws(x_b, y_b, rng, B_BOOT))
    coef_interval(power_posterior(x_b, y_b, eta_boot_bench))
print(f"bench dataset of world B: bootstrap sd of the slope {bench_boot[:, 1].std(ddof=1):.3f}, posterior sd "
      f"{np.sqrt(post_b[3] / (post_b[2] - 1) * post_b[1][1, 1]):.3f}, so eta = {eta_boot_bench:.2f}")

LLB = {}
for w in "AB":
    LLB[w] = llb_draws(*SIM[w], rng, B_BOOT)                  # (B, datasets, 2)
    ETA_RULE[w]["bootstrap spread of the slope"] = eta_bootstrap(*SIM[w], LLB[w])
    q = np.quantile(ETA_RULE[w]["bootstrap spread of the slope"], [0.1, 0.5, 0.9])
    print(f"world {w}: eta matched to the bootstrap spread of the slope, 10% / median / 90%: {q[0]:.2f} / {q[1]:.2f} / {q[2]:.2f}")
bench dataset of world B: bootstrap sd of the slope 0.212, posterior sd 0.117, so eta = 0.28
world A: eta matched to the bootstrap spread of the slope, 10% / median / 90%: 0.73 / 1.10 / 1.62
world B: eta matched to the bootstrap spread of the slope, 10% / median / 90%: 0.28 / 0.52 / 0.87
RULES = ["SafeBayes", "information matching", "bootstrap spread of the slope"]
RULE_COLOR = dict(zip(RULES, (VIOLET, ORANGE, GREEN)))
rule_cov = {w: {r: covers(power_posterior(*SIM[w], ETA_RULE[w][r])) for r in RULES} for w in "AB"}
llb_cov = {}
for w in "AB":
    lo, hi = np.quantile(LLB[w], [0.05, 0.95], axis=0)
    llb_cov[w] = ((lo <= TRUTH) & (TRUTH <= hi), hi - lo)

fig, axes = plt.subplots(2, 2, figsize=(12.5, 6.2), sharex=True, gridspec_kw={"height_ratios": [2.6, 1]})
for j, w in enumerate("AB"):
    ax = axes[0, j]
    ax.plot(ETA_GRID, CURVE[w][:, 1], color=BLUE, lw=2, label="slope, coverage if $\\eta$ were fixed")
    ax.plot([ETA_ORACLE[w][1]], [CI], "o", color=BLUE, ms=7)
    ax.annotate("needed", (ETA_ORACLE[w][1], CI), xytext=(-6, -13), textcoords="offset points", ha="right", fontsize=8.5, color=BLUE)
    for r in RULES:
        c = rule_cov[w][r][0][:, 1].mean()
        ax.plot([np.median(ETA_RULE[w][r])], [c], "D", color=RULE_COLOR[r], ms=7, mec="white", mew=0.8,
                label=f"{r}: covers {c:.0%}")
    ax.axhline(CI, color=INK, lw=1, ls="--")
    ax.axvline(1.0, color=MUTED, lw=1, ls=":")
    ax.set_xscale("log")
    ax.set_ylim(0.55, 1.01)
    ax.set_title(f"World {w}: the slope's 90% interval", loc="left")
    ax.legend(frameon=False, fontsize=8.5, loc="lower left")
    tidy(ax)
    ax = axes[1, j]
    for i, r in enumerate(RULES):
        q = np.quantile(ETA_RULE[w][r], [0.1, 0.25, 0.5, 0.75, 0.9])
        ax.plot([q[0], q[4]], [i, i], color=RULE_COLOR[r], lw=1.5)
        ax.plot([q[1], q[3]], [i, i], color=RULE_COLOR[r], lw=5, solid_capstyle="butt")
        ax.plot([q[2]], [i], "D", color=RULE_COLOR[r], ms=7, mec="white", mew=0.8)
    ax.axvline(ETA_ORACLE[w][1], color=BLUE, lw=1.2)
    ax.axvline(1.0, color=MUTED, lw=1, ls=":")
    ax.set_yticks(range(len(RULES)), RULES if j == 0 else [""] * len(RULES), fontsize=9)
    ax.set_ylim(len(RULES) - 0.5, -0.5)
    ax.set_xticks([0.05, 0.1, 0.25, 0.5, 1, 2], ["0.05", "0.1", "0.25", "0.5", "1", "2"])
    ax.set_xlabel("power $\\eta$ chosen in each dataset (median, middle half, middle 80%)")
    tidy(ax, grid="x")
axes[0, 0].set_ylabel("coverage");

rule_rows = {}
for w in "AB":
    std = covers(power_posterior(*SIM[w]))
    entries = {"standard posterior": (1.0, std), **{r: (np.median(ETA_RULE[w][r]), rule_cov[w][r]) for r in RULES},
               "loss-likelihood bootstrap (no power)": (np.nan, llb_cov[w])}
    for name, (eta, (hit, width)) in entries.items():
        rule_rows[(f"world {w}", name)] = {"median eta": eta, "slope coverage": hit[:, 1].mean(),
                                           "intercept coverage": hit[:, 0].mean(), "slope width": width[:, 1].mean()}
print(f"over the {REPS} datasets of each world")
pd.DataFrame(rule_rows).T.round(3)
over the 1000 datasets of each world
median eta slope coverage intercept coverage slope width
world A standard posterior 1 0.893 0.906 0.463
SafeBayes 1 0.91 0.915 0.504
information matching 1.08 0.88 0.882 0.438
bootstrap spread of the slope 1.1 0.903 0.888 0.449
loss-likelihood bootstrap (no power) NaN 0.863 0.88 0.444
world B standard posterior 1 0.692 0.851 0.451
SafeBayes 1 0.713 0.867 0.482
information matching 0.817 0.726 0.881 0.482
bootstrap spread of the slope 0.523 0.854 0.97 0.651
loss-likelihood bootstrap (no power) NaN 0.834 0.85 0.647
Figure

The top panels repeat the slope's curve from part 3, with one diamond per rule placed at its median power and at the coverage it actually achieved over the 1,000 datasets (each dataset using its own $\hat\eta$). The bottom panels show how the chosen powers are spread, with the blue line at the power the slope needed. The table gives the same numbers, with the intercept.

In world A every rule stays near 1, which is correct. Information matching leans above 1 and gives up a point of coverage (88% against 89% for the standard posterior on these datasets); the other two lose nothing.

In world B the three rules line up in the order of how directly they aim at the slope's interval. SafeBayes stays at 1 and covers 71%, against 69% for the standard posterior. Information matching moves to about 0.8 and covers 73%. Matching the bootstrap spread of the slope goes to about 0.5 and covers 85%: a real repair, three quarters of the way from 69% to 90%, but not all of it, and it pushes the intercept's interval to 97%. It stops short because the bootstrap itself is too narrow at this sample size. Its own 90% intervals cover the slope 83% of the time, and 86% in world A, where the standard posterior needed no help. The slope rests on the few standards at high concentration, and with so few of them the bootstrap underestimates how far the slope can move. That is a small-sample effect, and the next table shows it fading as the sample grows.

rows, REPS_N = {}, 400
rng = np.random.default_rng([RANDOM_SEED, 50])
for n in (200, 1000, 5000):
    x, y = simulate(rng, REPS_N, n, "B")
    draws = llb_draws(x, y, rng, 200)
    eta = eta_bootstrap(x, y, draws)
    lo, hi = np.quantile(draws[..., 1], [0.05, 0.95], axis=0)
    rows[n] = {"standard posterior": covers(power_posterior(x, y))[0][:, 1].mean(),
               "median eta of the bootstrap rule": np.median(eta),
               "power matched to the bootstrap spread": covers(power_posterior(x, y, eta))[0][:, 1].mean(),
               "the bootstrap itself": np.mean((lo <= B_TRUE) & (B_TRUE <= hi))}
print(f"world B, coverage of the slope's 90% interval over {REPS_N} fresh datasets of each size")
pd.DataFrame(rows).T.rename_axis("n").round(3)
world B, coverage of the slope's 90% interval over 400 fresh datasets of each size
standard posterior median eta of the bootstrap rule power matched to the bootstrap spread the bootstrap itself
n
200 0.698 0.539 0.84 0.815
1000 0.718 0.418 0.892 0.878
5000 0.702 0.377 0.915 0.902

With 1,000 standards the bootstrap-matched power is about 0.42 and the interval covers 89%; with 5,000 it is 0.38, near the large-sample value of a third, and covers 91%. The standard posterior stays near 70% however much data there is, as the sandwich said it would. So the second correction to the expected lesson is this: tempering restores coverage only if the power is chosen by a rule that targets the interval we care about, and only as well as that rule's own estimate of the real spread. Two of the three rules were not built for that, and in world B they leave the slope where it was.

The choice. For the slope's interval we keep the power matched to the bootstrap spread of the slope. Rejected: SafeBayes, which answers a question about prediction and here correctly reports that there is nothing to fix; the trace rule, which averages over parameters in a way that depends on their units; and a fixed 0.5. What would change our mind: several parameters of equal interest. Then no single $\eta$ will do, and the bootstrap draws themselves, or a normal posterior centred at the estimate with the sandwich covariance (Müller 2013), give each parameter its own correction.

5 · Fix the model instead

Tempering treats the symptom. The other route is to say what is wrong and put it in the likelihood. World B has two things wrong with it, so there are two candidate repairs.

  • Student-t likelihood. $y_i \sim t_\nu(\alpha + \beta x_i, s)$ with the degrees of freedom $\nu$ estimated. This names the heavy tails and nothing else.
  • Student-t likelihood with a model for the scale. The same, with scale $s\,(1 + g\,x_i)$ and $g \ge 0$ estimated. This names both problems. It has the same form as the simulator, so it is the best case for "fixing the model"; real instruments do not come with their variance function printed on the side.

Priors are weak: $\alpha, \beta \sim \mathcal N(0, 10)$, $s \sim \text{Half-Normal}(5)$, $g \sim \text{Half-Normal}(2)$, and $\nu \sim \text{Gamma}(2, 0.1)$, which has mean 20 and leaves room for both heavy and nearly Gaussian tails. There is no closed form, so these are NUTS fits (nutpie, four chains of 1,000 draws for the bench dataset).

def t_model(x, y, scale_model):
    with pm.Model() as model:
        xd, yd = pm.Data("x", x), pm.Data("y", y)
        a = pm.Normal("a", 0.0, 10.0)
        b = pm.Normal("b", 0.0, 10.0)
        s = pm.HalfNormal("s", 5.0)
        nu = pm.Gamma("nu", alpha=2.0, beta=0.1)
        scale = s * (1 + pm.HalfNormal("g", 2.0) * xd) if scale_model else s
        pm.StudentT("obs", nu=nu, mu=a + b * xd, sigma=scale, observed=yd)
    return model


T_MODELS = {"Student-t likelihood": False, "Student-t with a scale model": True}
for label, scale_model in T_MODELS.items():
    with sb.track(label):
        idata = pm.sample(model=t_model(x_b, y_b, scale_model), random_seed=RANDOM_SEED, progressbar=False)
    names = ["a", "b", "s", "nu"] + (["g"] if scale_model else [])
    rhat, ess, div = diagnose(idata, names)
    IDATA[label], ESS[label] = idata, float(az.ess(idata.posterior["b"].to_dataset(), method="bulk")["b"])
    print(f"{label}: r_hat {rhat:.3f}, smallest bulk ESS {ess:.0f}, {div} divergences")
    print(az.summary(idata, var_names=names, ci_kind="eti", ci_prob=0.9, round_to=3)[["mean", "sd", "eti90_lb", "eti90_ub"]]
          .to_string())
Student-t likelihood: r_hat 1.001, smallest bulk ESS 1423, 0 divergences
    mean    sd  eti90_lb  eti90_ub
a  0.884 0.183     0.584      1.18
b   1.95 0.105      1.78      2.12
s    1.2  0.12      1.01      1.41
nu  2.63 0.606      1.82      3.78
Student-t with a scale model: r_hat 1.002, smallest bulk ESS 1289, 0 divergences
    mean    sd  eti90_lb  eti90_ub
a   1.13 0.165     0.854      1.39
b   1.85 0.129      1.64      2.06
s  0.556  0.11     0.388     0.747
nu  10.8  7.58       4.1      25.6
g   1.12 0.373     0.627      1.78

Both fits are clean. On the bench dataset the plain Student-t puts $\nu$ between 2 and 4. The model with a scale term finds $g$ well away from zero, with a 90% interval from 0.6 to 1.8 that includes the true value of 1, and a larger and much less certain $\nu$, since the fan no longer has to be explained as tail. Both intervals for the slope contain 2 on this dataset, which the Gaussian one did not.

How would we know which problem to name?

In a simulation we know. With real data we would ask the fitted model to reproduce features of the residuals that a wrong model cannot. Two summaries of the residuals from a straight-line fit do the job here: the fan, the typical size of a residual in the top third of $x$ divided by the same in the bottom third, and the tail, the largest residual in robust standard-deviation units. For each model we draw 1,000 replicated datasets from the posterior predictive and compare.

def residual_summaries(x, y):
    """Fan: median |residual| in the top third of x over the bottom third. Tail: largest |residual| in robust sd units."""
    X = design(x)
    e = y - y @ (X @ np.linalg.solve(X.T @ X, X.T)).T
    lo, hi = x <= np.quantile(x, 1 / 3), x >= np.quantile(x, 2 / 3)
    fan = np.median(np.abs(e[..., hi]), axis=-1) / np.median(np.abs(e[..., lo]), axis=-1)
    tail = np.abs(e).max(axis=-1) / (1.4826 * np.median(np.abs(e), axis=-1))
    return fan, tail


rng = np.random.default_rng([RANDOM_SEED, 60])
S_PPC = 1000
m, V, a, b = post_b
s2 = b / rng.gamma(a, size=S_PPC)
beta = m + np.sqrt(s2)[:, None] * (rng.standard_normal((S_PPC, 2)) @ np.linalg.cholesky(V).T)
REPLICATED = {"Gaussian": beta[:, [0]] + beta[:, [1]] * x_b + np.sqrt(s2)[:, None] * rng.standard_normal((S_PPC, N))}
for label, scale_model in T_MODELS.items():
    p = az.extract(IDATA[label], num_samples=S_PPC, random_seed=RANDOM_SEED)
    scale = p["s"].values[:, None] * ((1 + p["g"].values[:, None] * x_b) if scale_model else 1.0)
    REPLICATED[label] = (p["a"].values[:, None] + p["b"].values[:, None] * x_b
                         + scale * rng.standard_t(p["nu"].values[:, None], size=(S_PPC, N)))

observed = residual_summaries(x_b, y_b)
fig, axes = plt.subplots(2, 3, figsize=(12.5, 5.2), sharex="row")
for j, (label, y_rep) in enumerate(REPLICATED.items()):
    for i, (name, obs, rep) in enumerate(zip(("fan: spread at high x / spread at low x", "tail: largest residual, robust sd units"),
                                             observed, residual_summaries(x_b, y_rep))):
        ax = axes[i, j]
        hi = np.quantile(rep, 0.99) if i == 0 else 60
        ax.hist(np.clip(rep, None, hi), bins=40, color=LIGHT)
        ax.axvline(obs, color=RED, lw=1.8)
        p_val = np.mean(rep >= obs)
        ax.set_title(f"{label}\nP(replicated $\\geq$ observed) = {p_val:.2f}" if i == 0 else f"P(replicated $\\geq$ observed) = {p_val:.2f}",
                     loc="left", fontsize=9.5)
        ax.set_xlabel(name)
        ax.set_yticks([])
        tidy(ax, grid=None)
        print(f"{label:30s} {name.split(':')[0]:5s} observed {obs:5.2f}, replicated median {np.median(rep):5.2f}, "
              f"P(replicated >= observed) = {p_val:.3f}")
Gaussian                       fan   observed  2.49, replicated median  1.01, P(replicated >= observed) = 0.000
Gaussian                       tail  observed  7.69, replicated median  2.92, P(replicated >= observed) = 0.000
Student-t likelihood           fan   observed  2.49, replicated median  0.99, P(replicated >= observed) = 0.002
Student-t likelihood           tail  observed  7.69, replicated median  8.45, P(replicated >= observed) = 0.581
Student-t with a scale model   fan   observed  2.49, replicated median  2.50, P(replicated >= observed) = 0.501
Student-t with a scale model   tail  observed  7.69, replicated median  6.11, P(replicated >= observed) = 0.246
Figure

The red line is the bench dataset; the grey histograms are what each fitted model expects (the tail panels are clipped at 60). The Gaussian model fails both checks: its replicated data never fan as much as the real data and never contain a residual as extreme. The Student-t passes the tail check and still fails the fan check: heavy tails do not make the scatter grow with $x$. The model with a scale term passes both. Two residual plots would have told the lab which problem to name.

Coverage of the fixed models

One dataset proves nothing about intervals, so the Student-t models go through the same repeated test as everything else. The Student-t likelihood is refitted by NUTS to each of the 1,000 datasets of both worlds, and the model with a scale term to those of world B. Each model is compiled once with nutpie and the data are swapped in with with_data, which makes a refit cost a few hundredths of a second; each uses two chains of 400 draws after 300 warm-up steps. The standard Gaussian posterior goes through the same loop in world B, as a check that NUTS and the closed form agree at scale.

def refit(model, xs, ys, names=("a", "b"), draws=400, tune=300):
    """NUTS on every dataset with one compiled model: draws (2 * draws, datasets, len(names)) and divergences."""
    compiled = nutpie.compile_pymc_model(model)
    out = np.empty((2 * draws, len(xs), len(names)))
    divergences = 0
    for r in range(len(xs)):
        trace = nutpie.sample(compiled.with_data(x=xs[r], y=ys[r]), draws=draws, tune=tune, chains=2, cores=2,
                              seed=RANDOM_SEED + r, progress_bar=False)
        for k, name in enumerate(names):
            out[:, r, k] = trace.posterior[name].values.ravel()
        divergences += int(trace.sample_stats["diverging"].sum())
    return out, divergences


MCMC = {w: {} for w in "AB"}
t0 = time.time()
for w in "AB":
    xs, ys = SIM[w]
    fits = {"Student-t likelihood": False} if w == "A" else {"Gaussian, standard (NUTS)": None, **T_MODELS}
    for label, scale_model in fits.items():
        model = power_model(xs[0], ys[0], 1.0) if scale_model is None else t_model(xs[0], ys[0], scale_model)
        t1 = time.time()
        MCMC[w][label], div = refit(model, xs, ys)
        lo, hi = np.quantile(MCMC[w][label], [0.05, 0.95], axis=0)
        cov = ((lo <= TRUTH) & (TRUTH <= hi)).mean(axis=0)
        print(f"world {w}, {label:30s}: {REPS} fits in {time.time() - t1:4.0f} s, {div} divergent transitions in all; "
              f"coverage intercept {cov[0]:.3f}, slope {cov[1]:.3f}; mean width of the slope's interval {(hi - lo)[:, 1].mean():.3f}")
print(f"all refits: {time.time() - t0:.0f} s")
world A, Student-t likelihood          : 1000 fits in   53 s, 0 divergent transitions in all; coverage intercept 0.906, slope 0.916; mean width of the slope's interval 0.348
world B, Gaussian, standard (NUTS)     : 1000 fits in   33 s, 0 divergent transitions in all; coverage intercept 0.848, slope 0.694; mean width of the slope's interval 0.448
world B, Student-t likelihood          : 1000 fits in   48 s, 0 divergent transitions in all; coverage intercept 0.907, slope 0.801; mean width of the slope's interval 0.343
world B, Student-t with a scale model  : 1000 fits in   85 s, 0 divergent transitions in all; coverage intercept 0.903, slope 0.907; mean width of the slope's interval 0.374
all refits: 219 s

No fit among the 4,000 had a divergent transition. In world A, where heavy tails are the whole problem, the Student-t likelihood keeps the slope's coverage at the nominal level (92%) and its intervals are a quarter narrower than the Gaussian model's: it gains efficiency that no power on a Gaussian likelihood can give, since tempering only ever widens.

In world B the plain Student-t is a partial repair of an interesting kind. Its slope interval is narrower than the standard Gaussian one and still covers more often (80% against 69%). A likelihood that discounts large residuals also discounts the noisy standards at high concentration, which is roughly what a weighted fit would do. But it named only one of the two problems and it remains overconfident. The model that names both covers 91% for the slope and 90% for the intercept, with a slope interval half as wide as that of the Gaussian model tempered to the same coverage.

The choice. For world B, the Student-t likelihood with a scale model. Rejected: the plain Student-t, which the fan check rules out, and tempering, which reaches the same coverage only at the oracle power and then with intervals twice as wide. What would change our mind: a failure we could detect but not describe. A predictive check that fails with no pattern anyone can name leaves tempering, or the bootstrap, as the honest fallback.

6 · The scoreboard

Every method now has the same three numbers on the same 1,000 datasets of world B: the error of the slope's posterior mean, the coverage of its 90% interval and the interval's width. Time, memory and effective sample size come from one fit to the bench dataset, as a user would run it: the closed forms take a fraction of a millisecond, the calibration rules add their own cost (17 sequential passes for SafeBayes, 1,000 weighted fits for the bootstrap), and the NUTS rows include compilation. The oracle row uses the power read off the 4,000-dataset curve, which no analyst would have.

rng = np.random.default_rng([RANDOM_SEED, 70])
S_DRAWS = 2000
xs, ys = SIM["B"]
tempered = {
    "Gaussian, standard (closed form)": 1.0,
    "power 0.5 (fixed)": 0.5,
    "power at the oracle value": ETA_ORACLE["B"][1],
    "power set by SafeBayes": ETA_RULE["B"]["SafeBayes"],
    "power set by information matching": ETA_RULE["B"]["information matching"],
    "power matched to the bootstrap spread of the slope": ETA_RULE["B"]["bootstrap spread of the slope"],
}
SLOPE_DRAWS = {name: coef_draws(power_posterior(xs, ys, eta), rng, S_DRAWS)[..., 1] for name, eta in tempered.items()}
SLOPE_DRAWS["loss-likelihood bootstrap (no power)"] = LLB["B"][..., 1]
for name, draws in MCMC["B"].items():
    SLOPE_DRAWS[name] = draws[..., 1]

for name in sb.table().index:
    sb.score(name, {"slope": SLOPE_DRAWS[name]}, ess=ESS.get(name))
board = sb.table()
board
seconds peak_gb added_gb ess ess_per_s rmse coverage width
method
Gaussian, standard (closed form) 0.000204 0.362 0.000131 NaN NaN 0.24 0.688 0.45
Gaussian, standard (NUTS) 2.18 0.49 0.128 1.39e+03 634 0.24 0.694 0.448
power 0.5 (fixed) 0.000103 0.521 0 NaN NaN 0.24 0.833 0.634
power at the oracle value 0.000112 0.521 0 NaN NaN 0.24 0.894 0.748
power set by SafeBayes 0.00206 0.541 0 NaN NaN 0.24 0.711 0.481
power set by information matching 0.00023 0.69 3.28e-05 NaN NaN 0.241 0.731 0.482
loss-likelihood bootstrap (no power) 0.00389 0.69 0 NaN NaN 0.237 0.834 0.647
power matched to the bootstrap spread of the slope 0.00387 0.69 0 NaN NaN 0.241 0.852 0.65
Student-t likelihood 1.21 0.661 0.0179 1.42e+03 1.17e+03 0.134 0.801 0.343
Student-t with a scale model 1.87 0.604 0.0125 1.78e+03 954 0.111 0.907 0.374
sb.plot(columns=("seconds", "ess_per_s", "rmse", "coverage", "width"),
        highlight=["Student-t likelihood", "Student-t with a scale model"]);
Figure

Read the table from the right. Width and coverage are tied together for every row that tempers the Gaussian likelihood: they all share one centre, so the only way to cover more is to be wider, and the oracle row shows the price of honesty by that route, an interval two thirds wider than the standard one (0.75 against 0.45). Error tells the other half. Every Gaussian row, tempered or not, has the same RMSE of 0.24, because the power does not move the estimate. The two Student-t rows have errors of 0.13 and 0.11: they are closer to the truth, not merely more modest about where it is. The model that names both problems is the only row that is at once near 90% coverage and narrow.

The NUTS row for the standard posterior matches the closed-form row in error, coverage and width, as it should, at several thousand times the cost; that is the price of not having a closed form, and at two or three seconds it is small in absolute terms. Time is otherwise a non-issue at this size: the most expensive rules, SafeBayes and the bootstrap, take a few milliseconds. ESS per second is reported for the NUTS rows only. The closed-form and bootstrap rows produce independent draws, and we do not dress those up as an ESS.

7 · Where SafeBayes earns its place

SafeBayes left world B alone, and it would be unfair to leave it there, because the problem it was designed for is real and none of the other methods addresses it. We rebuild, in small, the ridge regression experiment of Grünwald and van Ommen (2017).

There are 50 regressors, independent standard normals, and only four of them matter: $y = 0.1\,(x_1 + x_2 + x_3 + x_4) + \text{noise}$. The model is a Gaussian linear model on all 50 with the conjugate prior $\beta \mid \sigma^2 \sim \mathcal N(0, \sigma^2 I)$ and $\sigma^2 \sim \text{Inv-Gamma}(1, 1/40)$, as in the paper. In the correct version the noise is Gaussian with variance 1/40. In the wrong version a coin is tossed for every observation: heads, the point is replaced by an "easy" one with every regressor and the response equal to zero; tails, it is generated as before with noise variance 1/20. The easy points lie exactly on the true regression function, the best line is unchanged and so is the average noise variance, and yet half the data now have no noise at all, which a model with one $\sigma$ cannot represent. We use 100 observations, 30 repeated datasets, and score the posterior mean by its excess risk: how much worse its squared prediction error on new data is than that of the best coefficients.

P_RIDGE, N_RIDGE, REPS_RIDGE = 50, 100, 30
RIDGE_PRIOR = dict(v0=1.0, a0=1.0, b0=1 / 40)
BETA_RIDGE = np.zeros(P_RIDGE + 1)
BETA_RIDGE[1:5] = 0.1


def ridge_data(rng, n, easy):
    X = np.c_[np.ones(n), rng.standard_normal((n, P_RIDGE))]
    y = X @ BETA_RIDGE + np.sqrt(1 / 20 if easy else 1 / 40) * rng.standard_normal(n)
    if easy:
        at_zero = rng.random(n) < 0.5
        X[at_zero, 1:], y[at_zero] = 0.0, 0.0
    return X, y


def excess_risk(m, easy):
    """Expected squared error of predicting with coefficients m, minus that of the true coefficients."""
    d = m - BETA_RIDGE
    return d[..., 0] ** 2 + (0.5 if easy else 1.0) * (d[..., 1:] ** 2).sum(axis=-1)


rng = np.random.default_rng([RANDOM_SEED, 80])
RIDGE = {}
with np.errstate(all="ignore"):
    for easy in (True, False):
        risk, expects, inflate, loss = (np.zeros((REPS_RIDGE, len(SB_GRID))) for _ in range(4))
        for r in range(REPS_RIDGE):
            X, y = ridge_data(rng, N_RIDGE, easy)
            for j, eta in enumerate(SB_GRID):
                m, V, a, b = nig(X.T @ X, X.T @ y, y @ y, N_RIDGE, eta, **RIDGE_PRIOR)
                risk[r, j] = excess_risk(m, easy)
                # squared error the posterior predictive expects for a new point: E[sigma2] (1 + x' V x), averaged over x
                inflate[r, j] = 1 + V[0, 0] + (0.5 if easy else 1.0) * np.trace(V[1:, 1:])
                expects[r, j] = b / (a - 1) * inflate[r, j]
                loss[r, j] = prequential(X, y, eta, **RIDGE_PRIOR)[0].sum()
        RIDGE[easy] = dict(risk=risk, expects=expects, inflate=inflate, pick=loss.argmin(axis=1))

rows = {}
for easy, label in ((True, "wrong model (easy points)"), (False, "correct model")):
    d = RIDGE[easy]
    picked = d["risk"][np.arange(REPS_RIDGE), d["pick"]]
    rows[label] = {
        "excess risk, standard": d["risk"][:, 0].mean(), "excess risk, power 0.5": d["risk"][:, 2].mean(),
        "excess risk, SafeBayes": picked.mean(), "median eta of SafeBayes": np.median(SB_GRID[d["pick"]]),
        "best fixed eta": SB_GRID[d["risk"].mean(axis=0).argmin()], "excess risk at the best fixed eta": d["risk"].mean(axis=0).min(),
        "posterior mean of sigma2, standard": (d["expects"][:, 0] / d["inflate"][:, 0]).mean(),
        "real squared error / what the standard posterior expects": (1 / 40 + d["risk"][:, 0].mean()) / d["expects"][:, 0].mean(),
        "the same for SafeBayes": (1 / 40 + picked.mean()) / d["expects"][np.arange(REPS_RIDGE), d["pick"]].mean(),
    }
print("noise floor (squared error of the true coefficients): 0.025")
pd.DataFrame(rows).T.round(3)
noise floor (squared error of the true coefficients): 0.025
excess risk, standard excess risk, power 0.5 excess risk, SafeBayes median eta of SafeBayes best fixed eta excess risk at the best fixed eta posterior mean of sigma2, standard real squared error / what the standard posterior expects the same for SafeBayes
wrong model (easy points) 0.069 0.049 0.024 0.125 0.016 0.013 0.004 5.32 0.367
correct model 0.024 0.023 0.021 0.302 0.031 0.013 0.014 1.79 0.666
fig, axes = plt.subplots(1, 2, figsize=(12.5, 4.1))
for easy, color, label in ((True, RED, "wrong model: half the points are easy"), (False, BLUE, "correct model")):
    d = RIDGE[easy]
    axes[0].plot(SB_GRID, d["risk"].mean(axis=0), color=color, lw=2, label=label)
    axes[0].plot([1.0], [d["risk"][:, 0].mean()], "o", color=color, ms=7)
    counts = np.bincount(d["pick"], minlength=len(SB_GRID))
    axes[1].bar(np.arange(len(SB_GRID)) + (0.2 if easy else -0.2), counts, width=0.4, color=color, label=label)
axes[0].axhline(1 / 40, color=INK, lw=1, ls="--")
axes[0].text(SB_GRID[-1], 1 / 40, " noise floor", va="bottom", fontsize=8.5)
axes[0].set_xscale("log")
axes[0].set_xlabel("power $\\eta$")
axes[0].set_ylabel("excess risk of the posterior mean")
axes[0].set_title("Risk against the power", loc="left")
axes[0].legend(frameon=False, fontsize=9)
axes[0].set_ylim(0, None)
tidy(axes[0])
axes[1].set_xticks(np.arange(0, len(SB_GRID), 2), [f"{e:.3g}" for e in SB_GRID[::2]])
axes[1].set_xlabel("power $\\eta$ chosen by SafeBayes")
axes[1].set_ylabel(f"datasets out of {REPS_RIDGE}")
axes[1].set_title("What SafeBayes chooses", loc="left")
axes[1].legend(frameon=False, fontsize=9)
tidy(axes[1]);
Figure

Here the standard posterior is in real trouble, and not about interval widths. With easy points its excess risk is nearly three times the noise floor: predictions from the posterior mean are worse than predictions from the true coefficients by far more than the noise itself. And it does not know: the squared error it makes on new data is more than five times what its own predictive distribution announces. Its posterior mean for $\sigma^2$ is 0.004, when the noise variance averaged over the data is 0.025. The easy points persuade the model that there is little noise, and what noise there is in the other half of the data gets fitted by the fifty coefficients.

Lowering the power helps a great deal: the red curve falls by a factor of five as $\eta$ goes down. In this model a smaller $\eta$ acts on the posterior mean exactly like a stronger ridge penalty, a correspondence the paper points out. SafeBayes finds the direction from the data: it picks a power around 0.1 in the wrong-model datasets and brings the excess risk down by about two thirds, to what the standard posterior achieves when the model is correct. Its view of its own error swings the other way, to expecting nearly three times the error it makes, which is the safer side to be wrong on. With the correct model it also picks powers below 1 (around 0.3) and loses nothing by it: the blue curve shows that with fifty regressors and a hundred points a stronger penalty than this prior's predicts better anyway.

So the two halves of the notebook use the same dial for different faults. In world B the posterior sat in the right place and misjudged its own width, and only a rule built on the real spread of the estimate could help. Here the posterior is in the wrong place, in the sense that matters for prediction, and a rule built on prediction finds the repair.

The choice. SafeBayes when the worry is that a flexible model is being misled and predicts badly; not when the worry is the width of an interval for a well-estimated parameter. Rejected: reading its $\hat\eta = 1$ in world B as a certificate that the intervals are fine. What would change our mind: nothing in these results; the two uses are different by design.

8 · Real outliers: the stars of CYG OB1

The simulated worlds were chosen so that the centre stayed right. Real outliers are often not so considerate. The star cluster CYG OB1 is a standard example from Rousseeuw and Leroy (1987): for 47 stars, the logarithm of the surface temperature and the logarithm of the light intensity. Most stars lie on the main sequence, where hotter stars are brighter. Four are giants: cool and very bright. The documentation of the data names them (stars 11, 20, 30 and 34), which gives us a known answer of the kind real data allow: the line fitted to the other 43.

data.describe("e131_stars_cyg")
stars = data.load("e131_stars_cyg")
x_s = stars["log_te"].to_numpy() - 4.4          # centred near the middle of the main sequence
y_s = stars["log_light"].to_numpy()
giant = stars["giant"].to_numpy() == 1
STAR_PRIOR = dict(v0=100.0, a0=1.0, b0=0.1)     # weak, in the units of these data
print(f"\n{len(stars)} stars, {giant.sum()} documented giants: stars {stars.loc[giant, 'star'].tolist()}")

STAR = {}


def star_row(label, centre, lo, hi, note=""):
    STAR[label] = dict(slope=centre, lo=lo, hi=hi, note=note)
    print(f"{label:46s} slope {centre:6.2f}   90% interval [{lo:6.2f}, {hi:5.2f}]   {note}")


m, half = coef_interval(power_posterior(x_s[~giant], y_s[~giant], prior=STAR_PRIOR))
star_row("reference: Gaussian, 43 main-sequence stars", m[1], m[1] - half[1], m[1] + half[1])
m, half = coef_interval(power_posterior(x_s, y_s, prior=STAR_PRIOR))
star_row("Gaussian, all 47 stars", m[1], m[1] - half[1], m[1] + half[1])
resid = y_s - m[0] - m[1] * x_s
print(f"{'':46s} residuals of the four giants from this line, in residual sd: "
      f"{np.round(resid[giant] / resid.std(ddof=2), 1).tolist()}")

rng = np.random.default_rng([RANDOM_SEED, 90])
star_boot = llb_draws(x_s, y_s, rng, 4000)
m1, V1, a1, b1 = power_posterior(x_s, y_s, prior=STAR_PRIOR)
star_eta = {
    "power 0.5 (fixed)": 0.5,
    "power set by SafeBayes": float(safebayes(x_s, y_s, prior=STAR_PRIOR)),
    "power set by information matching": float(eta_information(x_s, y_s)[0]),
    "power matched to the bootstrap spread of the slope": float(b1 / (a1 - 1) * V1[1, 1] / star_boot[:, 1].var(ddof=1)),
}
for label, eta in star_eta.items():
    m, half = coef_interval(power_posterior(x_s, y_s, eta, prior=STAR_PRIOR))
    star_row(label, m[1], m[1] - half[1], m[1] + half[1], f"eta = {eta:.2f}")
q = np.quantile(star_boot[:, 1], [0.05, 0.5, 0.95])
star_row("loss-likelihood bootstrap (no power)", q[1], q[0], q[2])
e131_stars_cyg: One row per star (47): star (number in the table), log_te (logarithm of the effective surface temperature), log_light (logarithm of the light intensity relative to the sun's), giant (1 for the four stars the package documentation calls giants, points 11, 20, 30 and 34; the other 43 'are said to lie on the main sequence').
  source: Hertzsprung-Russell diagram of the star cluster CYG OB1: the data frame `starsCYG` of the R package robustbase (Maechler et al.), from Rousseeuw & Leroy (1987), Robust Regression and Outlier Detection, Wiley, p. 27, table 3, as exported by Rdatasets (https://vincentarelbundock.github.io/Rdatasets/doc/robustbase/starsCYG.html). Licence, as read on https://cran.r-project.org/web/packages/robustbase/index.html on 2026-11-24 (robustbase 0.99-7): 'License: GPL-2 | GPL-3 [expanded from: GPL (>= 2)]'. DERIVED by tools/build_e131_stars_cyg.py (columns renamed, `giant` added; the url is the unrenamed table) - keep the cached file in data/ (md5 a7409e14efcf3810e1388c734caacb12).
  url:    https://vincentarelbundock.github.io/Rdatasets/csv/robustbase/starsCYG.csv

47 stars, 4 documented giants: stars [11, 20, 30, 34]
reference: Gaussian, 43 main-sequence stars    slope   2.02   90% interval [  1.33,  2.72]   
Gaussian, all 47 stars                         slope  -0.41   90% interval [ -0.88,  0.05]   
                                               residuals of the four giants from this line, in residual sd: [0.7, 1.0, 1.2, 1.7]
power 0.5 (fixed)                              slope  -0.41   90% interval [ -1.08,  0.25]   eta = 0.50
power set by SafeBayes                         slope  -0.41   90% interval [ -0.88,  0.05]   eta = 1.00
power set by information matching              slope  -0.41   90% interval [ -0.87,  0.05]   eta = 1.03
power matched to the bootstrap spread of the slope slope  -0.41   90% interval [ -1.02,  0.20]   eta = 0.60
loss-likelihood bootstrap (no power)           slope  -0.38   90% interval [ -0.81,  0.34]   

The reference slope is about 2: on the main sequence, light grows with temperature. The Gaussian fit to all 47 stars has a slope of about $-0.4$, with a 90% interval from $-0.9$ to 0.05. Four stars in the far corner of the plot are enough to turn the line over.

The tempered posteriors do what the algebra said they would. Each keeps the centre at $-0.4$ and changes only the width. SafeBayes and information matching see nothing to correct ($\hat\eta$ of 1.00 and 1.03). The bootstrap asks for wider intervals ($\hat\eta = 0.60$), and the widest interval of the group still ends at 0.34, a long way below the reference interval, which starts at 1.33. A power on the likelihood changes how much we trust it, not what it says, and here what it says is wrong. That is the third correction: tempering is a repair for width, and outliers that sit to one side are a problem of centre.

Now the model-fixing route, twice. First the Student-t likelihood, the standard advice for outliers. Then a model that names what the documentation tells us is going on: a second population. Each star belongs to the main sequence with probability $1 - w$, where its light follows the line, or with probability $w$ to another group whose light has its own mean and spread and does not depend on the line at all. The group label is summed out of the likelihood, so the model does not use the documented labels; it has to find the giants by itself.

with pm.Model() as star_t:
    a = pm.Normal("a", 5.0, 5.0)
    b = pm.Normal("b", 0.0, 10.0)
    s = pm.HalfNormal("s", 2.0)
    nu = pm.Gamma("nu", alpha=2.0, beta=0.1)
    pm.StudentT("obs", nu=nu, mu=a + b * x_s, sigma=s, observed=y_s)
    idata_star_t = pm.sample(random_seed=RANDOM_SEED, progressbar=False)

with pm.Model(coords={"star": stars["star"].to_numpy()}) as star_mix:
    a = pm.Normal("a", 5.0, 5.0)
    b = pm.Normal("b", 0.0, 10.0)
    s = pm.HalfNormal("s", 1.0)
    w = pm.Beta("w", 1.0, 9.0)                         # a few stars, not half of them
    mu_other = pm.Normal("mu_other", 5.0, 5.0)
    s_other = pm.Gamma("s_other", alpha=2.0, beta=2.0)   # kept away from zero: no spike on a single star
    on_line = pt.log1p(-w) + pm.logp(pm.Normal.dist(a + b * x_s, s), y_s)
    off_line = pt.log(w) + pm.logp(pm.Normal.dist(mu_other, s_other), y_s)
    pm.Potential("mixture_loglik", pm.math.logaddexp(on_line, off_line).sum())
    pm.Deterministic("p_other", pm.math.sigmoid(off_line - on_line), dims="star")
    idata_star_mix = pm.sample(tune=1000, target_accept=0.95, random_seed=RANDOM_SEED, progressbar=False)

for label, idata, names in (("Student-t likelihood", idata_star_t, ["a", "b", "s", "nu"]),
                            ("two populations (mixture)", idata_star_mix, ["a", "b", "s", "w", "mu_other", "s_other"])):
    rhat, ess, div = diagnose(idata, names)
    slope = idata.posterior["b"]
    q = np.quantile(slope.values, [0.05, 0.5, 0.95])
    star_row(label, q[1], q[0], q[2], f"r_hat {rhat:.3f}, ESS {ess:.0f}, {div} divergences")
    print(f"{'':46s} slope by chain: {np.round(slope.mean('draw').values, 2).tolist()}")
print(f"Student-t: posterior median of nu {float(idata_star_t.posterior['nu'].median()):.0f}")
p_other = idata_star_mix.posterior["p_other"].mean(("chain", "draw")).values
flagged = stars.loc[p_other > 0.5, "star"].tolist()
print(f"mixture: stars more likely off the line than on it: {flagged}; "
      f"probabilities for the four giants {np.round(p_other[giant], 2).tolist()}; "
      f"largest probability among the stars not flagged {p_other[p_other <= 0.5].max():.2f}")
Student-t likelihood                           slope  -0.41   90% interval [ -0.93,  0.10]   r_hat 1.001, ESS 4405, 0 divergences
                                               slope by chain: [-0.41, -0.41, -0.4, -0.41]
two populations (mixture)                      slope   2.84   90% interval [  1.40,  3.84]   r_hat 1.012, ESS 375, 0 divergences
                                               slope by chain: [2.78, 2.76, 2.42, 2.88]
Student-t: posterior median of nu 23
mixture: stars more likely off the line than on it: [7, 9, 11, 20, 30, 34]; probabilities for the four giants [0.97, 0.97, 0.97, 0.97]; largest probability among the stars not flagged 0.40
fig, axes = plt.subplots(1, 2, figsize=(13, 4.6), gridspec_kw={"width_ratios": [1, 1.15]})
ax = axes[0]
gx = np.linspace(x_s.min() - 0.05, x_s.max() + 0.05, 50)
ax.scatter(x_s[~giant] + 4.4, y_s[~giant], s=24, color=BLUE, label="main sequence (43)")
ax.scatter(x_s[giant] + 4.4, y_s[giant], s=46, color=RED, marker="*", label="giants (documented)")
extra = [s_ for s_ in flagged if s_ not in stars.loc[giant, "star"].tolist()]
for s_ in extra:
    i = int(np.where(stars["star"] == s_)[0][0])
    ax.annotate(f"star {s_}", (x_s[i] + 4.4, y_s[i]), xytext=(6, 4), textcoords="offset points", fontsize=8.5, color=MUTED)
lines = {"Gaussian, all 47 stars": (ORANGE, "-"), "Student-t likelihood": (VIOLET, ":"),
         "two populations (mixture)": (GREEN, "-"), "reference: Gaussian, 43 main-sequence stars": (INK, "--")}
fits = {"Gaussian, all 47 stars": power_posterior(x_s, y_s, prior=STAR_PRIOR)[0],
        "reference: Gaussian, 43 main-sequence stars": power_posterior(x_s[~giant], y_s[~giant], prior=STAR_PRIOR)[0],
        "Student-t likelihood": [float(idata_star_t.posterior[k].mean()) for k in "ab"],
        "two populations (mixture)": [float(idata_star_mix.posterior[k].median()) for k in "ab"]}
for label, (color, ls) in lines.items():
    ax.plot(gx + 4.4, fits[label][0] + fits[label][1] * gx, color=color, ls=ls, lw=1.8, label=label.split(":")[0])
ax.set_xlabel("log surface temperature")
ax.set_ylabel("log light intensity")
ax.set_ylim(3.6, 6.6)
ax.set_title("CYG OB1: four giants turn the line over", loc="left")
ax.legend(frameon=False, fontsize=8.5, loc="lower left")
tidy(ax)

ax = axes[1]
order = list(STAR)
ref = STAR[order[0]]
ax.axvspan(ref["lo"], ref["hi"], color=LIGHT, alpha=0.5, lw=0)
ax.axvline(ref["slope"], color=INK, lw=1, ls="--")
ax.axvline(0, color=MUTED, lw=0.8)
for i, label in enumerate(order):
    r = STAR[label]
    color = INK if i == 0 else (GREEN if "mixture" in label else VIOLET if "Student" in label else ORANGE)
    ax.plot([r["lo"], r["hi"]], [i, i], color=color, lw=2.2)
    ax.plot([r["slope"]], [i], "o", color=color, ms=6)
ax.set_yticks(range(len(order)), [l.replace("reference: ", "reference: ").replace("power matched to the bootstrap spread of the slope",
                                                                              "power matched to the bootstrap spread") for l in order], fontsize=8.5)
ax.set_ylim(len(order) - 0.5, -0.5)
ax.set_xlabel("slope of log light on log temperature, with 90% interval")
ax.set_title("Only one model moves the centre", loc="left")
tidy(ax, grid="x");
Figure

The Student-t likelihood, the usual prescription, changes nothing: its slope is the Gaussian slope, and it estimates so many degrees of freedom (a posterior median of 23) that it is a Gaussian model in all but name. The reason is in the left panel. The giants are far away in temperature, so they have enormous leverage: the fitted line is pulled toward them until their residuals are unremarkable, all within two residual standard deviations. A heavy-tailed likelihood protects against large residuals. It has no way to see points that drag the line to themselves. This is the model-fixing route failing because the wrong problem was named.

The two-population model names the right one. Without being told, it puts the four giants off the line with probability 0.97, together with stars 7 and 9, which sit above the band. Its slope is positive, 2.8 with a 90% interval from 1.4 to 3.8, which contains the reference of 2.0. It is steeper than the reference, and the two extra stars it sets aside are the obvious suspects; whether they belong on the main sequence is a question for an astronomer. The sampler has more work here than anywhere else in the notebook: the four chains' mean slopes run from 2.4 to 2.9 and the smallest effective sample size is under 400, with r_hat at 1.01. The slopes by chain are worth printing for any mixture.

The choice. For the stars, the two-population model. Rejected: every tempered posterior (right width for the wrong line), and the Student-t likelihood (blind to outliers with leverage). What would change our mind: outliers in the response only, at ordinary temperatures; then the Student-t would see them and the mixture would be more machinery than needed.

9 · Which method for which failure

The figure collects what was measured, one row per situation and one column per method. For the two simulated worlds a cell shows the coverage of the slope's 90% interval and, in brackets, its width relative to the standard posterior. For the ridge regression it shows the excess risk in units of the noise floor, and for the stars the estimated slope, to be read against a reference of about 2.

def world_cell(w, cov, width):
    hit, base_width = covers(power_posterior(*SIM[w]))
    base = hit[:, 1].mean()                                   # the standard posterior's coverage in this world
    if abs(cov - CI) <= 0.03:
        verdict = "good"
    elif cov > CI:
        verdict = "wide"
    else:                                                     # short of 90%: did it close a third of the gap?
        verdict = "partial" if cov - base >= (CI - base) / 3 else "bad"
    return f"{cov:.0%}\n(width x{width / base_width[:, 1].mean():.2f})", verdict


def mcmc_cell(w, label):
    lo, hi = np.quantile(MCMC[w][label][..., 1], [0.05, 0.95], axis=0)
    return world_cell(w, np.mean((lo <= B_TRUE) & (B_TRUE <= hi)), (hi - lo).mean())


COLUMNS = ["standard\nposterior", "power 0.5\n(fixed)", "power by\nSafeBayes", "power by\ninformation\nmatching",
           "power by\nbootstrap spread\nof the slope", "Student-t\nlikelihood", "the problem,\nnamed"]
cells = {}
for w, row in (("A", "heavy tails,\nconstant scale\n(world A)"), ("B", "noise scale\ngrows with x\n(world B)")):
    std = covers(power_posterior(*SIM[w]))
    half_ = covers(power_posterior(*SIM[w], 0.5))
    named = "Student-t likelihood" if w == "A" else "Student-t with a scale model"
    cells[row] = [world_cell(w, std[0][:, 1].mean(), std[1][:, 1].mean()), world_cell(w, half_[0][:, 1].mean(), half_[1][:, 1].mean()),
                  *[world_cell(w, rule_cov[w][r][0][:, 1].mean(), rule_cov[w][r][1][:, 1].mean()) for r in RULES],
                  mcmc_cell(w, "Student-t likelihood"), mcmc_cell(w, named)]

d = RIDGE[True]
floor = 1 / 40


def ridge_cell(value):
    return f"{value / floor:.1f} x floor", ("good" if value < 1.5 * floor else "bad")


cells["fifty regressors,\neasy points\n(ridge)"] = [
    ridge_cell(d["risk"][:, 0].mean()), ridge_cell(d["risk"][:, 2].mean()),
    ridge_cell(d["risk"][np.arange(REPS_RIDGE), d["pick"]].mean()), ("not run", "none"), ("not run", "none"), ("not run", "none"),
    ("not run", "none")]


def star_cell(label):
    r = STAR[label]
    return f"slope {r['slope']:.1f}", ("good" if r["lo"] <= ref["slope"] <= r["hi"] else "bad")


cells["a second population\nwith leverage\n(stars)"] = [star_cell(k) for k in (
    "Gaussian, all 47 stars", "power 0.5 (fixed)", "power set by SafeBayes", "power set by information matching",
    "power matched to the bootstrap spread of the slope", "Student-t likelihood", "two populations (mixture)")]

SHADE = {"good": "#cdeedd", "wide": "#d5e5f8", "partial": "#fbe7b3", "bad": "#f8cfcc", "none": "#f1f0ec"}
fig, ax = plt.subplots(figsize=(13.2, 5.6))
for i, (row, values) in enumerate(cells.items()):
    ax.text(-0.6, i, row, ha="right", va="center", fontsize=9.5, color=INK, linespacing=1.3)
    for j, (text, verdict) in enumerate(values):
        ax.add_patch(plt.Rectangle((j - 0.47, i - 0.44), 0.94, 0.88, fc=SHADE[verdict], ec="white", lw=1.5))
        ax.text(j, i, text, ha="center", va="center", fontsize=9, color=INK if verdict != "none" else MUTED, linespacing=1.35)
for j, col in enumerate(COLUMNS):
    ax.text(j, -0.62, col, ha="center", va="bottom", fontsize=9.5, fontweight="bold", color=INK, linespacing=1.2)
for k, (verdict, text) in enumerate((("good", "does the job"), ("wide", "honest, wider than needed"),
                                      ("partial", "helps, still overconfident"), ("bad", "overconfident, or wrong"),
                                      ("none", "not run here"))):
    ax.add_patch(plt.Rectangle((-1.9 + 1.75 * k, len(cells) - 0.32), 0.22, 0.22, fc=SHADE[verdict], ec="white"))
    ax.text(-1.9 + 1.75 * k + 0.3, len(cells) - 0.21, text, va="center", fontsize=9, color=INK)
ax.set_xlim(-2.4, len(COLUMNS) - 0.5)
ax.set_ylim(len(cells) + 0.05, -1.45)
ax.axis("off")
ax.set_title("When to reach for which: every situation in this notebook against every method", loc="left");
Figure

Green means the method did its job there: coverage within three points of 90% (the counting error of 1,000 datasets is about one point), an excess risk below one and a half noise floors, or a slope interval that contains the reference. Blue is honest but wider than needed. Amber helps and stays overconfident: it closes at least a third of the gap between the standard posterior and 90%. Red is overconfident or wrong.

Read down the columns. The standard posterior is fine under heavy tails alone and fails in the other three rows. A fixed power of 0.5 is right in none of the four. SafeBayes is the one method that repairs the ridge regression, and it leaves both calibration worlds as it found them, which is right in A and no help in B. Matching the bootstrap spread of the slope is the tempering rule that comes closest in world B. No tempering rule does anything for the stars. The last column, a model that names the actual problem, is green in every row where we ran it, and the Student-t column next to it shows what happens when the name is half right (world B) or wrong (the stars).

In practice the order of work is the reverse of the notebook's. Start with predictive checks that could reveal a pattern (a fan, a tail, a cluster). If a pattern has a name, model it. If the checks fail without a pattern, or the right model is out of reach, compare the posterior spread of the parameter you report with a bootstrap spread, temper to match if they disagree, and say that you did. Use SafeBayes when the fear is a flexible model predicting badly, not when it is an interval that is too narrow.

Summary

  • Heavy tails alone did not break the interval for the slope. With Student-t noise of 3 degrees of freedom and constant scale, the Gaussian model's 90% intervals for both coefficients covered 90% of the time. What broke was the interval for $\sigma$ (right in a third of the datasets) and the shape of predictions. The expected lesson needed this change. Limit: we only looked at noise that has a variance (more than 2 degrees of freedom).
  • A noise scale that depends on $x$ did. In world B the slope's 90% interval covered 68%, and the sandwich said why: the slope's real variance is three times the model's, the intercept's 1.36 times.
  • The power $\eta$ widens intervals by $1/\sqrt\eta$ and leaves the centre alone. Coverage against $\eta$ shows the power each parameter needed: 0.36 for the slope and 0.81 for the intercept in world B, 1 for both in world A. One dial cannot serve two parameters, and it cannot move an estimate: every tempered row of the scoreboard has the same error.
  • The three rules for $\eta$ answer three questions. SafeBayes kept $\eta = 1$ in over 80% of the datasets of world B (coverage 71%) and was the method that repaired the fifty-regressor ridge example, cutting its excess risk by about two thirds. Information matching settled near 0.8 (coverage 73%), and its trace rule gives 0.70, 0.82 or 1.50 for the same data depending on the units of $x$. Matching the bootstrap spread of the slope reached 85% at $n = 200$ and about 90% from $n = 1000$ on. Limit: the last is our own targeted variant, and the bootstrap it leans on was itself too narrow at 200 points (83%).
  • Fixing the model beat tempering when the problem had a name. A Student-t likelihood with a model for the scale covered 91% with intervals half as wide as the Gaussian posterior tempered to the same coverage, and with less than half the error (0.11 against 0.24). A Student-t alone was a partial repair (80%). Limit: the scale model had the simulator's own form.
  • Naming the wrong problem fixed nothing. For the 47 stars of CYG OB1 the Gaussian slope is $-0.4$ against a reference of 2; tempering only widened the interval around $-0.4$, and the Student-t likelihood agreed with the Gaussian, because the four giants are leverage points with unremarkable residuals. A two-population mixture found the giants without the labels and recovered a positive slope whose interval contains the reference.

Try it yourself

  1. Calibrate on coverage. Implement the rule of Syring and Martin (2019) with the closed forms above: for a grid of $\eta$, resample the bench dataset with replacement 500 times, compute the $\eta$-posterior interval of the slope in each resample, and choose the $\eta$ at which 90% of those intervals contain the full-data least-squares slope. Run it on the 1,000 datasets of world B. Does it close the gap between 85% and 90% at $n = 200$?
  2. Move the centre. Add a world C: world A's noise, but 10% of the readings, all at concentrations above 4, are shifted up by 10. Redo the coverage curve of part 3 for the slope. Is there any $\eta$ at which the interval is honest without being useless, and what do residual_summaries say about this dataset?
  3. Standardise before matching. Recompute eta_information in world B after centring $x$ and scaling it to unit variance, and again for the slope alone. How much of the gap between 0.82 and the slope's 0.33 was the choice of units, and how much is the trace itself?
print(f"total run time: {time.time() - T_START:.0f} s")
total run time: 275 s