Inference and computation / E132

Bag your posterior: BayesBag, the unit you resample, and what bagging cannot repair

Type
Advanced worked example - read, run, modify
Data
Simulated: a discount test in 40 stores with a known answer, in three worlds (the model is right; baskets from one store resemble each other; the response to the discount is curved), plus the same test with a yes/no outcome. Real: the Capital Bikeshare daily counts of 2011-2012 (Fanaee-T and Gama 2013, UCI Machine Learning Repository), for a choice between two models
You will learn
What BayesBag is: the average of the posteriors of bootstrap copies of the data · why it is about twice as wide as it needs to be when the model is right · why the unit you resample decides whether it works · the mismatch index, a detector built from the two spreads, and the two cases it cannot see · tuning the bootstrap size · doing the $B$ fits when there is no closed form: nutpie refits against Laplace · bagged model probabilities for two models that fit about equally well · and when to fix the model instead

The question

A retailer wants to know what a discount does to the average basket. It picks 40 stores, gives each one a discount depth of 0, 5, 10, 15 or 20 percent (eight stores per depth), and records every transaction. The pricing lead asks one thing: what would a 30% discount add to the average basket, in dollars? The analyst pools the transactions, fits a straight line of basket value on discount depth with Gaussian noise, and reports the line's value at 30% minus its value at 0%, with a 90% interval.

That model can be wrong in several ways, and this notebook is about two of them. Baskets from the same store resemble each other, because stores differ in their customers and their neighbourhood, so the transactions are not independent. And the response to a discount may flatten, so that a line fitted up to 20% says too much about 30%. With a wrong model the posterior still settles down as data come in, and it settles on the parameter values that make the model least wrong. Its width keeps coming from the model's own likelihood, which describes how much the estimate would vary if the model were true. So the posterior of a wrong model can be very sure of an answer that the next dataset would contradict. Notebook E131 looked at one repair for that, raising the likelihood to a power; this one looks at another.

BayesBag takes the bootstrap's view of the data and keeps the Bayesian model. Draw $B$ bootstrap copies of the dataset, compute the posterior of each copy, and average the $B$ posteriors:

$$\pi^*(\theta \mid y) \;=\; \frac{1}{B}\sum_{b=1}^{B} \pi\big(\theta \mid y^{*(b)}\big).$$

The idea came up in phylogenetics (Waddell, Kishino and Ota 2002; Douady et al. 2003), Bühlmann (2014) proposed it again in a short discussion paper and gave it its name, after Breiman's (1996) bagging, and Huggins and Miller (2019, 2020) worked out its large-sample theory, a diagnostic built on it, and its use for choosing between models. The bootstrap copies differ from each other the way real datasets would, whatever the model says, so the bagged posterior carries the real sampling variability on top of the model's own.

The lesson we expected to find was the one in the method's sales pitch: when the model is wrong the standard posterior shrinks onto the wrong value and looks sure of itself, and the bagged posterior covers. The simulations keep part of that and correct the rest, and the corrections are the useful part:

  • Bagging changes the width of a posterior and leaves its centre where it was. It repairs a model whose estimate is right on average and too sure of itself. It does nothing for a model that aims at the wrong value.
  • It only sees the variability of the unit you resample. Resampling transactions when stores are what varies repairs nothing.
  • When the model is right, bagging costs width: the 90% interval becomes about a 98% interval.

Everything is measured against a known answer. In the simulations the true effect of a 30% discount is known, so we count how often each method's 90% interval contains it. For the two bike models, which have no known answer, we check whether two halves of the data tell the same story.

part question tool
1 What does the pooled model say about one test? the conjugate posterior in closed form, checked with NUTS
2 What is a bagged posterior? 100 bootstrap copies, by transaction and by store; the two spreads
3 How often is each interval right as the test runs longer? 1,000 repeated tests per size, three worlds
4 Can the two spreads detect a wrong model? the mismatch index; the tuned bootstrap size
5 What if the posterior has no closed form? 100 nutpie refits against 100 Laplace fits
6 What if we fix the model instead? store effects, overdispersion, a residual plot
7 Who wins, at what cost? the scoreboard
8 Which of two models? bagged model probabilities: two thermometers, then the bikes
9 Which method for which failure? a table of everything measured

A word on what is computed how. The straight-line model with a conjugate prior has a closed-form posterior, so every one of the nearly five million posteriors behind the coverage curves is exact and costs microseconds. The yes/no outcome of part 5 has no closed form: there the 100 fits are done twice, with NUTS (one compiled nutpie model, refilled with new data) and with a Laplace approximation, and the two are compared. The models of part 6 are fitted with NUTS. The model probabilities of part 8 are closed-form marginal likelihoods.

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 pymc_extras as pmx
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 = 132
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 · One test, three worlds, one model

A basket is worth \$40 on average with no discount, and baskets scatter around their mean with a standard deviation of \$15. The three worlds differ in what the analyst's model leaves out.

  • World A, the model is right. The mean basket rises by \$0.50 for every point of discount, and transactions are independent. A 30% discount adds \$15.
  • World B, stores differ. The same line, but every store has its own level, a few dollars above or below the line (standard deviation \$3). Two baskets from one store share that level. This is a small effect per basket, a correlation of 0.04 between baskets of the same store, and the truth is still \$15.
  • World C, the response flattens. Transactions are independent again, but the mean basket follows a curve that saturates, $40 + 16\,(1 - e^{-d/12})$ at depth $d$. Over the tested range of 0 to 20% it looks nearly straight. At 30% it gives \$14.69.

The size of the dataset is the number of transactions per store, which grows as the test runs longer. The number of stores stays at 40. Our bench is a test with 80 transactions per store, 3,200 in all.

J = 40                                             # stores
DEPTH = np.repeat([0.0, 5.0, 10.0, 15.0, 20.0], J // 5)   # discount depth of each store, in percent
X = DEPTH / 10.0                                   # the regressor: depth in units of 10 points
SIGMA, SIGMA_U, BASE, SLOPE = 15.0, 3.0, 40.0, 5.0   # basket sd, store sd, level, dollars per 10 points
CAP, RATE = 16.0, 12.0                             # world C: 40 + 16 (1 - exp(-depth / 12))
TARGET = 30.0                                      # the discount the pricing lead asks about
WORLDS = {"A": "the model is right", "B": "stores differ", "C": "the response flattens"}
CI, M_BENCH, M_GRID = 0.90, 80, (5, 20, 80, 320, 1280)


def mean_basket(depth, world):
    depth = np.asarray(depth, dtype=float)
    return BASE + CAP * (1 - np.exp(-depth / RATE)) if world == "C" else BASE + SLOPE * depth / 10


TRUTH = {w: float(mean_basket(TARGET, w) - mean_basket(0.0, w)) for w in WORLDS}


def simulate(world, m, reps, rng):
    """Transactions of `reps` independent tests: an array (reps, J, m) of basket values."""
    u = rng.normal(0, SIGMA_U, (reps, J, 1)) if world == "B" else 0.0
    return mean_basket(DEPTH, world)[None, :, None] + u + rng.normal(0, SIGMA, (reps, J, m))


rng = np.random.default_rng(RANDOM_SEED)
LONG = {w: simulate(w, M_GRID[-1], 1, rng)[0] for w in WORLDS}     # one long test per world
BENCH = {w: LONG[w][:, :M_BENCH] for w in WORLDS}                 # its first 80 transactions per store
print("true effect of a 30% discount:", {w: round(v, 2) for w, v in TRUTH.items()})
print(f"world B: correlation between two baskets of one store = {SIGMA_U**2 / (SIGMA_U**2 + SIGMA**2):.3f}")

fig, axes = plt.subplots(1, 3, figsize=(13, 3.9), sharey=True)
grid_d = np.linspace(0, 32, 100)
for ax, w in zip(axes, WORLDS):
    means = BENCH[w].mean(axis=1)
    ax.scatter(DEPTH + rng.uniform(-0.8, 0.8, J), means, s=22, color=BLUE, alpha=0.75, label="mean basket of one store")
    ax.plot(grid_d, mean_basket(grid_d, w), color=INK, lw=1.4, label="the truth")
    fit = np.polyfit(np.repeat(DEPTH, M_BENCH), BENCH[w].ravel(), 1)
    ax.plot(grid_d, np.polyval(fit, grid_d), color=ORANGE, lw=1.4, ls="--", label="least-squares line")
    ax.axvspan(20.5, 32, color=LIGHT, alpha=0.35, lw=0)
    ax.axvline(TARGET, color=MUTED, lw=0.8, ls=":")
    ax.set_title(f"World {w}: {WORLDS[w]}", loc="left", fontsize=10)
    ax.set_xlabel("discount depth (%)")
    tidy(ax)
axes[0].set_ylabel("basket value (\\$)")
axes[0].legend(frameon=False, fontsize=8, loc="upper left")
axes[2].text(26.2, 41.5, "not tested", fontsize=8, color=MUTED, ha="center");
true effect of a 30% discount: {'A': 15.0, 'B': 15.0, 'C': 14.69}
world B: correlation between two baskets of one store = 0.038
Figure

Each dot is the mean basket of one store over 80 transactions. In world A the dots scatter around the line by what 80 baskets allow, about \$1.70. In world B they scatter more, because each store carries its own level. In world C the dots look the same as in A, and nothing in the tested range announces that the curve and the dashed line part ways in the shaded region, which is where the question is.

The pooled model, in closed form

The analyst's model is $y_i = \alpha + \beta x_i + \varepsilon_i$ with $\varepsilon_i \sim \mathcal N(0, \sigma^2)$, independent over transactions. With the conjugate prior $\beta \mid \sigma^2 \sim \mathcal N(0, \sigma^2 \Lambda_0^{-1})$, $\sigma^2 \sim \text{Inv-Gamma}(a_0, b_0)$ the posterior is known exactly. Writing $G = X^\top X$ and $g = X^\top y$,

$$A_n = \Lambda_0 + G, \qquad m_n = A_n^{-1} g, \qquad a_n = a_0 + \tfrac n2, \qquad b_n = b_0 + \tfrac12\big(y^\top y - g^\top m_n\big),$$

and any linear combination $c^\top\beta$ has a Student-t posterior with $2a_n$ degrees of freedom, centre $c^\top m_n$ and squared scale $(b_n / a_n)\, c^\top A_n^{-1} c$. The effect of a 30% discount is $3\beta$, since $x$ counts tens of points. We take a prior so weak that it plays no part ($\Lambda_0 = 10^{-6} I$, $a_0 = b_0 = 10^{-3}$).

Only sums enter, and that is what makes a bootstrap cheap: a bootstrap copy of the data is the original data with integer weights, so its posterior needs the same sums with weights. Since $x$ is the same for every transaction of a store, the sums can be taken store by store.

A0, B0, LAM = 1e-3, 1e-3, 1e-6
F_LINE = np.stack([np.ones(J), X], axis=1)                 # features of each store: 1, x
C_LINE = np.array([0.0, TARGET / 10])                      # the effect at 30%: 3 * slope
F_QUAD = np.stack([np.ones(J), X, X**2], axis=1)
C_QUAD = np.array([0.0, TARGET / 10, (TARGET / 10) ** 2])


def effect_posterior(count, total, sumsq, F=F_LINE, c=C_LINE):
    """Student-t posterior of the effect at 30% from store-level sums.

    count (..., J): transactions used from each store; total (..., J): the sum of their basket
    values; sumsq (...): the sum of squares over all of them. Returns degrees of freedom, centre
    and scale, each of shape (...).
    """
    p = F.shape[1]
    G = np.einsum("...j,jp,jq->...pq", count, F, F) + LAM * np.eye(p)
    g = np.einsum("...j,jp->...p", total, F)
    sol = np.linalg.solve(G, np.stack([g, np.broadcast_to(c, g.shape)], axis=-1))
    mean, Ainv_c = sol[..., 0], sol[..., 1]
    a_n = A0 + count.sum(-1) / 2
    b_n = B0 + 0.5 * (sumsq - (g * mean).sum(-1))
    return 2 * a_n, mean @ c, np.sqrt(b_n / a_n * (Ainv_c @ c))


def store_sums(y):
    """Per-store sum and sum of squares of an array (..., J, m)."""
    return y.sum(-1), (y**2).sum(-1)


def standard_posterior(y, **kw):
    s, q = store_sums(y)
    return effect_posterior(np.full(s.shape, float(y.shape[-1])), s, q.sum(-1), **kw)


def t_interval(dof, loc, scale, prob=CI):
    half = stats.t.ppf(0.5 + prob / 2, dof) * scale
    return loc - half, loc + half


sb = Scoreboard(truth={"effect": np.full(1000, TRUTH["B"])}, ci_prob=CI)
with sb.track("standard posterior (closed form)"):
    STD_BENCH = {w: standard_posterior(BENCH[w]) for w in WORLDS}
for w in WORLDS:
    dof, loc, scale = STD_BENCH[w]
    lo, hi = t_interval(dof, loc, scale)
    print(f"world {w}, bench test: a 30% discount adds {loc:5.2f} dollars, 90% interval [{lo:5.2f}, {hi:5.2f}]"
          f"   (truth {TRUTH[w]:.2f}; posterior sd {scale * np.sqrt(dof / (dof - 2)):.2f})")
world A, bench test: a 30% discount adds 13.04 dollars, 90% interval [11.19, 14.89]   (truth 15.00; posterior sd 1.13)
world B, bench test: a 30% discount adds 13.11 dollars, 90% interval [11.22, 15.01]   (truth 15.00; posterior sd 1.15)
world C, bench test: a 30% discount adds 18.91 dollars, 90% interval [17.01, 20.80]   (truth 14.69; posterior sd 1.15)

The three posteriors have nearly the same width, because the width depends on how many transactions there are and how much they scatter, and that is the same in the three worlds. On this one test the interval of world A just misses its truth (\$14.89 against \$15.00), which happens to a correct 90% interval one time in ten. The interval of world B just holds it, and the interval of world C is nowhere near. One dataset cannot tell a model that was unlucky from a model that is wrong, so part 3 will count.

The same thing with NUTS

We will need a sampler later, for models with no closed form, so we set up the machinery here where the answer is known. Two details make hundreds of refits cheap. First, the Gaussian likelihood of a store's transactions depends on the data only through the store's mean and its within-store sum of squares, so the model sees 40 rows whatever the number of transactions. Second, the data enter through pm.Data, so nutpie compiles the model once and compiled.with_data(...) swaps in another dataset without compiling again. The weights w are there for the bootstrap: a store drawn twice gets weight 2, a store left out gets weight 0.

def gaussian_model(m, store_effects):
    """The line on store-level sufficient statistics; `store_effects` adds a level per store, integrated out."""
    with pm.Model() as model:
        w = pm.Data("w", np.ones(J))
        ybar = pm.Data("ybar", np.zeros(J))
        ssw = pm.Data("ssw", np.full(J, (m - 1) * SIGMA**2))
        a = pm.Normal("a", 40.0, 50.0)
        b = pm.Normal("b", 0.0, 50.0)
        sigma = pm.HalfNormal("sigma", 50.0)
        sd_mean = sigma / np.sqrt(m)
        if store_effects:
            sigma_u = pm.HalfNormal("sigma_u", 10.0)
            sd_mean = pt.sqrt(sigma_u**2 + sigma**2 / m)
        logp = (pm.logp(pm.Normal.dist(a + b * X, sd_mean), ybar)
                + pm.logp(pm.Gamma.dist(alpha=(m - 1) / 2, beta=1 / (2 * sigma**2)), ssw))
        pm.Potential("loglik", (w * logp).sum())
        pm.Deterministic("effect", TARGET / 10 * b)
    return model


def sufficient(y):
    """Store means and within-store sums of squares of an array (..., J, m)."""
    ybar = y.mean(-1)
    return ybar, ((y - ybar[..., None]) ** 2).sum(-1)


def nuts(compiled, draws=1000, tune=400, chains=4, seed=RANDOM_SEED, **new_data):
    return nutpie.sample(compiled.with_data(**new_data), draws=draws, tune=tune, chains=chains, cores=chains,
                         seed=seed, progress_bar=False)


ybar_b, ssw_b = sufficient(BENCH["B"])
with sb.track("standard posterior (NUTS)"):
    pooled_nuts = nutpie.compile_pymc_model(gaussian_model(M_BENCH, store_effects=False))
    idata_pooled = nuts(pooled_nuts, ybar=ybar_b, ssw=ssw_b)
draws = idata_pooled.posterior["effect"].values.ravel()
ESS_POOLED = float(az.ess(idata_pooled.posterior["effect"].values))
dof, loc, scale = STD_BENCH["B"]
print(f"world B, bench test, closed form: {loc:.3f}, 90% interval [{t_interval(dof, loc, scale)[0]:.3f}, {t_interval(dof, loc, scale)[1]:.3f}]")
print(f"world B, bench test, NUTS:        {draws.mean():.3f}, 90% interval [{np.quantile(draws, 0.05):.3f}, {np.quantile(draws, 0.95):.3f}]"
      f"   (r_hat {float(az.rhat(idata_pooled.posterior['effect'].values)):.3f}, "
      f"bulk ESS {float(az.ess(idata_pooled.posterior['effect'].values)):.0f}, "
      f"divergences {int(idata_pooled.sample_stats['diverging'].sum())})")
world B, bench test, closed form: 13.113, 90% interval [11.217, 15.010]
world B, bench test, NUTS:        13.127, 90% interval [11.233, 14.971]   (r_hat 1.001, bulk ESS 1597, divergences 0)

NUTS and the closed form agree to within a few cents, with a clean fit. The priors differ (the NUTS model uses ordinary weak priors, the closed form the conjugate one), and with 3,200 transactions that makes no visible difference.

The choice. The pooled straight-line model in closed form, on store-level sums. Rejected: sampling every posterior with NUTS (the same answer, and the coverage curves below need nearly five million posteriors). What would change our mind: a model with no closed form, which is part 5.

2 · Bagging the posterior

A bootstrap copy of the data is made by drawing units from the dataset with replacement, as many as the dataset has. The first decision is what a unit is. The bootstrap treats the units as independent draws from some population, so a unit should be the thing that was sampled independently. Here there are two candidates.

  • Transactions. Draw 3,200 transactions with replacement from the 3,200. This is what one does without thinking, and it matches the model, which also treats transactions as independent.
  • Stores. Draw 40 stores with replacement from the 40, and take all the transactions of each store drawn. This matches how the test was run: stores were chosen, then observed.

Either way, each copy gets its own closed-form posterior, and the bagged posterior is the equal mixture of the $B = 100$ Student-t distributions. Huggins and Miller report that 50 to 100 copies were enough in their applications, and we check that below.

B = 100


def bag_stores(y, B, rng, size=None, **kw):
    """Posteriors of B bootstrap copies made by resampling stores: (reps, B) arrays of dof, centre, scale."""
    m = y.shape[-1]
    s, q = store_sums(y)
    size = np.full(len(s), J) if size is None else np.asarray(size)
    c = rng.multinomial(size[:, None], np.full(J, 1 / J), size=(len(s), B)).astype(float)   # (reps, B, J)
    return effect_posterior(m * c, c * s[:, None, :], np.einsum("rbj,rj->rb", c, q), **kw)


def bag_transactions(y, B, rng):
    """The same, resampling individual transactions (one test at a time: this one needs the rows)."""
    reps, _, m = y.shape
    n = J * m
    flat = y.reshape(reps, n)
    out = np.empty((3, reps, B))
    offset = J * np.arange(B)[:, None]
    for r in range(reps):
        idx = rng.integers(0, n, (B, n))
        yy = flat[r][idx]
        key = (idx // m + offset).ravel()                                  # which store, in which copy
        count = np.bincount(key, minlength=B * J).reshape(B, J).astype(float)
        total = np.bincount(key, weights=yy.ravel(), minlength=B * J).reshape(B, J)
        out[:, r] = effect_posterior(count, total, (yy**2).sum(1))
    return tuple(out)


def mixture_draws(dof, loc, scale, n_draws, rng):
    """Draws from the equal mixture of the B posteriors of each test: an array (n_draws, reps)."""
    reps, n_comp = loc.shape
    pick = rng.integers(0, n_comp, (n_draws, reps))
    r = np.arange(reps)[None, :]
    return loc[r, pick] + scale[r, pick] * rng.standard_t(dof[r, pick])


def spreads(dof, loc, scale):
    """Variance of the bagged posterior and its two parts: mean variance of the copies, variance of their centres."""
    within = (scale**2 * dof / (dof - 2)).mean(-1)
    between = loc.var(-1)
    return within + between, within, between


rng = np.random.default_rng(RANDOM_SEED + 1)
yb = BENCH["B"][None]
with sb.track("BayesBag, transactions resampled (100 closed forms)"):
    BAG_ROWS = bag_transactions(yb, B, rng)
with sb.track("BayesBag, stores resampled (100 closed forms)"):
    BAG_STORES = bag_stores(yb, B, rng)

dof, loc, scale = STD_BENCH["B"]
v_std = scale**2 * dof / (dof - 2)
print(f"world B, bench test, truth {TRUTH['B']:.2f}")
print(f"  standard posterior:            centre {loc:.2f}, sd {np.sqrt(v_std):.2f}, 90% interval "
      f"[{t_interval(dof, loc, scale)[0]:.2f}, {t_interval(dof, loc, scale)[1]:.2f}]")
BENCH_BAG = {}
for label, bag in (("transactions", BAG_ROWS), ("stores", BAG_STORES)):
    d = mixture_draws(*bag, 20000, rng)[:, 0]
    total, within, between = (float(v[0]) for v in spreads(*bag))
    BENCH_BAG[label] = (d.mean(), np.quantile(d, 0.05), np.quantile(d, 0.95))
    print(f"  bagged over {label:12s}:   centre {d.mean():.2f}, sd {np.sqrt(total):.2f}, 90% interval "
          f"[{np.quantile(d, 0.05):.2f}, {np.quantile(d, 0.95):.2f}]   variance {total:.2f} = "
          f"{within:.2f} (mean variance of a copy) + {between:.2f} (variance of the copies' centres)")
for n_copies in (25, 50, 100, 400, 1600):
    d = mixture_draws(*bag_stores(yb, n_copies, rng), 20000, rng)[:, 0]
    print(f"  stores, B = {n_copies:4d}: 90% interval [{np.quantile(d, 0.05):.2f}, {np.quantile(d, 0.95):.2f}]")
world B, bench test, truth 15.00
  standard posterior:            centre 13.11, sd 1.15, 90% interval [11.22, 15.01]
  bagged over transactions:   centre 13.17, sd 1.73, 90% interval [10.35, 15.97]   variance 3.01 = 1.33 (mean variance of a copy) + 1.68 (variance of the copies' centres)
  bagged over stores      :   centre 13.01, sd 2.59, 90% interval [9.06, 17.30]   variance 6.68 = 1.37 (mean variance of a copy) + 5.31 (variance of the copies' centres)
  stores, B =   25: 90% interval [9.55, 17.16]
  stores, B =   50: 90% interval [8.84, 17.89]
  stores, B =  100: 90% interval [9.08, 17.07]
  stores, B =  400: 90% interval [8.80, 17.37]
  stores, B = 1600: 90% interval [8.74, 17.57]
fig, axes = plt.subplots(1, 2, figsize=(13, 4.1))
grid = np.linspace(loc - 11, loc + 11, 600)


def mixture_pdf(bag, grid):
    d, l, s = (v[0] for v in bag)
    return stats.t.pdf(grid[:, None], d, l, s).mean(axis=1)


ax = axes[0]
d, l, s = (v[0] for v in BAG_STORES)
for k in range(40):
    ax.plot(grid, stats.t.pdf(grid, d[k], l[k], s[k]) / 8, color=BLUE, lw=0.6, alpha=0.45)
ax.plot([], [], color=BLUE, lw=0.8, label="posterior of one bootstrap copy (40 of the 100, scaled down)")
ax.plot(grid, mixture_pdf(BAG_STORES, grid), color=ORANGE, lw=2.2, label="their average: the bagged posterior")
ax.axvline(TRUTH["B"], color=INK, lw=1, ls="--")
ax.set_title("Stores resampled: every copy is sure of a different answer", loc="left", fontsize=10)
ax.set_xlabel("effect of a 30% discount on the mean basket (\\$)")
ax.set_yticks([])
ax.legend(frameon=False, fontsize=8, loc="upper left")
ax.set_ylim(0, ax.get_ylim()[1] * 1.3)
tidy(ax, grid=None)

ax = axes[1]
ax.plot(grid, stats.t.pdf(grid, dof, loc, scale), color=INK, lw=1.8, label="standard posterior")
ax.plot(grid, mixture_pdf(BAG_ROWS, grid), color=AQUA, lw=1.8, label="bagged over transactions")
ax.plot(grid, mixture_pdf(BAG_STORES, grid), color=ORANGE, lw=2.2, label="bagged over stores")
ax.axvline(TRUTH["B"], color=INK, lw=1, ls="--")
ax.text(TRUTH["B"], ax.get_ylim()[1] * 0.97, " truth", fontsize=8, va="top")
ax.set_ylim(0, None)
ax.set_title("World B, the bench test: three posteriors of the same model", loc="left", fontsize=10)
ax.set_xlabel("effect of a 30% discount on the mean basket (\\$)")
ax.set_yticks([])
ax.legend(frameon=False, fontsize=8, loc="upper left")
tidy(ax, grid=None);
Figure

The left panel shows what bagging is. Each thin curve is the posterior of one bootstrap copy made by drawing stores. Every one of them is as narrow as the standard posterior, and they sit in different places, because a copy that happens to draw the stores with high levels at the deep discounts gives a steeper line. The bagged posterior is the average of the curves.

The printed decomposition says where its width comes from. By the law of total variance, the variance of a mixture is the mean variance of its components plus the variance of their centres:

$$v^* \;=\; \underbrace{\overline{\operatorname{Var}(\theta \mid y^{*})}}_{\text{what the model says}} \;+\; \underbrace{\operatorname{Var}\big(\mathrm E[\theta \mid y^{*}]\big)}_{\text{what the bootstrap saw}}.$$

The first part is the standard posterior's variance again. The second is a bootstrap estimate of how much the posterior mean moves from one dataset to the next, which is the quantity the standard posterior of a wrong model gets wrong. Huggins and Miller show that for large samples the first part tends to the model's variance and the second to the sandwich variance, the real variance of the estimate. So the bagged posterior is never narrower than the truth requires, and when the model is right the two parts are equal and it is too wide by a factor of two in variance. That is a known price, and it has a consequence we can use: the ratio of the two spreads says whether the model's own variance was right (part 4).

Now compare the two bootstraps. Resampling transactions gives a second part as large as the first, which is the signature of a correct model: this bootstrap sees transactions that look independent, because it has broken up the stores, and it reports no trouble. Resampling stores gives a second part several times larger than the first. The transactions are the same in both. Only the store bootstrap keeps the baskets of a store together, so only it can see that they move together.

The last lines repeat the store bootstrap with different numbers of copies. The interval's ends move by up to half a dollar between 100 copies and 1,600, against a width of about eight dollars. One hundred is enough for an interval, and we will see in part 4 that it leaves visible noise in the ratio of the two spreads.

The choice. Resample stores. Rejected: resampling transactions, which is the default in most software and assumes the very independence we doubt. What would change our mind: a test in which transactions were sampled independently from one population (an online experiment randomised by visit, with one visit per customer). Then the transaction is the unit.

3 · As the test runs longer

One dataset shows one interval. To learn how often the intervals are right we repeat the test 1,000 times in each world and at each of five durations, from 5 transactions per store (200 in all) to 1,280 per store (51,200 in all), and count how often each 90% interval contains the true effect. The transaction bootstrap needs every row of every copy, so we run it on 200 of the tests and up to 12,800 transactions; everything else uses store-level sums and all 1,000 tests.

REPS, REPS_ROWS, N_DRAWS, CHUNK = 1000, 200, 2000, 100


def tuned_size(v, v_star):
    """Huggins and Miller's bootstrap size: the number of stores to draw so that the bagged variance matches
    the bootstrap's own estimate of the sampling variance. Kept between J and 4J; J when it is undefined."""
    with np.errstate(divide="ignore", invalid="ignore"):
        size = np.where(v_star > v, J * v_star / (v_star - v), J)
    return np.clip(np.round(size), J, 4 * J).astype(int)


def coverage_study(world, m, rng):
    """Repeat the test REPS times; return per-test intervals, estimates and spreads for every method."""
    out = {k: [] for k in ("std", "stores", "tuned", "quad", "quad_stores", "curve", "rows")}
    keep = {k: [] for k in ("est", "v", "v_stores", "v_rows", "size", "draws_std", "draws_stores", "draws_rows", "draws_tuned")}
    for start in range(0, REPS, CHUNK):
        y = simulate(world, m, CHUNK, rng)
        dof, loc, scale = standard_posterior(y)
        v = scale**2 * dof / (dof - 2)
        out["std"].append(np.stack(t_interval(dof, loc, scale)))
        bag = bag_stores(y, B, rng)
        d = mixture_draws(*bag, N_DRAWS, rng)
        out["stores"].append(np.quantile(d, [0.05, 0.95], axis=0))
        v_star = spreads(*bag)[0]
        size = tuned_size(v, v_star)
        d_tuned = mixture_draws(*bag_stores(y, B, rng, size=size), N_DRAWS, rng)
        out["tuned"].append(np.quantile(d_tuned, [0.05, 0.95], axis=0))
        out["quad"].append(np.stack(t_interval(*standard_posterior(y, F=F_QUAD, c=C_QUAD))))
        dq = mixture_draws(*bag_stores(y, B, rng, F=F_QUAD, c=C_QUAD), N_DRAWS, rng)
        out["quad_stores"].append(np.quantile(dq, [0.05, 0.95], axis=0))
        out["curve"].append(np.stack(t_interval(*standard_posterior(y, F=F_QUAD, c=np.array([0.0, 0.0, 1.0])))))
        keep["est"].append(loc), keep["v"].append(v), keep["v_stores"].append(v_star), keep["size"].append(size)
        if m == M_BENCH and world == "B":
            keep["draws_std"].append(loc + scale * rng.standard_t(dof, (N_DRAWS, CHUNK)))
            keep["draws_stores"].append(d), keep["draws_tuned"].append(d_tuned)
        if start < REPS_ROWS and m <= 320:
            bag_r = bag_transactions(y, B, rng)
            d_rows = mixture_draws(*bag_r, N_DRAWS, rng)
            out["rows"].append(np.quantile(d_rows, [0.05, 0.95], axis=0))
            keep["v_rows"].append(spreads(*bag_r)[0])
            if m == M_BENCH and world == "B":
                keep["draws_rows"].append(d_rows)
    res = {k: np.concatenate(v, axis=1) for k, v in out.items() if v}
    res.update({k: np.concatenate(v, axis=-1) for k, v in keep.items() if v})
    return res


rng = np.random.default_rng(RANDOM_SEED + 2)
t0 = time.time()
STUDY = {(w, m): coverage_study(w, m, rng) for w in WORLDS for m in M_GRID}
print(f"{len(STUDY) * REPS:,} repeated tests, {time.time() - t0:.0f} s")

METHODS = {"std": "standard posterior", "rows": "BayesBag, transactions", "stores": "BayesBag, stores",
           "tuned": "BayesBag, stores, tuned size"}


def cover(interval, truth):
    return float(np.mean((interval[0] <= truth) & (truth <= interval[1])))


rows = []
for (w, m), res in STUDY.items():
    row = {"world": w, "transactions": J * m, "bias of the estimate": res["est"].mean() - TRUTH[w],
           "sd of the estimate": res["est"].std(), "posterior sd": np.sqrt(res["v"].mean())}
    for k, label in METHODS.items():
        row[f"coverage: {label}"] = cover(res[k], TRUTH[w]) if k in res else np.nan
    for k, label in METHODS.items():
        row[f"width: {label}"] = float(np.mean(res[k][1] - res[k][0])) if k in res else np.nan
    rows.append(row)
COV = pd.DataFrame(rows).set_index(["world", "transactions"])
print("\ncoverage of the 90% interval (1,000 tests; 200 for the transaction bootstrap, not run at 51,200)")
print(COV[[c for c in COV if c.startswith("coverage")]].rename(columns=lambda c: c.replace("coverage: ", "")).round(3).to_string())
print("\nthe estimate and the posterior's idea of it, in dollars; mean widths of the 90% intervals")
print(COV[[c for c in COV if not c.startswith("coverage")]].rename(columns=lambda c: c.replace("width: ", "w: ")).round(2).to_string())
15,000 repeated tests, 22 s

coverage of the 90% interval (1,000 tests; 200 for the transaction bootstrap, not run at 51,200)
                    standard posterior  BayesBag, transactions  BayesBag, stores  BayesBag, stores, tuned size
world transactions                                                                                            
A     200                        0.891                    0.97             0.981                         0.875
      800                          0.9                    0.98             0.967                         0.889
      3200                       0.906                   0.995             0.982                         0.888
      12800                      0.898                   0.975             0.978                          0.88
      51200                      0.905                     NaN             0.976                         0.879
B     200                        0.873                    0.95             0.975                         0.884
      800                        0.819                   0.925             0.958                         0.892
      3200                       0.609                    0.74             0.932                         0.889
      12800                      0.331                    0.45             0.887                          0.87
      51200                      0.175                     NaN             0.892                         0.882
C     200                        0.732                    0.88              0.91                         0.739
      800                        0.362                   0.575             0.658                         0.401
      3200                       0.011                    0.04               0.1                         0.034
      12800                          0                       0                 0                             0
      51200                          0                     NaN                 0                             0

the estimate and the posterior's idea of it, in dollars; mean widths of the 90% intervals
                    bias of the estimate  sd of the estimate  posterior sd  w: standard posterior  w: BayesBag, transactions  w: BayesBag, stores  w: BayesBag, stores, tuned size
world transactions                                                                                                                                                                
A     200                           0.27                4.49           4.5                   14.8                       20.9                 20.9                             14.6
      800                           0.02                2.27          2.25                    7.4                       10.4                 10.5                             7.28
      3200                         -0.04                1.13          1.13                    3.7                        5.2                 5.23                             3.63
      12800                         0.01                0.56          0.56                   1.85                        2.6                 2.62                             1.82
      51200                        -0.01                0.28          0.28                   0.93                        NaN                 1.31                             0.91
B     200                          -0.02                4.94          4.58                   15.1                       21.3                   22                             15.8
      800                           0.14                2.94          2.29                   7.55                       10.7                 12.4                             9.64
      3200                          0.07                2.23          1.15                   3.77                       5.29                 8.37                             7.44
      12800                         0.02                2.08          0.57                   1.89                       2.66                 6.99                             6.71
      51200                          0.1                2.01          0.29                   0.94                        NaN                 6.61                             6.54
C     200                            4.4                4.49          4.52                   14.9                       20.9                 21.2                             14.9
      800                           4.53                2.32          2.25                   7.41                       10.4                 10.8                             7.73
      3200                          4.51                1.14          1.13                   3.71                       5.23                 5.93                             4.57
      12800                         4.46                0.56          0.56                   1.86                        2.6                 3.83                              3.3
      51200                         4.45                0.29          0.28                   0.93                        NaN                 3.09                             2.93
rng = np.random.default_rng(RANDOM_SEED + 3)
fig, axes = plt.subplots(2, 3, figsize=(13.5, 7.6), sharex=True)
n_grid = J * np.array(M_GRID)
FOLLOW = {}
for col, w in enumerate(WORLDS):
    ax = axes[0, col]
    FOLLOW[w] = []
    for i, m in enumerate(M_GRID):
        y = LONG[w][None, :, :m]
        dof, loc, scale = (float(v[0]) for v in standard_posterior(y))
        lo, hi = t_interval(dof, loc, scale)
        d = mixture_draws(*bag_stores(y, 400, rng), 20000, rng)[:, 0]
        blo, bhi = np.quantile(d, [0.05, 0.95])
        FOLLOW[w].append((J * m, loc, lo, hi, blo, bhi))
        ax.plot([n_grid[i] * 0.86] * 2, [lo, hi], color=INK, lw=3.2, solid_capstyle="butt")
        ax.plot([n_grid[i] * 1.16] * 2, [blo, bhi], color=ORANGE, lw=3.2, solid_capstyle="butt")
        ax.plot([n_grid[i] * 0.86, n_grid[i] * 1.16], [loc, d.mean()], "o", ms=3.5, color="white", mec=INK, mew=0.8)
    ax.axhline(TRUTH[w], color=INK, lw=1, ls="--")
    ax.set_title(f"World {w}: {WORLDS[w]}", loc="left", fontsize=10)
    ax.set_xscale("log")
    tidy(ax)
    ax = axes[1, col]
    for k, colour, marker in (("std", INK, "o"), ("rows", AQUA, "s"), ("stores", ORANGE, "o"), ("tuned", VIOLET, "^")):
        cov = COV.loc[w, f"coverage: {METHODS[k]}"].to_numpy()
        ax.plot(n_grid, cov, marker=marker, ms=4.5, color=colour, lw=1.6, label=METHODS[k])
    ax.axhline(CI, color=MUTED, lw=1, ls="--")
    ax.set_ylim(-0.03, 1.03)
    ax.set_xlabel("transactions in the test (40 stores)")
    ax.set_xticks(n_grid, [f"{n:,}" for n in n_grid], fontsize=8)
    ax.minorticks_off()
    tidy(ax)
axes[0, 0].plot([], [], color=INK, lw=3.2, label="standard posterior, 90% interval")
axes[0, 0].plot([], [], color=ORANGE, lw=3.2, label="bagged over stores, 90% interval")
axes[0, 0].plot([], [], color=INK, lw=1, ls="--", label="truth")
axes[0, 0].legend(frameon=False, fontsize=8, loc="upper right")
axes[0, 0].set_ylabel("one test, followed as it runs longer:\neffect of a 30% discount (\\$)")
axes[1, 0].set_ylabel("1,000 repeated tests:\ncoverage of the 90% interval")
axes[1, 0].legend(frameon=False, fontsize=8, loc="lower left")
for w in WORLDS:
    n, loc, lo, hi, blo, bhi = FOLLOW[w][-1]
    print(f"world {w}, the followed test at {n:,} transactions: standard {loc:.2f} [{lo:.2f}, {hi:.2f}], "
          f"bagged over stores [{blo:.2f}, {bhi:.2f}], truth {TRUTH[w]:.2f}")
world A, the followed test at 51,200 transactions: standard 14.79 [14.32, 15.25], bagged over stores [14.08, 15.53], truth 15.00
world B, the followed test at 51,200 transactions: standard 12.51 [12.03, 12.98], bagged over stores [9.16, 16.33], truth 15.00
world C, the followed test at 51,200 transactions: standard 18.81 [18.35, 19.28], bagged over stores [17.31, 20.11], truth 14.69
Figure

The top row follows one test in each world as it accumulates transactions. The bottom row counts over 1,000 tests. Read the three columns in turn.

World A, the model is right. The standard interval covers 90% at every size, as it should. Both bagged intervals cover 97% or more. They are 1.4 times as wide as they need to be, which is the factor of two in variance from part 2. Bagging a correct model is safe and wasteful.

World B, stores differ. The standard posterior behaves the way the introduction warned. Its interval narrows with every transaction, as $1/\sqrt{N}$, and its estimate does not get better at that rate, because the stores' own levels do not average out by observing the same 40 stores for longer. The printed table shows the two numbers drifting apart: at 51,200 transactions the estimate still varies by about \$2 from one test to the next, and the posterior claims a standard deviation of about 30 cents. The coverage of the 90% interval falls from 87% at 200 transactions to 61% at the bench size and to 18% at the largest. In the followed test the black bar closes in on a value that is not the truth.

Which kind of failure is this? The estimate is right on average: its bias in the table is a few cents. Each single test lands on a value of its own, off by the luck of which stores got which discount, and the standard posterior shrinks onto that value. So it is the width that is wrong, and the centre is as good as 40 stores allow. That is the case bagging was made for, and the store bootstrap handles it: its coverage stays between 89 and 98% at every size, and its width stops shrinking when the estimate stops improving.

The transaction bootstrap fails with the standard posterior. It covers 95% at 200 transactions, when stores hardly matter and it is simply too wide, and 45% at 12,800. It doubles the variance of the standard posterior whatever the data look like, and doubling is not enough when the real variance is more than ten times the model's. A bootstrap that resamples the wrong unit inherits the model's mistake.

World C, the response flattens. Here the estimate is wrong on average, by about \$4.50 at every size: the least-squares line through a saturating curve keeps climbing past 20%, where the curve does not. The standard interval shrinks onto about \$19 and its coverage is 73% at 200 transactions, 36% at 800, 1% at 3,200 and nil beyond. The interval bagged over stores is wider and shrinks onto the same wrong value: 91%, 66%, 10%, then nil. Bagging bought some honesty while the intervals were wide enough to include the truth by accident, and none once the data were plentiful. This is the part of the expected lesson that does not hold. When the standard posterior "shrinks onto the wrong value" because the model aims at the wrong value, the bagged posterior follows it there.

The choice. BayesBag over stores when the worry is that the estimate is less certain than the model thinks. Rejected: trusting it against a wrong mean function. What would change our mind: nothing in these numbers. Bagging averages posteriors of the same model, and the average of posteriors centred near \$19 is centred near \$19.

4 · Can the two spreads detect a wrong model?

Part 2 found that the bagged variance is the model's variance plus the bootstrap's estimate of the real one, and that the two are equal when the model is right. Huggins and Miller turn this into a diagnostic. With $v$ the variance of the standard posterior and $v^*$ the variance of the bagged one, their mismatch index is, in its large-sample form,

$$\mathcal I \;=\; 1 - \frac{2v}{v^*} \qquad (\text{defined when } v^* > v).$$

It is 0 when $v^* = 2v$, the correct-model case. It rises towards 1 as the bootstrap sees more variability than the model allows, which means the standard posterior is overconfident. It is negative when the model is more cautious than it needs to be. We have $v$ and $v^*$ for every one of the repeated tests, under both bootstraps, so we can look at how the index behaves where we know the answer.

def mismatch(v, v_star):
    return np.where(v_star > v, 1 - 2 * v / np.where(v_star > v, v_star, 1.0), np.nan)


rows = []
for (w, m), res in STUDY.items():
    for unit, key in (("stores", "v_stores"), ("transactions", "v_rows")):
        if key in res:
            idx = mismatch(res["v"][: len(res[key])], res[key])
            q = np.nanquantile(idx, [0.1, 0.5, 0.9])
            rows.append({"world": w, "transactions": J * m, "unit resampled": unit, "10%": q[0], "median": q[1], "90%": q[2],
                         "share above 0.3": np.nanmean(idx > 0.3), "undefined": np.mean(np.isnan(idx)),
                         "coverage of the standard interval": COV.loc[(w, J * m), "coverage: standard posterior"]})
INDEX = pd.DataFrame(rows).set_index(["world", "unit resampled", "transactions"]).sort_index()
print("mismatch index over the repeated tests")
print(INDEX.round(2).to_string())

fig, axes = plt.subplots(1, 3, figsize=(13.5, 3.9), sharey=True)
for ax, w in zip(axes, WORLDS):
    for unit, colour in (("stores", ORANGE), ("transactions", AQUA)):
        t = INDEX.loc[(w, unit)]
        ax.fill_between(t.index, t["10%"], t["90%"], color=colour, alpha=0.2, lw=0)
        ax.plot(t.index, t["median"], marker="o", ms=4.5, color=colour, lw=1.6, label=f"{unit} resampled")
    ax.axhline(0, color=MUTED, lw=1, ls="--")
    for n, c in COV.loc[w, "coverage: standard posterior"].items():
        ax.text(n, -0.44, f"{c:.0%}", ha="center", fontsize=8, color=INK)
    ax.set_xscale("log")
    ax.set_xticks(n_grid, [f"{n:,}" for n in n_grid], fontsize=8)
    ax.minorticks_off()
    ax.set_ylim(-0.5, 1.02)
    ax.set_xlabel("transactions in the test")
    ax.set_title(f"World {w}: {WORLDS[w]}", loc="left", fontsize=10)
    tidy(ax)
axes[0].set_ylabel("mismatch index (median, 10% to 90%)")
axes[0].text(n_grid[0] * 0.8, -0.34, "coverage of the standard 90% interval:", fontsize=8, color=MUTED)
axes[0].legend(frameon=False, fontsize=8, loc="upper left");
mismatch index over the repeated tests
                                    10%  median  90%  share above 0.3  undefined  coverage of the standard interval
world unit resampled transactions                                                                                  
A     stores         200          -0.21   -0.01 0.19             0.01          0                               0.89
                     800          -0.22   -0.01 0.18             0.02          0                                0.9
                     3200         -0.21   -0.01 0.17             0.01          0                               0.91
                     12800        -0.21   -0.01 0.19             0.02          0                                0.9
                     51200        -0.21   -0.02 0.19             0.02          0                                0.9
      transactions   200          -0.11      -0 0.09                0          0                               0.89
                     800          -0.09      -0 0.09                0          0                                0.9
                     3200         -0.11   -0.01 0.08                0          0                               0.91
                     12800         -0.1   -0.01 0.08                0          0                                0.9
B     stores         200          -0.14    0.06 0.24             0.04          0                               0.87
                     800           0.06    0.25 0.41             0.35          0                               0.82
                     3200          0.42    0.59  0.7             0.99          0                               0.61
                     12800         0.78    0.85  0.9                1          0                               0.33
                     51200         0.94    0.96 0.97                1          0                               0.18
      transactions   200          -0.12   -0.01  0.1                0          0                               0.87
                     800          -0.11   -0.01  0.1                0          0                               0.82
                     3200          -0.1   -0.01 0.06                0          0                               0.61
                     12800        -0.11   -0.01 0.09                0          0                               0.33
C     stores         200           -0.2    0.02 0.19             0.02          0                               0.73
                     800          -0.16    0.06 0.24             0.04          0                               0.36
                     3200          0.02    0.21 0.37             0.25          0                               0.01
                     12800          0.4    0.53 0.63             0.98          0                                  0
                     51200         0.77    0.82 0.86                1          0                                  0
      transactions   200          -0.13   -0.01 0.09                0          0                               0.73
                     800          -0.11   -0.02 0.08                0          0                               0.36
                     3200          -0.1   -0.01 0.08                0          0                               0.01
                     12800         -0.1   -0.01 0.07                0          0                                  0
Figure

Lines are medians over the repeated tests, bands hold the middle 80%, and the small numbers along the bottom are the coverage of the standard interval, which is what the index is supposed to warn about.

In world A the index sits at zero under both bootstraps, as designed. With stores as the unit its band runs from about -0.2 to +0.2 and does not narrow as transactions accumulate. Two sources of noise are in it. One is the use of 100 copies, which alone gives the band of about 0.1 either way that the transaction index shows. The other is that a variance between stores is being estimated from 40 of them, whatever their size. A single value of 0.2 is not evidence of anything.

In world B the store index does its job once there is something to see: 0.25 at 800 transactions, 0.59 at the bench size, 0.85 at 12,800, well clear of the band of world A. So does the reverse: the index is how we would learn, from the data alone, that the store is the unit that matters. It also shows the first of three ways the detector fails.

Failure 1: the wrong unit. The transaction index stays at zero in world B at every size, while the coverage of the standard interval falls to 33%. A bootstrap of transactions cannot see dependence between transactions. The diagnostic shares the model's assumption and so confirms it.

Failure 2: too little to see yet. At 200 transactions the store index in world B is 0.06, indistinguishable from world A, and the standard interval already covers 87% instead of 90. That is a small miss, and the index is honest about it being small. But the trouble grows with the length of the test and the index only shows it once it is large.

Failure 3: a wrong centre. In world C the transaction index is zero throughout. The store index is near zero at 200 and 800 transactions, where the standard interval's coverage has already fallen to 73% and 36%. It is 0.21 at 3,200, barely out of the noise, when coverage is down to 1%, and it is clear only from 12,800 on. The reason it moves at all is instructive. All the stores at one depth miss the fitted line by the same amount, since the line is wrong there, and to a bootstrap of stores a shared miss looks like stores moving together. So the index eventually reports a mismatch, and the remedy it points to, the bagged posterior, does not work (part 3). The index compares two spreads. It has nothing to say about where the posterior is centred.

Tuning the bootstrap size

The index has a practical use beyond diagnosis. Bagging over-covers in world A because the bagged variance is the sum of two parts and only the second is needed. Huggins and Miller's remedy is to draw bootstrap copies larger than the data: a copy of $M$ units has both parts scaled by $N/M$, and $M = N v^* / (v^* - v)$ makes the total equal to the bootstrap's estimate of the real variance. That is $2N$ when the model is right and close to $N$ when the model's variance is negligible. With stores as units we draw between 40 and 160 stores per copy. The violet line in the coverage figure is this tuned version.

tuned = pd.DataFrame({
    "median stores per copy": {k: np.median(res["size"]) for k, res in STUDY.items()},
    "coverage, 40 stores per copy": {k: COV.loc[(k[0], J * k[1]), "coverage: BayesBag, stores"] for k in STUDY},
    "coverage, tuned": {k: COV.loc[(k[0], J * k[1]), "coverage: BayesBag, stores, tuned size"] for k in STUDY},
    "width, 40 stores per copy": {k: COV.loc[(k[0], J * k[1]), "width: BayesBag, stores"] for k in STUDY},
    "width, tuned": {k: COV.loc[(k[0], J * k[1]), "width: BayesBag, stores, tuned size"] for k in STUDY},
    "width, standard": {k: COV.loc[(k[0], J * k[1]), "width: standard posterior"] for k in STUDY},
})
tuned.index = pd.MultiIndex.from_tuples([(w, J * m) for w, m in tuned.index], names=["world", "transactions"])
print(tuned.loc[["A", "B"]].round(3).to_string())
                    median stores per copy  coverage, 40 stores per copy  coverage, tuned  width, 40 stores per copy  width, tuned  width, standard
world transactions                                                                                                                                 
A     200                               81                         0.981            0.875                       20.9          14.6             14.8
      800                               80                         0.967            0.889                       10.5          7.28              7.4
      3200                              81                         0.982            0.888                       5.23          3.63              3.7
      12800                             81                         0.978             0.88                       2.62          1.82             1.85
      51200                             81                         0.976            0.879                       1.31         0.909            0.925
B     200                               76                         0.975            0.884                         22          15.8             15.1
      800                               64                         0.958            0.892                       12.4          9.64             7.54
      3200                              50                         0.932            0.889                       8.37          7.44             3.77
      12800                             43                         0.887             0.87                       6.99          6.71             1.89
      51200                             41                         0.892            0.882                       6.61          6.54            0.943

In world A the tuned bootstrap draws about 80 stores per copy, twice the data, and its interval comes back to the width of the standard one. In world B it draws fewer as the test runs longer, down towards 40. Its coverage is 87 to 89% in both worlds, a little under the 90% it aims at. The shortfall is the price of estimating a variance from 40 stores and then trusting the estimate: the default bagged posterior hides that with its surplus width, and the tuned one has no surplus. With hundreds of units the gap would close.

The choice. Compute the index with the unit that was sampled, read it as a warning about width only, and treat values within 0.2 of zero as nothing. Use the tuned size when the default interval is too wide to be useful and there are enough units to estimate a variance. Rejected: reading an index near zero as a certificate that the model is right. What would change our mind: a version of the index that also looked at the centre, which would have to come from outside the model, from held-out data or a richer model.

5 · When the posterior has no closed form

So far every posterior was a formula. Most models are not like that, and then BayesBag costs $B$ fits. The same test has a second outcome that makes the point: whether a basket contains a promoted product, yes or no. With no discount 20% of baskets do, and the log-odds rise by 0.25 for every ten points of discount, so a 30% discount raises the share by 14.6 percentage points. Stores differ here too: each store's own rate is drawn around the curve (a Beta distribution with precision 60, a standard deviation of about 5 points). The analyst's model is a pooled logistic regression, binomial counts per store with no allowance for store differences, and it has no closed-form posterior.

We do the $B = 100$ fits two ways.

  • NUTS, 100 times. The model is compiled once with nutpie. The bootstrap weights of the stores enter through pm.Data, so each refit is compiled.with_data(w=...) followed by a short run of two chains. The likelihood is a pm.Potential, the binomial log-probability of each store times its weight.
  • Laplace, 100 times. Find the posterior mode by Newton's method, take the inverse of the negative Hessian there as the covariance, and draw from that Gaussian. For a two-parameter logistic regression this is a few lines of NumPy and runs for all 100 copies at once. pymc_extras.fit_laplace does the same for any PyMC model, and we time it on one fit.

NUTS is the reference: it samples each copy's posterior without approximation. Laplace is the fast approximation, good when each posterior is close to Gaussian, which a pooled logistic regression on 3,200 transactions is.

PHI, A_CONV, B_CONV = 60.0, special.logit(0.20), 0.25
TRUTH_CONV = 100 * float(special.expit(A_CONV + TARGET / 10 * B_CONV) - special.expit(A_CONV))   # percentage points


def simulate_conversions(reps, rng, m=M_BENCH):
    """Baskets with a promoted product, per store: (reps, J) counts out of m."""
    p = special.expit(A_CONV + B_CONV * X)
    return rng.binomial(m, rng.beta(p * PHI, (1 - p) * PHI, (reps, J)))


def conversion_model(overdispersed):
    with pm.Model() as model:
        w = pm.Data("w", np.ones(J))
        k = pm.Data("k", np.zeros(J, dtype="int64"))
        a = pm.Normal("a", 0.0, 2.0)
        b = pm.Normal("b", 0.0, 1.0)
        p = pm.math.invlogit(a + b * X)
        if overdispersed:
            phi = pm.LogNormal("phi", np.log(50.0), 1.5)
            dist = pm.BetaBinomial.dist(n=M_BENCH, alpha=p * phi, beta=(1 - p) * phi)
        else:
            dist = pm.Binomial.dist(n=M_BENCH, p=p)
        pm.Potential("loglik", (w * pm.logp(dist, k)).sum())
        pm.Deterministic("effect", 100 * (pm.math.invlogit(a + TARGET / 10 * b) - pm.math.invlogit(a)))
    return model


D_CONV = np.stack([np.ones(J), X], axis=1)
PRIOR_PREC = np.array([1 / 2.0**2, 1.0])


def laplace_fit(k, w, iters=30):
    """Mode and covariance of the pooled logistic posterior by Newton's method; k and w of shape (..., J)."""
    theta = np.zeros(k.shape[:-1] + (2,))
    theta[..., 0] = special.logit((w * k).sum(-1) / (w * M_BENCH).sum(-1))
    for _ in range(iters):
        p = special.expit(theta @ D_CONV.T)
        grad = ((w * (k - M_BENCH * p))[..., None] * D_CONV).sum(-2) - PRIOR_PREC * theta
        hess = np.einsum("...j,jp,jq->...pq", w * M_BENCH * p * (1 - p), D_CONV, D_CONV) + np.diag(PRIOR_PREC)
        theta = theta + np.linalg.solve(hess, grad[..., None])[..., 0]
    return theta, np.linalg.inv(hess)


def laplace_effect(theta, cov, n_draws, rng):
    """Draws of the effect (percentage points) from the Gaussian approximations: (..., n_draws)."""
    chol = np.linalg.cholesky(cov)
    th = theta[..., None, :] + np.einsum("...pq,...sq->...sp", chol, rng.normal(size=theta.shape[:-1] + (n_draws, 2)))
    return 100 * (special.expit(th[..., 0] + TARGET / 10 * th[..., 1]) - special.expit(th[..., 0]))


def store_weights(shape, rng):
    return rng.multinomial(J, np.full(J, 1 / J), size=shape).astype(float)


def nuts_bag(compiled, weights, seed=0, **new_data):
    """One short NUTS run per bootstrap copy; returns the pooled draws of the effect."""
    out = []
    for i, w in enumerate(weights):
        trace = nuts(compiled, draws=250, tune=300, chains=2, seed=seed + i, w=w, **new_data)
        out.append(trace.posterior["effect"].values.ravel())
    return np.concatenate(out)


rng = np.random.default_rng(RANDOM_SEED + 4)
K_TESTS = simulate_conversions(REPS, rng)
k_bench = K_TESTS[0]
W_BENCH = store_weights(B, rng)
sbc = Scoreboard(truth={"effect": np.full(REPS, TRUTH_CONV)}, ci_prob=CI)

with sbc.track("standard posterior (NUTS)"):
    pooled_conv = nutpie.compile_pymc_model(conversion_model(overdispersed=False))
    idata_conv = nuts(pooled_conv, k=k_bench)
with sbc.track("BayesBag, stores (100 NUTS refits)"):
    bag_nuts = nuts_bag(pooled_conv, W_BENCH, k=k_bench)
with sbc.track("standard posterior (Laplace)"):
    std_lap = laplace_effect(*laplace_fit(k_bench, np.ones(J)), 4000, rng)
with sbc.track("BayesBag, stores (100 Laplace fits)"):
    bag_lap = laplace_effect(*laplace_fit(np.broadcast_to(k_bench, W_BENCH.shape), W_BENCH), 500, rng).ravel()

std_nuts = idata_conv.posterior["effect"].values
ESS_CONV = float(az.ess(std_nuts))
print(f"true effect of a 30% discount on the share of baskets with a promoted product: {TRUTH_CONV:.1f} points")
print(f"standard posterior, NUTS:      {std_nuts.mean():5.2f}, 90% interval [{np.quantile(std_nuts, 0.05):5.2f}, {np.quantile(std_nuts, 0.95):5.2f}]"
      f"   (r_hat {float(az.rhat(std_nuts)):.3f}, bulk ESS {ESS_CONV:.0f}, divergences {int(idata_conv.sample_stats['diverging'].sum())})")
print(f"standard posterior, Laplace:   {std_lap.mean():5.2f}, 90% interval [{np.quantile(std_lap, 0.05):5.2f}, {np.quantile(std_lap, 0.95):5.2f}]")
print(f"bagged over stores, 100 NUTS:  {bag_nuts.mean():5.2f}, 90% interval [{np.quantile(bag_nuts, 0.05):5.2f}, {np.quantile(bag_nuts, 0.95):5.2f}]")
print(f"bagged over stores, 100 Laplace: {bag_lap.mean():5.2f}, 90% interval [{np.quantile(bag_lap, 0.05):5.2f}, {np.quantile(bag_lap, 0.95):5.2f}]")
print(f"mismatch index on the bench test: {1 - 2 * std_nuts.var() / bag_nuts.var():.2f} (NUTS), {1 - 2 * std_lap.var() / bag_lap.var():.2f} (Laplace)")

gap = []
for r in range(1, 6):                      # five more tests: do the two routes keep agreeing?
    w_r = store_weights(B, rng)
    d_nuts = nuts_bag(pooled_conv, w_r, seed=1000 * r, k=K_TESTS[r])
    d_lap = laplace_effect(*laplace_fit(np.broadcast_to(K_TESTS[r], w_r.shape), w_r), 500, rng).ravel()
    gap.append(np.abs(np.quantile(d_nuts, [0.05, 0.95]) - np.quantile(d_lap, [0.05, 0.95])).max() / np.ptp(np.quantile(d_nuts, [0.05, 0.95])))
print(f"five more tests: the ends of the two bagged intervals differ by at most {max(gap):.1%} of the interval's width")

t0 = time.time()
with pm.Model() as pooled_for_pmx:
    a = pm.Normal("a", 0.0, 2.0)
    b = pm.Normal("b", 0.0, 1.0)
    pm.Binomial("k", n=M_BENCH, p=pm.math.invlogit(a + b * X), observed=k_bench)
    first = pmx.fit_laplace(progressbar=False)
    t1 = time.time()
    again = pmx.fit_laplace(progressbar=False)
print(f"pymc_extras.fit_laplace on the bench test: {t1 - t0:.1f} s the first time, {time.time() - t1:.2f} s the second; "
      f"slope {float(again.posterior['b'].mean()):.3f} against {float(idata_conv.posterior['b'].mean()):.3f} from NUTS")
true effect of a 30% discount on the share of baskets with a promoted product: 14.6 points
standard posterior, NUTS:      15.22, 90% interval [ 9.75, 20.86]   (r_hat 1.005, bulk ESS 920, divergences 0)
standard posterior, Laplace:   15.31, 90% interval [ 9.57, 21.19]
bagged over stores, 100 NUTS:  15.38, 90% interval [ 6.36, 24.20]
bagged over stores, 100 Laplace: 15.40, 90% interval [ 6.46, 24.13]
mismatch index on the bench test: 0.20 (NUTS), 0.14 (Laplace)
five more tests: the ends of the two bagged intervals differ by at most 0.9% of the interval's width
pymc_extras.fit_laplace on the bench test: 0.2 s the first time, 0.10 s the second; slope 0.256 against 0.259 from NUTS
t0 = time.time()
theta, cov = laplace_fit(K_TESTS, np.ones((REPS, J)))
CONV_STD = laplace_effect(theta, cov, N_DRAWS, rng).T                                     # (draws, tests)
W_ALL = store_weights((REPS, B), rng)
theta, cov = laplace_fit(np.broadcast_to(K_TESTS[:, None, :], W_ALL.shape), W_ALL)
CONV_BAG = laplace_effect(theta, cov, N_DRAWS // B, rng).reshape(REPS, -1).T
print(f"{REPS:,} tests, standard and bagged posteriors by Laplace: {time.time() - t0:.1f} s")


def refit_tests(compiled, datasets, draws=500, tune=400):
    """One two-chain NUTS fit per dataset (a list of dicts for with_data): draws (n, tests) and divergences."""
    out, divergent = [], 0
    for i, new_data in enumerate(datasets):
        trace = nuts(compiled, draws=draws, tune=tune, chains=2, seed=i, **new_data)
        out.append(trace.posterior["effect"].values.ravel())
        divergent += int(trace.sample_stats["diverging"].sum())
    return np.stack(out, axis=1), divergent


N_NUTS = 300
t0 = time.time()
CONV_STD_NUTS, div = refit_tests(pooled_conv, [{"k": k} for k in K_TESTS[:N_NUTS]])
print(f"{N_NUTS} tests, standard posterior by NUTS: {time.time() - t0:.1f} s, {div} divergences")


def report(label, draws, truth):
    lo, hi = np.quantile(draws, [0.05, 0.95], axis=0)
    print(f"  {label:44s} coverage {np.mean((lo <= truth) & (truth <= hi)):.3f}, mean width {np.mean(hi - lo):5.2f}, "
          f"bias {draws.mean() - truth:+.2f}  ({draws.shape[1]} tests)")


print("coverage of the 90% interval for the effect on the share, in percentage points")
report("standard posterior (NUTS)", CONV_STD_NUTS, TRUTH_CONV)
report("standard posterior (Laplace)", CONV_STD, TRUTH_CONV)
report("BayesBag, stores (100 Laplace fits)", CONV_BAG, TRUTH_CONV)
idx = 1 - 2 * CONV_STD.var(axis=0) / CONV_BAG.var(axis=0)
print(f"  mismatch index over the tests: median {np.median(idx):.2f}, 10% to 90% [{np.quantile(idx, 0.1):.2f}, {np.quantile(idx, 0.9):.2f}]")
1,000 tests, standard and bagged posteriors by Laplace: 3.8 s
300 tests, standard posterior by NUTS: 7.8 s, 0 divergences
coverage of the 90% interval for the effect on the share, in percentage points
  standard posterior (NUTS)                    coverage 0.727, mean width 11.64, bias +0.14  (300 tests)
  standard posterior (Laplace)                 coverage 0.711, mean width 11.65, bias +0.02  (1000 tests)
  BayesBag, stores (100 Laplace fits)          coverage 0.944, mean width 20.92, bias +0.09  (1000 tests)
  mismatch index over the tests: median 0.37, 10% to 90% [0.17, 0.53]

On the bench test the two routes give the same bagged interval to within a tenth of a point, and on five further tests their interval ends differ by about 1% of the width at most, which is the Monte Carlo noise of 100 short runs. The cost is very different. One hundred NUTS refits take three to five seconds once the model is compiled, a few hundredths of a second each, which is what with_data buys: compiling the model 100 times would take minutes. One hundred Laplace fits take about a hundredth of a second. pymc_extras.fit_laplace agrees with NUTS on the slope and takes a tenth or two of a second per call once its functions are compiled (and a few seconds the first time on a machine that has not cached them), so 100 fits through it would cost more than the 100 short NUTS runs did here.

Because the Laplace route is so cheap, the coverage count over 1,000 tests uses it, and NUTS checks the standard posterior on 300 of them. The pooled model's 90% interval covers 71% by Laplace and 73% by NUTS on its 300 tests: with 80 baskets per store, store differences make the counts about 2.3 times as variable as a binomial allows. The bagged interval covers 94%. The median mismatch index is 0.37, the same warning as in world B, though on a single test it ranges from about 0.2 to 0.5, and the bench test gave 0.14 and 0.20 by the two routes.

Two limits belong here. The agreement of Laplace and NUTS is a property of this model, whose posterior is nearly Gaussian. For a posterior with skew, several modes or a boundary, the Laplace copies would each be wrong in the same direction and averaging 100 of them would not help. There NUTS refits are the honest route, and their cost is the cost of one fit times $B$. And a model that takes ten minutes to sample takes sixteen hours to bag. Huggins and Miller suggest one long run on the original data followed by short runs on the copies, started from its draws and using its tuned step size, which trims the warm-up and leaves the factor $B$.

The choice. Laplace for the copies when each posterior is close to Gaussian, with NUTS refits on a handful of copies as the check; NUTS refits throughout otherwise. Rejected: recompiling the model for every copy. What would change our mind: a mode that depends on the parameterisation, as in a hierarchy written non-centred, where Laplace is known to fail.

6 · Fix the model instead

Bagging is a repair applied from outside: it does not say what is wrong with the model. When we can name the problem, we can put it in the model.

Stores differ: say so

For the basket values the missing piece is a level per store, $u_j \sim \mathcal N(0, \sigma_u^2)$. It can be integrated out exactly: the mean of a store's $m$ baskets is then Gaussian around the line with variance $\sigma_u^2 + \sigma^2/m$, so the model still sees 40 rows and still samples in a fraction of a second. For the yes/no outcome the missing piece is overdispersion, and a beta-binomial likelihood supplies it. We fit each model to the bench test and then to 300 repeated tests, the store-effects model in world A as well, to see what the extra parameter costs when it is not needed.

rng = np.random.default_rng(RANDOM_SEED + 5)
with sb.track("store effects in the model (NUTS)"):
    hier_nuts = nutpie.compile_pymc_model(gaussian_model(M_BENCH, store_effects=True))
    idata_hier = nuts(hier_nuts, ybar=ybar_b, ssw=ssw_b)
draws = idata_hier.posterior["effect"].values
ESS_HIER = float(az.ess(draws))
print(f"world B, bench test, store effects in the model: {draws.mean():.2f}, 90% interval [{np.quantile(draws, 0.05):.2f}, "
      f"{np.quantile(draws, 0.95):.2f}]; sigma_u = {float(idata_hier.posterior['sigma_u'].mean()):.2f} (truth {SIGMA_U:.0f})"
      f"   (r_hat {float(az.rhat(draws)):.3f}, bulk ESS {ESS_HIER:.0f}, divergences {int(idata_hier.sample_stats['diverging'].sum())})")

NUTS_DRAWS = {}
t0 = time.time()
for w, models in (("B", ("pooled", "store effects")), ("A", ("store effects",))):
    stats_w = [dict(zip(("ybar", "ssw"), sufficient(y))) for y in simulate(w, M_BENCH, N_NUTS, rng)]
    print(f"world {w}, {N_NUTS} tests of bench size")
    for name in models:
        NUTS_DRAWS[w, name], div = refit_tests(pooled_nuts if name == "pooled" else hier_nuts, stats_w)
        report(f"{name} model (NUTS), {div} divergences", NUTS_DRAWS[w, name], TRUTH[w])
print(f"{3 * N_NUTS} NUTS refits: {time.time() - t0:.0f} s")

with sbc.track("overdispersion in the model: beta-binomial (NUTS)"):
    bb_nuts = nutpie.compile_pymc_model(conversion_model(overdispersed=True))
    idata_bb = nuts(bb_nuts, k=k_bench)
draws = idata_bb.posterior["effect"].values
ESS_BB = float(az.ess(draws))
print(f"\nyes/no outcome, bench test, beta-binomial: {draws.mean():.2f}, 90% interval [{np.quantile(draws, 0.05):.2f}, "
      f"{np.quantile(draws, 0.95):.2f}]; precision, posterior median {float(np.median(idata_bb.posterior['phi'].values)):.0f} (truth {PHI:.0f})"
      f"   (r_hat {float(az.rhat(draws)):.3f}, bulk ESS {ESS_BB:.0f}, divergences {int(idata_bb.sample_stats['diverging'].sum())})")
CONV_BB, div = refit_tests(bb_nuts, [{"k": k} for k in K_TESTS[:N_NUTS]])
print(f"yes/no outcome, {N_NUTS} tests ({div} divergences)")
report("beta-binomial (NUTS)", CONV_BB, TRUTH_CONV)
world B, bench test, store effects in the model: 13.14, 90% interval [9.24, 17.00]; sigma_u = 3.13 (truth 3)   (r_hat 1.002, bulk ESS 1857, divergences 0)
world B, 300 tests of bench size
  pooled model (NUTS), 0 divergences           coverage 0.567, mean width  3.76, bias +0.06  (300 tests)
  store effects model (NUTS), 0 divergences    coverage 0.897, mean width  7.74, bias +0.06  (300 tests)
world A, 300 tests of bench size
  store effects model (NUTS), 0 divergences    coverage 0.930, mean width  4.00, bias -0.02  (300 tests)
900 NUTS refits: 23 s
yes/no outcome, bench test, beta-binomial: 15.01, 90% interval [7.67, 22.23]; precision, posterior median 152 (truth 60)   (r_hat 1.000, bulk ESS 1458, divergences 0)
yes/no outcome, 300 tests (0 divergences)
  beta-binomial (NUTS)                         coverage 0.880, mean width 17.48, bias -0.06  (300 tests)

In world B the model with store effects covers 90% of the time with an interval of \$7.70, against \$8.40 for the bagged one. The pooled model sampled by NUTS covers 57% on these 300 tests, which agrees with the 61% of the closed form on 1,000 within the noise of 300. In world A, where there are no store effects to find, the richer model costs little: its interval is 9% wider than the pooled one and covers 93%. The beta-binomial does the same for the yes/no outcome, 88% with an interval of 17.5 points against 20.9 for the bagged one. So when the problem has a name, the named fix gives calibrated intervals without surplus width, and it also explains the data: the posterior of $\sigma_u$ says how much stores differ (\$3.10 on the bench test, against a true \$3), which a wider interval never will. The beta-binomial's precision is a caution in the other direction. Forty stores determine it poorly (a posterior median of about 150 on the bench test, against a true 60), and the interval for the effect is close to calibrated all the same.

It is worth being exact about why the fix is narrower. The bagged posterior carries the model's variance plus the bootstrap's, and only the second was needed. The tuned bootstrap of part 4 removes the surplus and ends up a little narrower than the store-effects model, with the same coverage.

The response flattens: look at the residuals

For world C the index was silent and bagging did not help. The check that does see it is the most ordinary one: average the residuals of the fitted line at each depth.

fig, axes = plt.subplots(1, 2, figsize=(13, 3.9))
ax = axes[0]
depths = np.unique(DEPTH)
for w, colour, shift in (("A", BLUE, -0.5), ("C", RED, 0.5)):
    y = BENCH[w]
    fit = np.polyfit(np.repeat(DEPTH, M_BENCH), y.ravel(), 1)
    res = y.mean(axis=1) - np.polyval(fit, DEPTH)
    mean = np.array([res[DEPTH == d].mean() for d in depths])
    se = np.array([y[DEPTH == d].std() / np.sqrt((DEPTH == d).sum() * M_BENCH) for d in depths])
    ax.errorbar(depths + shift, mean, yerr=1.645 * se, fmt="o", ms=5, color=colour, capsize=3, lw=1.3,
                label=f"world {w}: {WORLDS[w]}")
    print(f"world {w}, bench test, mean residual of the line by depth: " + ", ".join(f"{d:.0f}%: {v:+.2f}" for d, v in zip(depths, mean))
          + f"   (standard error {se.mean():.2f})")
ax.axhline(0, color=MUTED, lw=1, ls="--")
ax.set_xlabel("discount depth (%)")
ax.set_ylabel("mean residual of the fitted line (\\$)")
ax.set_title("Residuals by depth, bench test (bars: 90% intervals)", loc="left", fontsize=10)
ax.legend(frameon=False, fontsize=8)
tidy(ax)

ax = axes[1]
quad = pd.DataFrame({
    "the line": {J * m: cover(STUDY["C", m]["std"], TRUTH["C"]) for m in M_GRID},
    "the line, bagged over stores": {J * m: cover(STUDY["C", m]["stores"], TRUTH["C"]) for m in M_GRID},
    "a quadratic": {J * m: cover(STUDY["C", m]["quad"], TRUTH["C"]) for m in M_GRID},
    "a quadratic, bagged over stores": {J * m: cover(STUDY["C", m]["quad_stores"], TRUTH["C"]) for m in M_GRID},
})
for (name, col), colour, ls in zip(quad.items(), (INK, ORANGE, GREEN, GREEN), ("-", "-", "-", "--")):
    ax.plot(col.index, col.to_numpy(), marker="o", ms=4.5, color=colour, lw=1.6, ls=ls, label=name)
ax.axhline(CI, color=MUTED, lw=1, ls="--")
ax.set_xscale("log")
ax.set_xticks(n_grid, [f"{n:,}" for n in n_grid], fontsize=8)
ax.minorticks_off()
ax.set_ylim(-0.03, 1.03)
ax.set_xlabel("transactions in the test")
ax.set_ylabel("coverage of the 90% interval")
ax.set_title("World C: coverage for the effect at 30%", loc="left", fontsize=10)
ax.legend(frameon=False, fontsize=8, loc="upper right")
tidy(ax)
quad["width, the line"] = [np.mean(STUDY["C", m]["std"][1] - STUDY["C", m]["std"][0]) for m in M_GRID]
quad["width, a quadratic"] = [np.mean(STUDY["C", m]["quad"][1] - STUDY["C", m]["quad"][0]) for m in M_GRID]
quad["bias, a quadratic"] = [np.mean(STUDY["C", m]["quad"].mean(axis=0)) - TRUTH["C"] for m in M_GRID]
print("\nworld C, coverage of the 90% interval for the effect at 30%, by transactions in the test")
print(quad.round(3).to_string())
curve = pd.DataFrame({f"world {w}": {J * m: 1 - cover(STUDY[w, m]["curve"], 0.0) for m in M_GRID} for w in ("A", "C")})
print("\nshare of tests in which the 90% interval of the quadratic coefficient excludes zero")
print(curve.round(3).T.to_string())
print("world A, a quadratic: coverage", {J * m: round(cover(STUDY["A", m]["quad"], TRUTH["A"]), 3) for m in M_GRID},
      "width", {J * m: round(float(np.mean(STUDY["A", m]["quad"][1] - STUDY["A", m]["quad"][0])), 1) for m in M_GRID})
world A, bench test, mean residual of the line by depth: 0%: +0.97, 5%: -1.46, 10%: +0.17, 15%: +0.15, 20%: +0.17   (standard error 0.59)
world C, bench test, mean residual of the line by depth: 0%: -1.80, 5%: +0.82, 10%: +2.36, 15%: +0.02, 20%: -1.40   (standard error 0.60)

world C, coverage of the 90% interval for the effect at 30%, by transactions in the test
       the line  the line, bagged over stores  a quadratic  a quadratic, bagged over stores  width, the line  width, a quadratic  bias, a quadratic
200       0.732                          0.91        0.876                            0.965             14.9                  29              -3.08
800       0.362                         0.658        0.814                            0.934             7.41                14.5              -3.18
3200      0.011                           0.1        0.548                             0.79             3.71                7.26              -3.31
12800         0                             0        0.098                            0.279             1.85                3.63              -3.21
51200         0                             0            0                            0.001            0.928                1.82              -3.25

share of tests in which the 90% interval of the quadratic coefficient excludes zero
         200    800    3200   12800  51200
world A  0.104  0.091  0.095  0.116  0.104
world C  0.258   0.66  0.993      1      1
world A, a quadratic: coverage {200: 0.902, 800: 0.895, 3200: 0.908, 12800: 0.886, 51200: 0.897} width {200: 29.0, 800: 14.5, 3200: 7.3, 12800: 3.6, 51200: 1.8}
Figure

The left panel is one dataset per world, and it shows why one dataset is thin evidence: in world C the residuals bend the way a saturating curve would (low at both ends, high in the middle), and in world A, where the line is true, one depth happens to sit two and a half standard errors low. The count over 1,000 tests is the fair version. A quadratic term whose 90% interval excludes zero turns up in 10% of the tests in world A, as it must, and in world C in 26% of the tests at 200 transactions, 66% at 800, 99% at the bench size and in every one beyond. Compare the mismatch index of part 4, which at the bench size was still inside its noise. A check aimed at the mean finds a wrong mean long before a check built from spreads does.

Finding the curvature is not the same as fixing the answer, and the right panel is the failure of this section. Adding a quadratic term does not make the model right. A parabola fitted to a saturating curve turns over after 20%, so it undershoots at 30% by about \$3.20, where the line overshot by \$4.50. Its interval is twice as wide, because it extrapolates a curvature, and that keeps its coverage up for a while: 88% at 200 transactions, 55% at the bench size, 10% at 12,800, nil at 51,200. In world A the same extra width is pure cost, an interval twice as wide for the same 90%. Bagging the quadratic adds width and no direction (79% at the bench size, 28% at 12,800). No model fitted to depths of 0 to 20% knows what happens at 30%, and the two candidates bracket the truth from either side. The real fix for world C is in the design: put some stores at 30%.

The choice. Put the named problem in the model when it has a name: store effects for world B, overdispersion for the yes/no outcome. Rejected: a quadratic term as a cure for world C (it changes the sign of the error), and bagging as a substitute for looking at residuals. What would change our mind: a model too awkward to extend, or a mismatch we can detect and cannot name. That is where the bagged posterior over the right unit is the honest fallback.

7 · The scoreboard

Every method for the basket question now has the same numbers on the tests of world B at the bench size: the error of its estimate, the coverage and mean width of its 90% interval, and what one analysis costs. Time and memory are measured on the bench test. The closed-form rows are scored on 1,000 tests (200 for the transaction bootstrap) and the NUTS rows on 300, compilation included in their time. One row is new. To see what the $B$ fits would cost on this model without the closed form, we run them with NUTS on the bench test, 100 refits of the compiled pooled model with store weights, and compare the interval with the closed-form one on the same weights. Its coverage is not measured: that would take 100 fits for each of several hundred tests, and the posterior is the same as in the row above it. A second, smaller board does the same for the yes/no outcome.

rng = np.random.default_rng(RANDOM_SEED + 6)
with sb.track("BayesBag, stores, tuned size (200 closed forms)"):
    size_bench = tuned_size(np.array([v_std]), spreads(*bag_stores(yb, B, rng))[0])
    tuned_bench = mixture_draws(*bag_stores(yb, B, rng, size=size_bench), 20000, rng)[:, 0]
w_b = store_weights(B, rng)
with sb.track("BayesBag, stores resampled (100 NUTS refits)"):
    bag_gauss_nuts = nuts_bag(pooled_nuts, w_b, ybar=ybar_b, ssw=ssw_b)
s_b, q_b = store_sums(BENCH["B"])
same = mixture_draws(*(v[None] for v in effect_posterior(M_BENCH * w_b, w_b * s_b, w_b @ q_b)), 20000, rng)[:, 0]
print(f"world B, bench test, tuned size ({int(size_bench[0])} stores per copy): 90% interval "
      f"[{np.quantile(tuned_bench, 0.05):.2f}, {np.quantile(tuned_bench, 0.95):.2f}]")
print(f"world B, bench test, bagged over stores with the same 100 weight vectors: NUTS refits "
      f"[{np.quantile(bag_gauss_nuts, 0.05):.2f}, {np.quantile(bag_gauss_nuts, 0.95):.2f}], closed forms "
      f"[{np.quantile(same, 0.05):.2f}, {np.quantile(same, 0.95):.2f}]")

res = STUDY["B", M_BENCH]
few = {"effect": np.full(N_NUTS, TRUTH["B"])}
sb.score("standard posterior (closed form)", {"effect": res["draws_std"]})
sb.score("standard posterior (NUTS)", {"effect": NUTS_DRAWS["B", "pooled"]}, truth=few, ess=ESS_POOLED)
sb.score("BayesBag, transactions resampled (100 closed forms)", {"effect": res["draws_rows"]},
         truth={"effect": np.full(REPS_ROWS, TRUTH["B"])})
sb.score("BayesBag, stores resampled (100 closed forms)", {"effect": res["draws_stores"]})
sb.score("BayesBag, stores, tuned size (200 closed forms)", {"effect": res["draws_tuned"]})
sb.score("store effects in the model (NUTS)", {"effect": NUTS_DRAWS["B", "store effects"]}, truth=few, ess=ESS_HIER)
board = sb.table()
print("\nbasket value, world B, 3,200 transactions: effect of a 30% discount in dollars")
print(board.to_string())

few = {"effect": np.full(N_NUTS, TRUTH_CONV)}
sbc.score("standard posterior (NUTS)", {"effect": CONV_STD_NUTS}, truth=few, ess=ESS_CONV)
sbc.score("standard posterior (Laplace)", {"effect": CONV_STD})
sbc.score("BayesBag, stores (100 Laplace fits)", {"effect": CONV_BAG})
sbc.score("overdispersion in the model: beta-binomial (NUTS)", {"effect": CONV_BB}, truth=few, ess=ESS_BB)
board_conv = sbc.table()
print("\nyes/no outcome, stores differ, 3,200 transactions: effect of a 30% discount in percentage points")
print(board_conv.to_string())
world B, bench test, tuned size (54 stores per copy): 90% interval [9.20, 17.00]
world B, bench test, bagged over stores with the same 100 weight vectors: NUTS refits [8.31, 17.68], closed forms [8.26, 17.71]

basket value, world B, 3,200 transactions: effect of a 30% discount in dollars
                                                     seconds  peak_gb  added_gb      ess  ess_per_s  rmse  coverage  width
method                                                                                                                    
standard posterior (closed form)                    0.000728     0.33  4.92e-05      NaN        NaN  2.24     0.608   3.77
standard posterior (NUTS)                               2.55    0.469     0.139  1.6e+03        626  2.29     0.567   3.76
BayesBag, transactions resampled (100 closed forms)  0.00329    0.477    0.0078      NaN        NaN   2.3      0.74   5.29
BayesBag, stores resampled (100 closed forms)       0.000349    0.478  3.28e-05      NaN        NaN  2.25     0.932   8.37
store effects in the model (NUTS)                       1.19    0.606    0.0143 1.86e+03   1.55e+03  2.29     0.897   7.74
BayesBag, stores, tuned size (200 closed forms)      0.00123    0.625  1.64e-05      NaN        NaN  2.25     0.889   7.44
BayesBag, stores resampled (100 NUTS refits)            2.07    0.628   0.00303      NaN        NaN   NaN       NaN    NaN

yes/no outcome, stores differ, 3,200 transactions: effect of a 30% discount in percentage points
                                                   seconds  peak_gb  added_gb      ess  ess_per_s  rmse  coverage  width
method                                                                                                                  
standard posterior (NUTS)                            0.921    0.774    0.0123      920        998  5.38     0.727   11.6
BayesBag, stores (100 NUTS refits)                    2.12    0.775   0.00095      NaN        NaN   NaN       NaN    NaN
standard posterior (Laplace)                      0.000583    0.636  4.92e-05      NaN        NaN  5.34     0.711   11.7
BayesBag, stores (100 Laplace fits)                0.00729    0.636  6.55e-05      NaN        NaN  5.35     0.944   20.9
overdispersion in the model: beta-binomial (NUTS)     1.06    0.633    0.0128 1.46e+03   1.38e+03  5.28      0.88   17.5
sb.plot(columns=("seconds", "ess_per_s", "rmse", "coverage", "width"),
        highlight=["BayesBag, stores resampled (100 closed forms)", "store effects in the model (NUTS)"]);
Figure
sbc.plot(columns=("seconds", "ess_per_s", "rmse", "coverage", "width"),
         highlight=["BayesBag, stores (100 Laplace fits)", "overdispersion in the model: beta-binomial (NUTS)"]);
Figure

Read the first board by its coverage column, then its width, then its cost.

The error column is the same for every row, about \$2.2. All the methods share one estimate, the least-squares line: bagging leaves the centre alone, and with the same number of baskets in every store the store-effects model weights the stores equally too. Every difference between the rows is in the interval.

Coverage and width. The standard posterior covers 61% in closed form on 1,000 tests and 57% by NUTS on 300. The transaction bootstrap covers 74%: wider, and still wrong. The store bootstrap covers 93% with an interval of \$8.40. The tuned size brings that to 89% at \$7.40, and the model with store effects to 90% at \$7.70. The last two are where a method ought to be, and they get there from opposite directions, one by estimating the real variance from 40 stores without a model and one by modelling it.

Cost. A closed-form posterior takes a fraction of a millisecond, so 100 or 200 of them are still a few milliseconds. The 100 NUTS refits take about four seconds and give the same interval as the closed forms on the same weights, to within the noise of short chains. A single NUTS fit takes one to a few seconds, nearly all of it compilation, whether of the pooled model or of the one with store effects. So where the posterior has to be sampled, bagging costs about what fitting the better model costs, and it is not the cheap option its reputation suggests. Bagging is cheap in thinking time: it needs the unit to resample and nothing else. ESS per second is reported for the NUTS rows only. The bagged rows are independent draws from a mixture and no ESS is claimed for them.

The second board repeats the pattern for the yes/no outcome: 71 to 73% for the pooled model, 94% for the bagged one, 88% for the beta-binomial with an interval a sixth narrower.

8 · Which of two models?

Huggins and Miller's second paper is about choosing between models, and the problem there is sharper than the one about intervals. Give two models equal prior weight and the posterior probability of the first is $1 / (1 + e^{-\Delta})$, where $\Delta$ is the difference of their log marginal likelihoods. That difference is a sum over observations, so its chance fluctuation grows like $\sqrt N$. If the two models fit about equally well, the systematic part of $\Delta$ is small, the fluctuation takes over, and the probability lands near 0 or near 1 according to the luck of the sample. Their theorem for two equally good models says that as $N$ grows the posterior probability of the first becomes a coin flip between 0 and 1, where one would hope for one half. Bagging averages the probability over bootstrap copies, each with its own luck, and their result for the bagged probability is a uniform distribution between 0 and 1 for copies of the size of the data, and convergence to one half for copies that are smaller by a suitable power, for which they suggest $M = N^{0.95}$ as a default and $N^{0.75}$ when the models are clearly wrong.

Two thermometers

We first check this where we know the answer. A response depends on a quantity nobody observes, and there are two noisy measurements of it, two thermometers. Model 1 regresses the response on the first, model 2 on the second. Both are wrong, since the response is curved in the hidden quantity. In one scenario the thermometers are equally noisy, so neither model is better and an honest probability is one half. In the other the second thermometer is a little noisier, so model 1 is truly better, and a method should not be sure of model 2. Marginal likelihoods are in closed form for the conjugate regression (we take Huggins and Miller's prior, $\lambda = 1$, $a_0 = 2$, $b_0 = 1$, on standardised columns), so each bagged probability is an average of 100 exact ones.

def log_marginal(M, cols, n, lam=1.0, a0=2.0, b0=1.0):
    """Log marginal likelihood of the conjugate regression on columns `cols`, from weighted moment matrices
    M (..., q, q) of the columns of the data with the response last, and the number of rows n (...)."""
    cols = list(cols)
    G = M[..., cols, :][..., :, cols] + lam * np.eye(len(cols))
    g = M[..., cols, -1]
    a_n = a0 + n / 2
    b_n = b0 + 0.5 * (M[..., -1, -1] - (g * np.linalg.solve(G, g[..., None])[..., 0]).sum(-1))
    return (-n / 2 * np.log(2 * np.pi) + len(cols) / 2 * np.log(lam) - 0.5 * np.linalg.slogdet(G)[1]
            + a0 * np.log(b0) - a_n * np.log(b_n) + special.gammaln(a_n) - special.gammaln(a0))


def prob_first(Z, W, cols1, cols2):
    """Posterior probability of model 1 against model 2 at equal prior odds, for each weight vector in W (..., n)."""
    q = Z.shape[1]
    products = (Z[:, :, None] * Z[:, None, :]).reshape(len(Z), q * q)
    M = (W @ products).reshape(W.shape[:-1] + (q, q))
    n = W.sum(-1)
    return special.expit(log_marginal(M, cols1, n) - log_marginal(M, cols2, n))


def resample_counts(n_units, size, B, rng):
    """How often each of n_units is drawn in each of B bootstrap copies of `size` units: (B, n_units)."""
    idx = rng.integers(0, n_units, (B, size)) + n_units * np.arange(B)[:, None]
    return np.bincount(idx.ravel(), minlength=B * n_units).reshape(B, n_units).astype(float)


def standardise(a):
    a = np.asarray(a, dtype=float)
    return (a - a.mean()) / a.std()


def thermometer_test(n, noise, rng):
    hidden = rng.normal(size=n)
    readings = [hidden + s * rng.normal(size=n) for s in noise]
    response = hidden + 0.4 * (hidden**2 - 1) + rng.normal(size=n)
    return np.column_stack([np.ones(n)] + [standardise(c) for c in (*readings, response)])


SCENARIOS = {"equally good": (0.6, 0.6), "model 1 is better": (0.6, 0.75)}
SIZES, REPS_T = (250, 1000, 4000), 300
CHOICE = ("standard", "bagged, copies of N", "bagged, copies of N^0.75")
rng = np.random.default_rng(RANDOM_SEED + 7)
t0 = time.time()
PROB = {}
for scenario, noise in SCENARIOS.items():
    for n in SIZES:
        out = np.empty((REPS_T, 3))
        for r in range(REPS_T):
            Z = thermometer_test(n, noise, rng)
            out[r, 0] = prob_first(Z, np.ones((1, n)), [0, 1], [0, 2])[0]
            out[r, 1] = prob_first(Z, resample_counts(n, n, B, rng), [0, 1], [0, 2]).mean()
            out[r, 2] = prob_first(Z, resample_counts(n, int(round(n**0.75)), B, rng), [0, 1], [0, 2]).mean()
        PROB[scenario, n] = out
print(f"{len(PROB) * REPS_T:,} simulated datasets, {time.time() - t0:.0f} s")
rows = []
for (scenario, n), out in PROB.items():
    for k, name in enumerate(CHOICE):
        rows.append({"scenario": scenario, "rows": n, "method": name, "median P(model 1)": np.median(out[:, k]),
                     "at least 95% sure of one model": np.mean((out[:, k] < 0.05) | (out[:, k] > 0.95)),
                     "at least 95% sure of model 2": np.mean(out[:, k] < 0.05)})
THERMO = pd.DataFrame(rows).set_index(["scenario", "rows", "method"])
print(THERMO.round(3).to_string())

fig, axes = plt.subplots(2, 3, figsize=(13, 5.6), sharex=True, sharey=True)
for i, scenario in enumerate(SCENARIOS):
    for k, (ax, name) in enumerate(zip(axes[i], CHOICE)):
        ax.hist(PROB[scenario, SIZES[-1]][:, k], bins=np.linspace(0, 1, 21), color=(INK, ORANGE, VIOLET)[k], alpha=0.85)
        ax.set_title(f"{scenario}: {name}", loc="left", fontsize=9.5)
        tidy(ax)
    axes[i, 0].set_ylabel(f"datasets (of {REPS_T})")
for ax in axes[1]:
    ax.set_xlabel(f"probability given to model 1 ({SIZES[-1]:,} rows)");
1,800 simulated datasets, 3 s
                                                 median P(model 1)  at least 95% sure of one model  at least 95% sure of model 2
scenario          rows method                                                                                                   
equally good      250  standard                              0.671                           0.707                         0.317
                       bagged, copies of N                   0.548                           0.127                         0.067
                       bagged, copies of N^0.75              0.514                            0.01                         0.007
                  1000 standard                              0.341                           0.843                          0.45
                       bagged, copies of N                   0.474                            0.14                          0.07
                       bagged, copies of N^0.75              0.499                               0                             0
                  4000 standard                              0.923                            0.96                          0.47
                       bagged, copies of N                   0.518                           0.113                         0.043
                       bagged, copies of N^0.75              0.505                               0                             0
model 1 is better 250  standard                              0.998                           0.777                         0.083
                       bagged, copies of N                    0.78                            0.23                         0.003
                       bagged, copies of N^0.75              0.649                           0.003                             0
                  1000 standard                                  1                           0.957                         0.017
                       bagged, copies of N                   0.978                           0.617                             0
                       bagged, copies of N^0.75              0.789                           0.037                             0
                  4000 standard                                  1                               1                             0
                       bagged, copies of N                       1                           0.967                             0
                       bagged, copies of N^0.75              0.906                           0.223                             0
Figure

The histograms are for 4,000 rows. With two equally good models (top row) the standard posterior is at least 95% sure of one of them in 96% of the datasets, up from 71% at 250 rows, and which one is a coin flip: the theorem's picture, and it gets worse with more data. The bagged probability with copies of the size of the data is spread almost evenly between 0 and 1. It is that sure in 11% of datasets, close to the 10% of a uniform distribution, so it is rarely confident and still not informative. With smaller copies it piles up around one half, which is the honest answer here.

The second scenario shows both sides of the trade. At 250 rows the standard posterior is at least 95% sure of the worse model in 8% of datasets, the bagged one in 0.3%, the small copies never. At 4,000 rows the difference between the models is plain: the standard posterior and the bagged one with full-size copies are sure of model 1 nearly always, and the small copies reach 95% in only 22% of datasets (bottom right). Bagged model probabilities trade decisiveness for reproducibility, and the copy size sets the rate of exchange.

The bikes: measured temperature or how it feels?

Now the real case. Capital Bikeshare's daily rental counts for 2011 and 2012 come with two temperature columns, the measured temperature and the "feels-like" temperature, and the two are almost the same variable. Which of them drives demand is a natural question for anyone building a forecast, and a Bayesian would answer it with a posterior model probability. We compare two linear regressions of the standardised daily count that share year, working day, weather, humidity, wind and season, and differ in the temperature column.

data.describe("bike_day")
bike = data.load("bike_day")
base = [np.ones(len(bike)), bike["yr"], bike["workingday"], standardise(bike["hum"]), standardise(bike["windspeed"])]
base += [(bike["weathersit"] == k).astype(float) for k in (2, 3)] + [(bike["season"] == k).astype(float) for k in (2, 3, 4)]
temp, feel = standardise(bike["temp"]), standardise(bike["atemp"])
ZB = np.column_stack(base + [temp, feel, temp**2, feel**2, standardise(bike["cnt"])])
N_BASE = len(base)
PAIRS = {"a straight line in temperature": ([*range(N_BASE), N_BASE], [*range(N_BASE), N_BASE + 1]),
         "with a squared term": ([*range(N_BASE), N_BASE, N_BASE + 2], [*range(N_BASE), N_BASE + 1, N_BASE + 3])}
week = (bike["instant"].to_numpy() - 1) // 7
n_days, n_weeks = len(bike), week.max() + 1
print(f"\n{n_days} days in {n_weeks} weeks; correlation between the two temperature columns: {np.corrcoef(temp, feel)[0, 1]:.3f}")


def bagged_probability(mask, unit, cols, rng, power=1.0):
    """Bagged P(model 1) on the days in `mask`, resampling the distinct values of `unit` among them."""
    units, position = np.unique(unit[mask], return_inverse=True)
    counts = resample_counts(len(units), int(round(len(units) ** power)), B, rng)
    W = np.zeros((B, len(mask)))
    W[:, mask] = counts[:, position]
    return prob_first(ZB, W, *cols).mean()


rng = np.random.default_rng(RANDOM_SEED + 8)
everything, day = np.ones(n_days, dtype=bool), np.arange(n_days)
BIKE_METHODS = ("standard", "bagged over days", "bagged over weeks", "bagged over days, copies of N^0.75")
N_SPLITS = 200
rows, HALVES = [], {}
t0 = time.time()
for pair, cols in PAIRS.items():
    def all_methods(mask):
        return [prob_first(ZB, mask[None].astype(float), *cols)[0], bagged_probability(mask, day, cols, rng),
                bagged_probability(mask, week, cols, rng), bagged_probability(mask, day, cols, rng, power=0.75)]
    full = all_methods(everything)
    halves = np.empty((N_SPLITS, 2, len(BIKE_METHODS)))
    for i in range(N_SPLITS):
        in_a = (rng.permutation(n_weeks) < n_weeks // 2)[week]          # a random half of the weeks
        halves[i] = [all_methods(in_a), all_methods(~in_a)]
    HALVES[pair] = halves
    for k, name in enumerate(BIKE_METHODS):
        pa, pb = halves[:, 0, k], halves[:, 1, k]
        rows.append({"models": pair, "method": name, "P(measured), all the data": full[k],
                     "halves at least 95% sure": np.mean((halves[..., k] < 0.05) | (halves[..., k] > 0.95)),
                     "splits where the halves contradict": np.mean(((pa > 0.8) & (pb < 0.2)) | ((pa < 0.2) & (pb > 0.8))),
                     "mean gap between halves": np.mean(np.abs(pa - pb))})
BIKES = pd.DataFrame(rows).set_index(["models", "method"])
print(f"{N_SPLITS} random splits of the weeks into two halves, {time.time() - t0:.0f} s")
print(BIKES.round(3).to_string())

fig, axes = plt.subplots(1, 3, figsize=(13, 4.3), sharex=True, sharey=True)
panels = (("a straight line in temperature", 0, INK, "standard posterior"),
          ("a straight line in temperature", 2, ORANGE, "bagged over weeks"),
          ("with a squared term", 0, INK, "standard posterior"))
for ax, (pair, k, colour, name) in zip(axes, panels):
    ax.fill_between([0, 0.2], 0.8, 1, color=RED, alpha=0.12, lw=0)
    ax.fill_between([0.8, 1], 0, 0.2, color=RED, alpha=0.12, lw=0)
    ax.scatter(HALVES[pair][:, 0, k], HALVES[pair][:, 1, k], s=16, color=colour, alpha=0.6)
    ax.plot([0, 1], [0, 1], color=MUTED, lw=0.8, ls="--")
    ax.set_title(f"{pair}:\n{name}", loc="left", fontsize=9.5)
    ax.set_xlabel("P(measured temperature), one half of the weeks")
    ax.set_xlim(-0.03, 1.03), ax.set_ylim(-0.03, 1.03)
    tidy(ax, grid=None)
axes[0].set_ylabel("P(measured temperature), the other half")
axes[0].text(0.02, 0.9, "the halves\ncontradict", fontsize=8, color=RED, va="center");
bike_day: Daily rental counts 2011-2012 with weather and calendar covariates.
  source: Fanaee-T & Gama (2013), Capital Bikeshare (Washington DC), UCI ML Repository.
  url:    https://archive.ics.uci.edu/static/public/275/bike+sharing+dataset.zip

731 days in 105 weeks; correlation between the two temperature columns: 0.992
200 random splits of the weeks into two halves, 2 s
                                                                   P(measured), all the data  halves at least 95% sure  splits where the halves contradict  mean gap between halves
models                         method                                                                                                                                              
a straight line in temperature standard                                                0.982                     0.455                                0.35                    0.596
                               bagged over days                                        0.677                     0.025                               0.195                    0.402
                               bagged over weeks                                        0.69                     0.015                               0.155                    0.367
                               bagged over days, copies of N^0.75                      0.561                         0                                   0                    0.148
with a squared term            standard                                                    1                      0.98                                   0                    0.012
                               bagged over days                                            1                     0.782                                   0                    0.049
                               bagged over weeks                                           1                     0.752                                   0                    0.053
                               bagged over days, copies of N^0.75                      0.861                         0                                   0                     0.09
Figure

On all the data the standard posterior gives the measured temperature a probability of 0.98. That looks like a finding. The bagged probability is 0.68, whether days or weeks are resampled, and 0.56 with smaller copies: the bootstrap copies do not agree on which column is better.

The check with a known answer is whether two analysts with different halves of the data would agree. We split the 105 weeks at random into two halves, 200 times, and compute every probability on each half. With the straight-line models the standard posterior is at least 95% sure of one column in 46% of the halves, and in 35% of the splits the two halves contradict each other, one giving the measured temperature more than 0.8 and the other less than 0.2 (the shaded corners of the left panel). The bagged probability is that sure in 2% of the halves and contradicts itself in 16 to 20% of the splits, and with the smaller copies never. One caution about this check: the two halves of one dataset are not independent samples. If one half happens to favour a column, the other is left with the days that favour it less, so contradictions are more frequent than they would be between two fresh years. The falling arc of the points in the first two panels is that dependence. It affects every method alike, and the comparison between them stands.

So the standard probability of 0.98 was the sample's luck, as in the thermometer simulation. The resampling unit matters little here, days or weeks, because neighbouring days do not share much of what separates the two columns.

The last panel belongs to the theme of part 6. The straight-line models are both wrong in the same way: demand rises with temperature and falls again on hot days. Add a squared term to each and the question changes character. The measured temperature now wins with probability 1.00 on all the data and in nearly every half, no split contradicts itself, and the bagged probability agrees. The first comparison was unstable because two wrong models were being ranked by how they were wrong. With a mean function that fits, the same data answer the question, and here the small copies show their cost: they still say only 0.86.

The choice. Report the bagged model probability next to the standard one, and distrust a confident standard probability that the bagged one does not share. Rejected: small bootstrap copies as a default, which gave stable answers and could not recognise a real difference at this sample size. What would change our mind: many models instead of two, where Huggins and Miller's recommendation of $N^{0.95}$ was developed and where instability is the rule.

9 · Which method for which failure

The figure collects what was measured. The upper block is about intervals: each row is a way the pooled model can relate to the truth, each column a method, and each cell the coverage of the 90% interval at the bench size of 3,200 transactions. The lower block is about choosing between two models.

def cover_draws(draws, truth):
    return cover(np.quantile(draws, [0.05, 0.95], axis=0), truth)


def bench_cov(w, k):
    return COV.loc[(w, J * M_BENCH), f"coverage: {METHODS[k]}"]


COLUMNS = ["standard\nposterior", "BayesBag,\ntransactions", "BayesBag,\nstores", "BayesBag, stores,\ntuned size", "the problem,\nnamed"]
ROWS = [
    ("the model is right\n(world A)", [bench_cov("A", k) for k in METHODS] + [cover_draws(NUTS_DRAWS["A", "store effects"], TRUTH["A"])],
     "store effects", "the standard posterior:\nbagging only costs width"),
    ("baskets of one store move together\n(world B)", [bench_cov("B", k) for k in METHODS] + [cover_draws(NUTS_DRAWS["B", "store effects"], TRUTH["B"])],
     "store effects", "store effects in the model,\nor BayesBag over stores"),
    ("the model aims at the wrong value\n(world C)", [bench_cov("C", k) for k in METHODS] + [cover(STUDY["C", M_BENCH]["quad"], TRUTH["C"])],
     "a quadratic term", "no interval here: look at\nresiduals, change the design"),
    ("no closed form, stores differ\n(yes/no outcome)", [cover_draws(CONV_STD, TRUTH_CONV), np.nan, cover_draws(CONV_BAG, TRUTH_CONV), np.nan,
                                                         cover_draws(CONV_BB, TRUTH_CONV)],
     "beta-binomial", "overdispersion in the model, or\nBayesBag by Laplace or NUTS refits"),
]


def shade(c):
    if np.isnan(c):
        return "#f1f0ec"
    if c < 0.80:
        return "#f6c6c1"
    if c < 0.87:
        return "#fbe3b3"
    return "#c9e9d6" if c <= 0.93 else "#cde2fb"


fig, (ax, ax2) = plt.subplots(2, 1, figsize=(13.5, 8.2), gridspec_kw={"height_ratios": [4.3, 2.3]})
for j, name in enumerate(COLUMNS):
    ax.text(j + 0.5, len(ROWS) + 0.12, name, ha="center", va="bottom", fontsize=9, fontweight="bold")
ax.text(len(COLUMNS) + 0.1, len(ROWS) + 0.12, "reach for", ha="left", va="bottom", fontsize=9, fontweight="bold")
for i, (label, values, fix, advice) in enumerate(ROWS):
    y0 = len(ROWS) - 1 - i
    ax.text(-0.08, y0 + 0.5, label, ha="right", va="center", fontsize=9)
    for j, c in enumerate(values):
        ax.add_patch(plt.Rectangle((j + 0.03, y0 + 0.05), 0.94, 0.9, fc=shade(c), ec="white"))
        ax.text(j + 0.5, y0 + (0.57 if j == 4 else 0.5), "not run" if np.isnan(c) else f"{c:.1%}" if 0.99 < c < 1 else f"{c:.0%}", ha="center", va="center",
                fontsize=9 if np.isnan(c) else 13, color=MUTED if np.isnan(c) else INK)
        if j == 4:
            ax.text(j + 0.5, y0 + 0.22, fix, ha="center", va="center", fontsize=8, color=INK)
    ax.text(len(COLUMNS) + 0.1, y0 + 0.5, advice, ha="left", va="center", fontsize=9)
for k, (colour, text) in enumerate((("#f6c6c1", "under 80%"), ("#fbe3b3", "80 to 87%"), ("#c9e9d6", "87 to 93%: as stated"),
                                    ("#cde2fb", "over 93%: wider than needed"))):
    ax.add_patch(plt.Rectangle((0.03 + 1.45 * k, -0.42), 0.22, 0.22, fc=colour, ec="white", clip_on=False))
    ax.text(0.3 + 1.45 * k, -0.31, text, fontsize=8, va="center")
ax.set_xlim(-0.1, len(COLUMNS) + 2.4)
ax.set_ylim(-0.5, len(ROWS) + 0.6)
ax.axis("off")
ax.set_title("Coverage of the 90% interval at 3,200 transactions, 40 stores", loc="left", fontsize=10.5)

big = SIZES[-1]
line = "a straight line in temperature"
CHOICE_ROWS = [
    (f"two equally good models\n(thermometers, {big:,} rows)", "at least 95% sure of one of them",
     [THERMO.loc[("equally good", big, name), "at least 95% sure of one model"] for name in CHOICE]),
    ("a slightly better model\n(thermometers, 250 rows)", "at least 95% sure of the worse one",
     [THERMO.loc[("model 1 is better", 250, name), "at least 95% sure of model 2"] for name in CHOICE]),
    ("two temperature columns\n(bikes, straight lines)", "two halves of the data contradict each other",
     [BIKES.loc[(line, name), "splits where the halves contradict"] for name in ("standard", "bagged over days", "bagged over days, copies of N^0.75")]),
]
for j, name in enumerate(("standard\nmodel probability", "bagged,\ncopies of $N$", "bagged,\ncopies of $N^{0.75}$")):
    ax2.text(j + 0.5, len(CHOICE_ROWS) + 0.1, name, ha="center", va="bottom", fontsize=9, fontweight="bold")
ax2.text(3.1, len(CHOICE_ROWS) + 0.1, "what is counted", ha="left", va="bottom", fontsize=9, fontweight="bold")
for i, (label, what, values) in enumerate(CHOICE_ROWS):
    y0 = len(CHOICE_ROWS) - 1 - i
    ax2.text(-0.08, y0 + 0.5, label, ha="right", va="center", fontsize=9)
    for j, c in enumerate(values):
        ax2.add_patch(plt.Rectangle((j + 0.03, y0 + 0.06), 0.94, 0.88, fc="#f6c6c1" if c > 0.2 else "#fbe3b3" if c > 0.05 else "#c9e9d6", ec="white"))
        ax2.text(j + 0.5, y0 + 0.5, f"{c:.0%}", ha="center", va="center", fontsize=13)
    ax2.text(3.1, y0 + 0.5, f"share of analyses {what}" if i < 2 else f"share of splits in which {what}", ha="left", va="center", fontsize=9)
ax2.set_xlim(-0.1, len(COLUMNS) + 2.4)
ax2.set_ylim(-0.1, len(CHOICE_ROWS) + 0.6)
ax2.axis("off")
ax2.set_title("Choosing between two models: how often the answer is confident and unreliable", loc="left", fontsize=10.5)
print(pd.DataFrame([v for _, v, _, _ in ROWS], index=[r[0].replace("\n", " ") for r in ROWS],
                   columns=[c.replace("\n", " ") for c in COLUMNS]).round(3).to_string())
print(pd.DataFrame([v for _, _, v in CHOICE_ROWS], index=[r[0].replace("\n", " ") for r in CHOICE_ROWS],
                   columns=["standard", "bagged, N", "bagged, N^0.75"]).round(3).to_string())
print(f"\ntotal run time: {time.time() - T_START:.0f} s")
                                                standard posterior  BayesBag, transactions  BayesBag, stores  BayesBag, stores, tuned size  the problem, named
the model is right (world A)                                 0.906                   0.995             0.982                         0.888                0.93
baskets of one store move together (world B)                 0.609                    0.74             0.932                         0.889               0.897
the model aims at the wrong value (world C)                  0.011                    0.04               0.1                         0.034               0.548
no closed form, stores differ (yes/no outcome)               0.711                     NaN             0.944                           NaN                0.88
                                                    standard  bagged, N  bagged, N^0.75
two equally good models (thermometers, 4,000 rows)      0.96      0.113               0
a slightly better model (thermometers, 250 rows)       0.083      0.003               0
two temperature columns (bikes, straight lines)         0.35      0.195               0

total run time: 100 s
Figure

Read the upper block by rows. When the model is right, the standard posterior is the method and every bagged variant except the tuned one is wider than it needs to be. When units move together, the standard posterior and the bootstrap of the wrong unit fail together, and the three methods that know about stores, the store bootstrap, its tuned version and the store-effects model, all work, the bootstrap with some surplus. When the model aims at the wrong value, the whole row is red or nearly: no interval built around a wrong centre is repaired by widening it for long. And the yes/no outcome repeats the second row with the fits done by a sampler or by Laplace.

The lower block says the same about model probabilities: the standard one is often sure when it has no right to be, bagging removes most of that, and small copies remove all of it along with some of the ability to be sure when it is warranted.

In practice the order of work is this. Decide what the independently sampled unit is. Fit the model, bag it over that unit with 100 copies, and compare the two spreads. If the bagged variance is about twice the standard one, the model's width is not the problem, which is not the same as the model being right. If it is much more than twice, the standard posterior is too narrow: say what the model is missing and add it if you can, and report the bagged posterior if you cannot. In both cases look at the residuals, because nothing above protects against a model that is centred in the wrong place.

Summary

  • BayesBag is the average of the posteriors of bootstrap copies of the data. Its variance is the model's variance plus a bootstrap estimate of the real sampling variance. When the model is right the two are equal, so the bagged 90% interval is 1.4 times too wide and covers 97 to 98%. Limit: that surplus is the method's fixed price, paid in every world.
  • It repairs a wrong width, and only that. With store effects left out of the model, the estimate was unbiased and the standard interval's coverage fell from 87% at 200 transactions to 61% at 3,200 and 18% at 51,200, while the interval bagged over stores stayed between 89 and 98%. With a wrong mean function the estimate was off by \$4.50 at every size, and both intervals went to zero coverage, the bagged one a little later (10% against 1% at 3,200). Limit: which of the two cases you are in cannot be read off the posterior.
  • The unit you resample decides everything. Bagging over transactions when stores were the sampled unit covered 74% at 3,200 transactions and 45% at 12,800, hardly better than the standard posterior. Limit: with 40 stores the store bootstrap itself is slightly optimistic, which shows as 89% once the model's variance has become negligible.
  • The mismatch index detects one kind of trouble. It sat at 0 with a spread of 0.2 when the model was right, and reached 0.59 and then 0.85 as store effects came to dominate. It stayed at 0 when computed with the wrong unit, was indistinguishable from 0 while the trouble was small, and reacted to a wrong mean function only after coverage was gone. A quadratic term detected that case in 99% of tests at the size where the index was still inside its noise. Limit: an index near zero says the width is plausible, nothing more.
  • Tuning the bootstrap size removes the surplus. Drawing about 80 stores per copy when the model was right, and fewer as it failed, gave intervals of the right width and coverage of 87 to 89%. Limit: it trusts a variance estimated from 40 units and comes out a little short.
  • The cost is $B$ fits, and here that was small. One hundred closed-form posteriors took about a millisecond; one hundred nutpie refits of a compiled model took three to five seconds; one hundred Laplace fits of a logistic regression took a few milliseconds and matched the NUTS refits to 1% of the interval's width. Limit: Laplace matched because these posteriors are nearly Gaussian, and a model that samples in ten minutes still needs sixteen hours.
  • Fixing the model was better when the problem had a name. Store effects in the model gave 90% coverage with an interval 8% narrower than the bagged one, cost 9% in width where they were not needed, and estimated how much stores differ. The beta-binomial did the same for the yes/no outcome (88% against 94%, a sixth narrower). Limit: a quadratic term did not fix the extrapolation, it reversed the sign of its error.
  • Bagged model probabilities are less often sure and less often contradicted. For two equally good models the standard posterior was at least 95% sure of one in 96% of datasets of 4,000 rows, the bagged one in 11%. For the two temperature columns of the bike data the standard probability was 0.98, the bagged one 0.68, and two halves of the data contradicted each other in 35% of splits against 16 to 20%. A squared term made the comparison stable for every method. Limit: smaller copies never contradicted themselves and also could not confirm a real difference at this sample size.

Try it yourself

  1. Add stores instead of weeks. Change the study so that the number of transactions per store stays at 80 and the number of stores grows from 10 to 320. In world B the standard interval's coverage should stop falling and settle at one level. Work out that level from the ratio of the two variances before you run it, then check how the tuned bootstrap's shortfall changes with the number of stores.
  2. Give world C the right curve. Write the saturating model $\alpha + L\,(1 - e^{-d/\tau})$ in PyMC on the store means, compile it once with nutpie and refit it on 300 tests with with_data. Does its interval for the effect at 30% cover, and how wide is it compared with the line's and the quadratic's? Then add eight stores at 30% to the design and repeat for all three models.
  3. Bag the bikes by block length. Replace weeks by blocks of 2, 14 and 28 days in bagged_probability and watch the bagged probability of the measured temperature for the straight-line models. Then compute the mismatch index of the temperature coefficient with days and with weeks as the unit: does the unit matter more for the coefficient than it did for the model probability?