The question
A city wants to use cheap particle sensors next to its few reference monitors. Before a sensor is trusted it is tested twice. In a chamber held at a known concentration it is read 100 times, and the average reading tells us what the sensor shows at that level. Then it spends 100 days beside a reference monitor, and the slope of sensor reading on reference concentration is its sensitivity. A location and a regression: two of the simplest estimates there are.
The trouble is that some of the readings are not measurements of the thing we want. The electronics glitch. Somebody lights a cigarette near the inlet. A damp morning adds a little to every reading taken before ten. On the dirtiest days the sensor saturates and reports the same number whatever the air contains. Each of these is a second process that produces a share of the data, somewhere between a few percent and a fifth, and the analyst does not know which of them is at work, or how often. This is the contamination model of classical robust statistics (Huber 1964): a fraction $1 - \varepsilon$ of the readings comes from the model we wrote, and a fraction $\varepsilon$ from something else.
The series has met outliers before, and each time it gave them a model. D02 uses a Student-t likelihood, E39 gives each radiocarbon date a probability of being an outlier, E99 has a second component for radio signals that did not travel in a straight line, and E131 found the giants of a star cluster with a two-population mixture. This notebook asks what to do when you cannot, or would rather not, write that second model. E131 answered a related question with a power on the likelihood, which makes the posterior wider and leaves its centre where it was. Here the centre is the problem.
The candidate is a generalised posterior. Bissiri, Holmes and Walker (2016) showed that a prior can be updated coherently with any loss $\ell$ in place of the negative log-likelihood,
$$\pi_\ell(\theta \mid y) \;\propto\; \pi(\theta)\,\exp\Big\{-w \sum_{i=1}^n \ell(y_i, \theta)\Big\},$$
where $w$ is a learning rate that says how much one observation counts against the prior. With $\ell = -\log f$ and $w = 1$ this is Bayes' rule. We try two other losses. The first keeps the Gaussian model $f$ and changes the yardstick: instead of the Kullback-Leibler divergence, which the log-likelihood estimates, it uses the density power divergence of Basu, Harris, Hjort and Jones (1998), also called the beta-divergence. Ghosh and Basu (2016) proposed the posterior built on it, and Jewson, Smith and Holmes (2018) argued that it is a principled update of beliefs and not a pseudo-posterior. Its loss is bounded, so a reading far from the fit stops mattering, and it needs no description of where the far readings come from. The second is the oldest robust loss of all, Huber's, which is quadratic for small residuals and linear for large ones.
The lesson we expected to find: the beta-divergence posterior needs no model of the outliers, at the cost of a tuning constant and some efficiency on clean data. That sentence survives, and it leaves out most of what matters in practice. The loss has units, so the width of the interval depends on whether the readings are written in micrograms or milligrams. There are two tuning constants, not one. Contamination close to the bulk defeats every method here. And with leverage points the posterior has two modes, so the answer depends on where the sampler starts.
Everything is measured against a known answer. The chamber is held at a level where the sensor reads 10 on average, and the true slope of the calibration line is 2.
| part | question | tool |
|---|---|---|
| 1 | What does contamination do to the Gaussian posterior? | three kinds of bad readings, one bench dataset |
| 2 | How do the four alternatives discount a reading? | influence curves; the two losses, the closed-form integral |
| 3 | What do they say about the bench dataset? | six NUTS fits, two of them with a learning rate from a pilot estimate |
| 4 | Are the loss-based intervals honest? | exact posteriors on a grid, 1,000 clean datasets, three units |
| 5 | What does $\beta$ cost, and who chooses it? | efficiency and bias against $\beta$; the Hyvärinen score |
| 6 | What happens as the contamination grows? | estimate against contamination fraction, three kinds |
| 7 | And with leverage points? | a calibration line with a saturating sensor; where the chains start |
| 8 | Who wins, at what cost? | the scoreboard |
| 9 | Does it survive real gross errors? | Belgian telephone calls; the stars of CYG OB1 |
| 10 | Which method for which contamination? | a table of everything measured |
A word on what is computed how. The six posteriors of the bench dataset, every regression fit and
every fit to the real data are NUTS runs (nutpie), with the two losses written as pm.Potential.
For the repeated datasets of the location problem, the Gaussian posterior is in closed form, the
beta-divergence and Huber posteriors have one or two parameters and are computed exactly on a grid
(checked against NUTS on the bench), and the mixture and the Student-t are refitted by NUTS, with
one compiled model and the data swapped in. Pilot estimates are fixed-point iterations.
import os
for name in ("OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS"):
os.environ.setdefault(name, "1") # before NumPy: one BLAS thread per chain
import logging
import sys
import time
import warnings
import arviz as az
import matplotlib.pyplot as plt
import nutpie
import numpy as np
import pandas as pd
import pymc as pm
import pytensor.tensor as pt
from scipy import integrate, 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 = 133
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:.4g}")
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")
GAUSS, MIX, STUDENT, BD1, BDM, BDH, HUBER = (
"Gaussian", "contamination mixture", "Student-t", "beta-divergence, rate 1", "beta-divergence, rate matched",
"beta-divergence, beta by H-score", "Huber loss, rate matched")
COLOR = {GAUSS: ORANGE, MIX: GREEN, STUDENT: VIOLET, BD1: BLUE, BDM: BLUE, BDH: AQUA, HUBER: YELLOW}
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 · A chamber, a hundred readings, and three kinds of bad ones
In the chamber the sensor's readings scatter around 10 with a standard deviation of 1. A share $\varepsilon$ of them is replaced by a reading from another process. We simulate three, chosen because they ask different things of a method.
- Glitches (symmetric, far away). The reading is the true level plus noise ten times as large. On average the glitches are right, so they do not bias the mean; they make it noisy.
- A second source (one-sided, far away). The reading is 8 units too high: something else is being measured. These pull the mean up, by $8\varepsilon$.
- Humidity (one-sided, close to the bulk). The reading is 2.5 units too high. A third of these readings are within two standard deviations of 10, where ordinary readings are plentiful, so no method can tell them apart one by one.
The datasets share their random numbers: the dataset with 10% contamination is the clean dataset with a tenth of its readings replaced, and the one with 20% replaces those and as many again. The dataset we keep "on the bench" for single fits is the first one with a tenth of its readings from the second source (nine of them, as it turned out).
MU, SIGMA, N = 10.0, 1.0, 100
CI = 0.90
EPS = (0.0, 0.05, 0.10, 0.20)
KINDS = {"glitches": "glitches: symmetric, far", "second source": "second source: one-sided, far",
"humidity": "humidity: one-sided, close"}
REPS = 100 # datasets per setting when a method needs NUTS
REPS_EXACT = 1000 # datasets where every posterior involved is exact
def simulate_location(seed, reps, n=N):
"""Clean readings, the uniform numbers that decide which are replaced, and the replacements of each kind."""
rng = np.random.default_rng(seed)
clean = MU + SIGMA * rng.standard_normal((reps, n))
u = rng.random((reps, n))
other = {"glitches": MU + 10 * SIGMA * rng.standard_normal((reps, n)),
"second source": MU + 8 * SIGMA + SIGMA * rng.standard_normal((reps, n)),
"humidity": MU + 2.5 * SIGMA + SIGMA * rng.standard_normal((reps, n))}
return clean, u, other
def contaminate(world, kind, eps, reps=None):
"""The datasets of one setting, and the mask of replaced readings."""
clean, u, other = world
bad = u[:reps] < eps
return np.where(bad, other[kind][:reps], clean[:reps]), bad
WORLD = simulate_location([RANDOM_SEED, 1], REPS_EXACT)
BENCH_KIND, BENCH_EPS = "second source", 0.10
y_bench, bad_bench = (v[0] for v in contaminate(WORLD, BENCH_KIND, BENCH_EPS, 1))
fig, axes = plt.subplots(1, 3, figsize=(13, 3.5), sharey=True)
for ax, (kind, title) in zip(axes, KINDS.items()):
y, bad = (v[0] for v in contaminate(WORLD, kind, 0.10, 1))
bins = np.linspace(-12, 32, 67) if kind == "glitches" else np.linspace(6.5, 21, 59)
ax.hist(y[~bad], bins=bins, color=BLUE, alpha=0.7, label=f"from the sensor model ({(~bad).sum()})")
ax.hist(y[bad], bins=bins, color=RED, alpha=0.8, label=f"replaced ({bad.sum()})")
ax.axvline(MU, color=INK, lw=1.2, ls="--")
ax.axvline(y.mean(), color=ORANGE, lw=1.6)
ax.set_title(f"{title}\nmean {y.mean():.2f}, median {np.median(y):.2f}", loc="left", fontsize=10)
ax.set_xlabel("reading")
ax.legend(frameon=False, fontsize=8.5, loc="upper right")
tidy(ax)
axes[0].set_ylabel("readings")
print(f"bench dataset: {bad_bench.sum()} of {N} readings from the second source; mean {y_bench.mean():.3f}, "
f"median {np.median(y_bench):.3f}, mean of the {(~bad_bench).sum()} good readings {y_bench[~bad_bench].mean():.3f}");
bench dataset: 9 of 100 readings from the second source; mean 10.733, median 10.110, mean of the 91 good readings 10.063

One dataset of each kind at 10% contamination, the same clean readings in all three. The dashed line is the truth and the orange line the sample mean. In colour the bad readings are easy to see. The analyst has no colours: the glitches and the second source could be found by eye in a histogram, and the damp readings on the right could not.
The Gaussian model
The model everyone starts with is $y_i \sim \mathcal N(\mu, \sigma^2)$. With flat priors on $\mu$ and $\log\sigma$ its posterior for $\mu$ is a Student-t centred on the sample mean with scale $s/\sqrt n$, which we use whenever a Gaussian posterior is needed many times. (The models fitted by NUTS below use the weak proper priors $\mu \sim \mathcal N(0, 100)$ and $\sigma \sim \text{Half-Normal}(10)$; part 3 checks that the two agree.)
QUANTILES = (np.arange(1000) + 0.5) / 1000 # exact posteriors are stored as 1,000 evenly spaced quantiles
def robust_scale(e, axis=-1):
"""The median absolute deviation, scaled to estimate a Gaussian standard deviation."""
med = np.median(e, axis=axis, keepdims=True)
return 1.4826 * np.median(np.abs(e - med), axis=axis)
def gaussian_location(Y):
"""Posterior of mu under the Gaussian model, for each row of Y: quantile draws of shape (1000, rows)."""
n = Y.shape[-1]
return Y.mean(-1) + Y.std(-1, ddof=1) / np.sqrt(n) * stats.t.ppf(QUANTILES, n - 1)[:, None]
def summary(draws, truth):
"""Posterior mean and central 90% interval per dataset (draws on axis 0), and what they add up to."""
mean = draws.mean(0)
lo, hi = np.quantile(draws, [(1 - CI) / 2, (1 + CI) / 2], axis=0)
return dict(mean=mean, lo=lo, hi=hi, bias=float(np.mean(mean - truth)), rmse=float(np.sqrt(np.mean((mean - truth) ** 2))),
coverage=float(np.mean((lo <= truth) & (truth <= hi))), width=float(np.mean(hi - lo)))
g = summary(gaussian_location(y_bench[None, :]), MU)
print(f"Gaussian posterior of the level, bench dataset: {g['mean'][0]:.2f}, 90% interval [{g['lo'][0]:.2f}, {g['hi'][0]:.2f}] (truth {MU:.0f})")
print(f"robust scale of the readings (MAD): {robust_scale(y_bench):.2f}; their standard deviation: {y_bench.std(ddof=1):.2f}")
Gaussian posterior of the level, bench dataset: 10.73, 90% interval [10.34, 11.13] (truth 10) robust scale of the readings (MAD): 1.20; their standard deviation: 2.39
Nine readings in a hundred that are 8 too high move the estimate by about 0.7, and the interval does not come near the truth. The sample standard deviation has more than doubled as well, so the posterior is both in the wrong place and vaguer than it should be. The median and the MAD, which we will use as starting values and never as estimates, are 10.1 and 1.2.
The choice. A simulated truth with a contamination share we control, and three kinds of contamination, because "robust" means something different for each. Rejected: a single heavy-tailed noise distribution, which is the case E131 studied and in which the centre is never in doubt. What would change our mind: nothing about the design; a method that passed all three kinds would simply be the one to use, and none does.
2 · Four ways to discount a reading
Each alternative replaces the Gaussian log-likelihood by something that grows more slowly with the size of a residual. The clearest way to compare them is to ask how hard a single reading at distance $r$ (in standard deviations) pulls on the estimate of the level. For the Gaussian model the pull is $r$ itself: twice as far, twice the pull. That function of $r$ is the influence of a reading.
A contamination mixture names the second process: $y_i \sim (1 - \omega)\,\mathcal N(\mu, \sigma^2) + \omega\,\mathcal N(\mu_o, \sigma_o^2)$. A reading is discounted by the probability that it belongs to the other component. We let the other component sit anywhere ($\mu_o \sim \mathcal N(0, 100)$), with a spread at least that of the bulk ($\sigma_o = \sigma\,(1 + e^{\lambda})$, $\lambda \sim \mathcal N(0, 2)$, so from just above $\sigma$ to fifty times it), and we say that outliers are the minority: $\omega$ is half of a Beta(1, 2) variable and cannot exceed one half. For the second source and the humidity this is the model that generated the data. That makes it the method to beat, and the question is how much is lost by not writing it.
A Student-t likelihood names heavy tails: $y_i \sim t_\nu(\mu, \sigma)$ with $\nu \sim \text{Gamma}(2, 0.1)$ estimated. Its pull is $(\nu + 1)\,r/(\nu + r^2)$, which rises, peaks near $\sqrt\nu$ and then falls slowly, like $1/r$.
The beta-divergence posterior keeps the Gaussian density $f$ and uses the loss
$$\ell_\beta(y, \theta) \;=\; -\frac{1}{\beta}\, f(y; \theta)^{\beta} \;+\; \frac{1}{1+\beta}\int f(z; \theta)^{1+\beta}\,dz , \qquad \beta > 0 .$$
The first term rewards density at the observation, as a log-likelihood does, but $f^\beta/\beta$ is bounded where $\log f$ is not: a reading in a region of negligible density contributes nothing, instead of minus infinity. The second term keeps the model from cheating by spreading out; it is the same for every observation and depends only on the parameters. Subtracting the constant $1/\beta - 1$ and letting $\beta \to 0$ gives back $-\log f$, so the Gaussian posterior is the member $\beta = 0$ of the family. For a Gaussian density the integral is elementary:
$$\int \mathcal N(z; \mu, \sigma^2)^{1+\beta} dz = (2\pi\sigma^2)^{-\frac{1+\beta}{2}} \int e^{-\frac{(1+\beta)(z-\mu)^2}{2\sigma^2}} dz = (2\pi\sigma^2)^{-\frac{1+\beta}{2}} \sqrt{\frac{2\pi\sigma^2}{1+\beta}} = (2\pi\sigma^2)^{-\beta/2}\,(1+\beta)^{-1/2},$$
so that $\ell_\beta(y, \theta) = -\tfrac1\beta\,\mathcal N(y; \mu, \sigma^2)^\beta + (2\pi\sigma^2)^{-\beta/2}(1+\beta)^{-3/2}$. Setting the derivative in $\mu$ to zero shows what the loss does: the estimate is a weighted mean with weights $e^{-\beta r_i^2/2}$, and the pull of a reading is $r\,e^{-\beta r^2/2}$. It falls to zero much faster than the Student-t's. At $\beta = 0.5$ a reading four standard deviations out has a weight of 0.02, and one at eight has none to speak of.
The Huber loss is $\rho_c(r) = r^2/2$ for $|r| \le c$ and $c|r| - c^2/2$ beyond, applied to residuals divided by a fixed robust scale (the MAD), with the customary $c = 1.345$. Its pull is $r$ clipped at $\pm c$: a far reading pulls as hard as one at $c$, never harder, and never less. There is no density behind it, so this is a Gibbs posterior in the plain sense, a loss in the place of a log-likelihood.
C_HUBER, BETA = 1.345, 0.5
def huber_rho(r):
a = np.abs(r)
return np.where(a <= C_HUBER, 0.5 * r**2, C_HUBER * a - 0.5 * C_HUBER**2)
def huber_psi(r):
return np.clip(r, -C_HUBER, C_HUBER)
def integral_term(sigma, beta):
"""(1 / (1 + beta)) times the integral of the Gaussian density to the power 1 + beta."""
return (2 * np.pi * sigma**2) ** (-beta / 2) * (1 + beta) ** -1.5
for m_, s_, b_ in ((10.0, 1.0, 0.5), (1.3, 0.7, 0.25), (-4.0, 12.0, 1.0)):
numeric = integrate.quad(lambda z: stats.norm.pdf(z, m_, s_) ** (1 + b_), m_ - 40 * s_, m_ + 40 * s_)[0] / (1 + b_)
print(f"mu = {m_:5.1f}, sigma = {s_:4.1f}, beta = {b_:4.2f}: integral term by quadrature {numeric:.10f}, closed form {integral_term(s_, b_):.10f}")
r = np.linspace(0, 9, 400)
fig, axes = plt.subplots(1, 2, figsize=(12.5, 3.9))
ax = axes[0]
ax.plot(r, r, color=COLOR[GAUSS], lw=2, label="Gaussian")
ax.plot(r, huber_psi(r), color=COLOR[HUBER], lw=2, label="Huber loss, c = 1.345")
ax.plot(r, 4 * r / (3 + r**2), color=COLOR[STUDENT], lw=2, label="Student-t, $\\nu$ = 3")
for b_, ls in ((0.25, "--"), (0.5, "-")):
ax.plot(r, r * np.exp(-0.5 * b_ * r**2), color=COLOR[BD1], lw=2, ls=ls, label=f"beta-divergence, $\\beta$ = {b_}")
ax.set_ylim(0, 3.2)
ax.set_xlabel("distance of a reading from the fitted level, in standard deviations")
ax.set_ylabel("pull on the estimate")
ax.set_title("How hard one reading pulls", loc="left")
ax.legend(frameon=False, fontsize=9, loc="upper right")
tidy(ax)
ax = axes[1]
ax.plot(r, 0.5 * r**2, color=COLOR[GAUSS], lw=2, label="Gaussian: $r^2/2$")
ax.plot(r, huber_rho(r), color=COLOR[HUBER], lw=2, label="Huber loss")
ax.plot(r, 2 * np.log1p(r**2 / 3), color=COLOR[STUDENT], lw=2, label="Student-t, $\\nu$ = 3")
for b_, ls in ((0.25, "--"), (0.5, "-")):
ax.plot(r, (1 - np.exp(-0.5 * b_ * r**2)) / b_, color=COLOR[BD1], lw=2, ls=ls, label=f"beta-divergence, $\\beta$ = {b_}")
ax.set_ylim(0, 9)
ax.set_xlabel("distance of a reading from the fitted level, in standard deviations")
ax.set_ylabel("loss, from its value at the centre")
ax.set_title("What one reading costs the fit", loc="left")
ax.legend(frameon=False, fontsize=9, loc="upper left")
tidy(ax);
mu = 10.0, sigma = 1.0, beta = 0.50: integral term by quadrature 0.3438097150, closed form 0.3438097150 mu = 1.3, sigma = 0.7, beta = 0.25: integral term by quadrature 0.6217101919, closed form 0.6217101919 mu = -4.0, sigma = 12.0, beta = 1.00: integral term by quadrature 0.0117539497, closed form 0.0117539497

The closed form of the integral term agrees with numerical quadrature to ten decimals for three unrelated settings.
The left panel is the whole idea in one picture. The Gaussian line keeps rising: the further a reading, the more it counts. Huber's levels off. The Student-t comes back down slowly, and the beta-divergence comes back down fast and reaches zero; such a pull is called redescending. The right panel shows the same thing as a cost (the beta-divergence loss is drawn with $\sigma = 1$ and the density's constant left out). The two redescending curves flatten, and a flat cost is the root of a difficulty we will meet in part 7: a cost that stops growing does not care where a far reading is, so the total cost can have more than one minimum.
A learning rate, and where to start
A log-likelihood comes with its own scale. A loss does not: $\exp\{-w \sum \ell\}$ is a different posterior for each $w$, wider when $w$ is small, and the loss itself gives no reason to prefer $w = 1$. E131 is about exactly this number for the case $\ell = -\log f$, where it is called the power, and it compares several ways of setting it. We use the simplest one that targets an interval: choose $w$ so that the posterior variance of the parameter we report equals the variance that the estimate really has from one dataset to the next. In large samples the estimate that minimises $\sum \ell$ has the sandwich covariance $J^{-1} K J^{-1}$, with $J = \sum_i \partial^2 \ell_i$ and $K = \sum_i (\partial \ell_i)(\partial \ell_i)^\top$, while the generalised posterior has covariance $J^{-1}/w$. For the $k$-th parameter the two agree when
$$\hat w \;=\; \frac{[J^{-1}]_{kk}}{[J^{-1} K J^{-1}]_{kk}},$$
with both matrices evaluated at a pilot estimate. This is the information matching of Lyddon, Holmes and Walker (2019), applied to one parameter instead of the trace, which E131 found to depend on the units of the regressors. For the Huber loss on scaled residuals it reduces to the share of readings inside $\pm c$ divided by the mean of $\psi_c(r)^2$. We call the result "rate matched". Jewson, Smith and Holmes (2018) argue that the beta-divergence loss, being built from a density and a divergence, needs no such weight, and set $w = 1$. We fit it both ways, and part 4 measures the difference.
One piece of housekeeping serves all five models. A robust fit should start from a robust place, so
we write each location and slope as start + unit × z with a flat z, add the prior as a
potential on the parameter itself, and pass the start as data. The prior is then the one stated
above whatever the start, the sampler begins at the start (plus a small jitter), and the same
compiled model can be refilled with new data and new starts. The location starts at the median and
the scale at the MAD.
PRIOR = dict(level_sd=100.0, slope_sd=10.0, sigma_sd=10.0)
def located(name, start, unit, prior_sd):
"""A parameter with prior N(0, prior_sd), sampled as start + unit * z so that a chain starts at `start`."""
z = pm.Flat(name + "_z")
value = pm.Deterministic(name, start + unit * z)
pm.Potential(name + "_prior", pm.logp(pm.Normal.dist(0.0, prior_sd), value))
return value
def positive(name, start, prior_sd):
"""A scale with prior Half-Normal(prior_sd), sampled as start * exp(u); the `+ u` is the Jacobian."""
u = pm.Flat(name + "_u")
value = pm.Deterministic(name, start * pt.exp(u))
pm.Potential(name + "_prior", pm.logp(pm.HalfNormal.dist(prior_sd), value) + u)
return value
def robust_model(method, y, x=None):
"""One of the five posteriors, for a level (x is None) or a straight line. Starts, units, beta and the
learning rate are data, so one compiled model serves every dataset."""
with pm.Model() as model:
yd = pm.Data("y", y)
st = {k: pm.Data(k, v) for k, v in dict(start_level=0.0, start_slope=0.0, start_scale=1.0,
unit_level=1.0, unit_slope=1.0, x_centre=0.0).items()}
level = located("level", st["start_level"], st["unit_level"], PRIOR["level_sd"]) # the line at x = x_centre
if x is None:
mu = level
else:
xd = pm.Data("x", x)
slope = located("slope", st["start_slope"], st["unit_slope"], PRIOR["slope_sd"])
pm.Deterministic("intercept", level - slope * st["x_centre"])
mu = level + slope * (xd - st["x_centre"])
if method == "huber":
rate = pm.Data("rate", 1.0)
res = (yd - mu) / st["start_scale"] # the scale is fixed at its robust start
rho = pt.switch(pt.abs(res) <= C_HUBER, 0.5 * res**2, C_HUBER * pt.abs(res) - 0.5 * C_HUBER**2)
pm.Potential("huber_loss", -rate * rho.sum())
return model
sigma = positive("sigma", st["start_scale"], PRIOR["sigma_sd"])
if method == "gauss":
pm.Potential("loglik", pm.logp(pm.Normal.dist(mu, sigma), yd).sum())
elif method == "student":
nu = pm.Gamma("nu", alpha=2.0, beta=0.1)
pm.Potential("loglik", pm.logp(pm.StudentT.dist(nu=nu, mu=mu, sigma=sigma), yd).sum())
elif method == "mixture":
share = pm.Deterministic("share", 0.5 * pm.Beta("omega", 1.0, 2.0))
other_level = located("other_level", st["start_level"], 3 * st["start_scale"], PRIOR["level_sd"])
other_sigma = pm.Deterministic("other_sigma", sigma * (1 + pt.exp(pm.Normal("log_excess", 0.0, 2.0))))
on = pt.log1p(-share) + pm.logp(pm.Normal.dist(mu, sigma), yd)
off = pt.log(share) + pm.logp(pm.Normal.dist(other_level, other_sigma), yd)
pm.Potential("loglik", pt.logaddexp(on, off).sum())
elif method == "beta":
beta, rate = pm.Data("beta", BETA), pm.Data("rate", 1.0)
log_f = pm.logp(pm.Normal.dist(mu, sigma), yd)
integral = (2 * np.pi * sigma**2) ** (-beta / 2) * (1 + beta) ** -1.5
pm.Potential("beta_loss", rate * (pt.exp(beta * log_f) / beta - integral).sum())
return model
def nuts(compiled, seed, draws=250, tune=250, chains=2, **values):
"""NUTS on a compiled model with new data. Repeated datasets get 2 chains of 250 draws after 250 warm-up steps."""
values = {k: np.asarray(v, dtype=float) for k, v in values.items()}
return nutpie.sample(compiled.with_data(**values), draws=draws, tune=tune, chains=chains, cores=min(chains, 4),
seed=seed, progress_bar=False)
def location_start(y):
s = robust_scale(y)
return dict(y=y, start_level=np.median(y), start_scale=s, unit_level=0.3 * s)
The two pilot estimates are short fixed-point iterations. For the beta-divergence, setting the derivatives of $\sum_i \ell_\beta$ to zero gives a weighted mean and a weighted variance with weights $w_i = e^{-\beta r_i^2/2\sigma^2}$, the variance with a correction in its denominator:
$$\hat\mu = \frac{\sum w_i y_i}{\sum w_i}, \qquad \hat\sigma^2 = \frac{\sum w_i (y_i - \hat\mu)^2}{\sum w_i - n\beta(1+\beta)^{-3/2}} .$$
For the Huber loss it is the usual reweighted mean. Both start from the median and the MAD.
def beta_pilot(Y, beta, iters=300):
"""The minimiser of the summed beta-divergence loss for each row of Y: level and scale."""
n = Y.shape[-1]
mu, sigma = np.median(Y, -1), robust_scale(Y)
for _ in range(iters):
res = Y - mu[:, None]
w = np.exp(-0.5 * beta * (res / sigma[:, None]) ** 2)
mu_new = (w * Y).sum(-1) / w.sum(-1)
sigma_new = np.sqrt((w * res**2).sum(-1) / (w.sum(-1) - n * beta * (1 + beta) ** -1.5))
done = np.max(np.abs(mu_new - mu) + np.abs(sigma_new - sigma)) < 1e-10
mu, sigma = mu_new, sigma_new
if done:
break
return mu, sigma
def huber_pilot(Y, iters=100):
"""Huber's M-estimate of the level for each row of Y, with the scale fixed at the MAD."""
mu, s = np.median(Y, -1), robust_scale(Y)
for _ in range(iters):
res = (Y - mu[:, None]) / s[:, None]
w = np.where(np.abs(res) <= C_HUBER, 1.0, C_HUBER / np.maximum(np.abs(res), 1e-12))
mu = (w * Y).sum(-1) / w.sum(-1)
return mu, s
def matched_rate(curvature, score2, X=None, k=0):
"""The learning rate at which the posterior variance of coefficient k equals its sandwich variance."""
if X is None:
return curvature.sum(-1) / score2.sum(-1)
J = np.einsum("...n,...ni,...nj->...ij", curvature, X, X)
K = np.einsum("...n,...ni,...nj->...ij", score2, X, X)
J_inv = np.linalg.inv(J)
return J_inv[..., k, k] / (J_inv @ K @ J_inv)[..., k, k]
def beta_rate(res, sigma, beta, X=None, k=0):
"""Matched rate of the beta-divergence loss, from residuals and the scale at a pilot estimate."""
sigma = np.asarray(sigma)[..., None]
f_beta = (2 * np.pi * sigma**2) ** (-beta / 2) * np.exp(-0.5 * beta * (res / sigma) ** 2)
return matched_rate(f_beta * (1 / sigma**2 - beta * res**2 / sigma**4), f_beta**2 * res**2 / sigma**4, X, k)
def huber_rate(res, X=None, k=0):
"""Matched rate of the Huber loss, from residuals already divided by the scale."""
return matched_rate((np.abs(res) <= C_HUBER).astype(float), huber_psi(res) ** 2, X, k)
mu_b, sigma_b = beta_pilot(y_bench[None, :], BETA)
mu_h, s_h = huber_pilot(y_bench[None, :])
RATE_BENCH = {BDM: float(beta_rate(y_bench - mu_b[0], sigma_b[0], BETA)), HUBER: float(huber_rate((y_bench - mu_h[0]) / s_h[0]))}
print(f"bench dataset, pilot estimates: beta-divergence level {mu_b[0]:.3f} and scale {sigma_b[0]:.3f}; Huber level {mu_h[0]:.3f}")
print(f"matched learning rates: beta-divergence {RATE_BENCH[BDM]:.2f}, Huber loss {RATE_BENCH[HUBER]:.2f}")
bench dataset, pilot estimates: beta-divergence level 10.010 and scale 1.120; Huber level 10.234 matched learning rates: beta-divergence 2.86, Huber loss 0.99
The beta-divergence pilot puts the level at 10.01 and the scale at 1.1, as if the nine bad readings were not there. Huber's estimate is pulled up a little. The matched rates are the interesting numbers: the Huber loss asks for a rate near 1, which says its natural scale is about right, and the beta-divergence loss asks for a rate near 3, which says that at $w = 1$ its posterior will be much wider than the estimate's real spread. Part 4 explains where that number comes from.
The choice. For the beta-divergence, $\beta = 0.5$ as the working value until part 5 studies it, and both learning rates. For the Huber loss, the matched rate only. Rejected: estimating Huber's scale inside the Gibbs posterior, which needs a second loss for the scale; fixing it at the MAD is the common shortcut and its cost shows up later, when the MAD itself is contaminated. What would change our mind: a loss with a likelihood behind it and a scale of its own. That is the Student-t, which is on the list.
3 · Six posteriors for the bench dataset
Each model is compiled once with nutpie and sampled with four chains of 1,000 draws after 500 warm-up steps. The scoreboard records the time of compiling and sampling together, since that is what a first fit costs. The rate-matched beta-divergence posterior is the same model with one number changed; its row includes a compilation of its own so that the rows can be compared.
sb = Scoreboard(truth={"level": np.full(REPS, MU)}, ci_prob=CI)
COMPILED, BENCH, ESS = {}, {}, {}
METHOD = {GAUSS: "gauss", MIX: "mixture", STUDENT: "student", BD1: "beta", BDM: "beta", HUBER: "huber"}
VARS = {GAUSS: ["level", "sigma"], MIX: ["level", "sigma", "share", "other_level", "other_sigma"],
STUDENT: ["level", "sigma", "nu"], BD1: ["level", "sigma"], BDM: ["level", "sigma"], HUBER: ["level"]}
def diagnose(trace, names):
ds = trace.posterior.to_dataset()[list(names)]
rhat = max(float(v.max()) for v in az.rhat(ds).data_vars.values())
ess = min(float(v.min()) for v in az.ess(ds, method="bulk").data_vars.values())
return rhat, ess, int(trace.sample_stats["diverging"].sum())
rows = []
for label, method in METHOD.items():
extra = {"rate": RATE_BENCH[label]} if label in RATE_BENCH else {}
with sb.track(label):
compiled = nutpie.compile_pymc_model(robust_model(method, y_bench))
trace = nuts(compiled, RANDOM_SEED, draws=1000, tune=500, chains=4, **location_start(y_bench), **extra)
COMPILED.setdefault(method, compiled)
rhat, ess, div = diagnose(trace, VARS[label])
BENCH[label] = trace
ESS[label] = float(az.ess(trace.posterior["level"].to_dataset(), method="bulk")["level"])
q = np.quantile(trace.posterior["level"].values, [0.05, 0.5, 0.95])
rows.append({"method": label, "level": q[1], "5%": q[0], "95%": q[2], "width": q[2] - q[0], "r_hat": rhat,
"smallest bulk ESS": ess, "divergences": div})
bench_table = pd.DataFrame(rows).set_index("method")
print(f"posterior of the level, bench dataset (truth {MU:.0f}; mean of the good readings {y_bench[~bad_bench].mean():.2f})")
bench_table.round(3)
posterior of the level, bench dataset (truth 10; mean of the good readings 10.06)
| level | 5% | 95% | width | r_hat | smallest bulk ESS | divergences | |
|---|---|---|---|---|---|---|---|
| method | |||||||
| Gaussian | 10.73 | 10.35 | 11.12 | 0.778 | 1.002 | 3863 | 0 |
| contamination mixture | 10.06 | 9.88 | 10.25 | 0.366 | 1.001 | 4193 | 0 |
| Student-t | 10.05 | 9.851 | 10.26 | 0.409 | 1.001 | 1709 | 0 |
| beta-divergence, rate 1 | 10.01 | 9.656 | 10.39 | 0.732 | 1.002 | 3034 | 0 |
| beta-divergence, rate matched | 10.01 | 9.806 | 10.22 | 0.413 | 1.001 | 3822 | 0 |
| Huber loss, rate matched | 10.22 | 9.998 | 10.46 | 0.467 | 1.002 | 1821 | 0 |
post = BENCH[MIX].posterior
print(f"mixture: share of the other component {float(post['share'].mean()):.3f} ({bad_bench.sum()} of {N} readings were replaced), "
f"its level {float(post['other_level'].mean()):.2f} and spread {float(post['other_sigma'].mean()):.2f} (truth 18 and 1)")
print(f"Student-t: degrees of freedom, posterior median {float(BENCH[STUDENT].posterior['nu'].median()):.1f}; "
f"scale {float(BENCH[STUDENT].posterior['sigma'].mean()):.2f}")
print(f"beta-divergence, rate 1: scale {float(BENCH[BD1].posterior['sigma'].mean()):.2f}; Gaussian: scale {float(BENCH[GAUSS].posterior['sigma'].mean()):.2f}")
fig, ax = plt.subplots(figsize=(9.5, 3.4))
ax.axvline(MU, color=INK, lw=1.2, ls="--")
ax.axvline(y_bench[~bad_bench].mean(), color=MUTED, lw=1, ls=":")
for i, label in enumerate(bench_table.index):
row = bench_table.loc[label]
ax.plot([row["5%"], row["95%"]], [i, i], color=COLOR[label], lw=2.6)
ax.plot([row["level"]], [i], "o", color=COLOR[label], ms=6, mfc="white" if label == BDM else COLOR[label])
ax.set_yticks(range(len(bench_table)), bench_table.index, fontsize=9)
ax.set_ylim(len(bench_table) - 0.5, -0.5)
ax.set_xlabel("level of the sensor in the chamber: posterior median and 90% interval")
ax.set_title(f"The bench dataset: {bad_bench.sum()} readings in {N} from a second source", loc="left", fontsize=11)
ax.text(MU, -0.42, " truth", fontsize=8.5, color=INK, va="top")
tidy(ax, grid="x");
mixture: share of the other component 0.096 (9 of 100 readings were replaced), its level 17.49 and spread 1.21 (truth 18 and 1) Student-t: degrees of freedom, posterior median 1.7; scale 0.93 beta-divergence, rate 1: scale 1.21; Gaussian: scale 2.42

All six fits are clean: r_hat is 1.00, the smallest effective sample size is above 1,500 and there is not one divergent transition. The dotted line marks the mean of the 91 good readings, 10.06, which is the best any method could do with this dataset; the dashed line is the truth.
The Gaussian interval runs from 10.3 to 11.1 and misses. The mixture finds the second source without being told where it is: it puts 9.6% of the readings in a component at 17.5, and its level, 10.06, is the mean of the good readings. The Student-t gets nearly the same answer by a different route, with degrees of freedom below 2: to accommodate nine readings at 8 standard deviations it has to become almost a Cauchy. The beta-divergence posterior has no parameter for the bad readings at all and is the closest to 10. Its scale is 1.2 where the Gaussian model's is 2.4.
Two things in the table deserve a second look, and the next two parts take them in turn. The beta-divergence interval at rate 1 is nearly as wide as the Gaussian one, twice the width of the mixture's, while the rate-matched interval is as narrow as the Student-t's. And the Huber posterior sits at 10.2, with an interval whose lower end is at the truth: the nine bad readings each pull with the force of a reading at $c$, all in the same direction, and the loss has no way to let go of them.
The choice. Nothing is rejected yet on the strength of one dataset. What the bench fit settles is that the two losses run in PyMC as written, with
pm.Potential, as fast and as cleanly as the models with a likelihood. What would change our mind about running them at all: chains that disagreed. They will, in part 7.
4 · Are the intervals honest? The learning rate, and the units of the data
Nothing guarantees that the interval of a posterior built on a loss covers at its nominal level. The Gaussian posterior of a correct Gaussian model covers the truth 90% of the time by construction. For the two generalised posteriors we have to count.
Counting needs many posteriors, and here they can be exact. The Huber posterior has one parameter and the beta-divergence posterior two, so we evaluate each on a grid placed around its pilot estimate (seven posterior standard deviations either way for the level, six for $\log\sigma$) and read the quantiles of the level off the cumulative sums. No sampling is involved. The first check is that the grid and NUTS agree on the bench dataset.
def quantile_draws(grid, density):
"""1,000 evenly spaced quantiles of densities tabulated on grids (rows: datasets), by the trapezoid rule."""
cdf = np.concatenate([np.zeros_like(density[:, :1]), np.cumsum(0.5 * (density[:, 1:] + density[:, :-1]), axis=1)], axis=1)
return np.stack([np.interp(QUANTILES, c / c[-1], g) for c, g in zip(cdf, grid)], axis=1)
def beta_loss(Y, mu, sigma, beta):
"""Summed beta-divergence loss of a Gaussian level and scale (broadcast against the readings on the last axis)."""
f_beta = (2 * np.pi * sigma**2) ** (-beta / 2) * np.exp(-0.5 * beta * ((Y - mu) / sigma) ** 2)
return (-f_beta / beta + integral_term(sigma, beta)).sum(-1)
def beta_location(Y, beta, rate=1.0, unit=1.0, shape=(81, 41), full=False):
"""Exact beta-divergence posterior of the level, for each row of Y, as quantile draws (1000, rows).
`rate` is a number or "matched". `unit` rescales the priors, for data expressed in other units."""
mu_hat, s_hat = beta_pilot(Y, beta)
w = beta_rate(Y - mu_hat[:, None], s_hat, beta) if rate == "matched" else np.full(len(Y), float(rate))
col = lambda v: v[:, None]
L0, h_mu, h_ls = beta_loss(Y, col(mu_hat), col(s_hat), beta), 1e-3 * s_hat, 1e-3 # curvatures set the grid
c_mu = (beta_loss(Y, col(mu_hat + h_mu), col(s_hat), beta) - 2 * L0 + beta_loss(Y, col(mu_hat - h_mu), col(s_hat), beta)) / h_mu**2
c_ls = (beta_loss(Y, col(mu_hat), col(s_hat * np.exp(h_ls)), beta) - 2 * L0
+ beta_loss(Y, col(mu_hat), col(s_hat * np.exp(-h_ls)), beta)) / h_ls**2
mu_g = col(mu_hat) + col(1 / np.sqrt(w * c_mu)) * np.linspace(-7, 7, shape[0]) # (rows, levels)
ls_g = col(np.log(s_hat)) + col(1 / np.sqrt(w * c_ls)) * np.linspace(-6, 6, shape[1]) # (rows, log scales)
sig_g = np.exp(ls_g)
density = np.empty((len(Y), *shape))
for lo in range(0, len(Y), 25): # 25 datasets at a time: 66 MB
k = slice(lo, lo + 25)
loss = beta_loss(Y[k, None, None, :], mu_g[k, :, None, None], sig_g[k, None, :, None], beta)
logp = (-w[k, None, None] * loss + stats.norm.logpdf(mu_g[k, :, None], 0, unit * PRIOR["level_sd"])
+ stats.halfnorm.logpdf(sig_g[k, None, :], scale=unit * PRIOR["sigma_sd"]) + ls_g[k, None, :])
density[k] = np.exp(logp - logp.max(axis=(1, 2), keepdims=True))
draws = quantile_draws(mu_g, density.sum(-1))
return (draws, dict(density=density, mu=mu_g, sigma=sig_g, rate=w)) if full else draws
def huber_location(Y, rate="matched"):
"""Exact Huber-loss Gibbs posterior of the level, the scale fixed at the MAD, as quantile draws (1000, rows)."""
mu_hat, s = huber_pilot(Y)
res = (Y - mu_hat[:, None]) / s[:, None]
w = huber_rate(res) if rate == "matched" else np.full(len(Y), float(rate))
sd = s / np.sqrt(w * (np.abs(res) <= C_HUBER).sum(-1))
mu_g = mu_hat[:, None] + sd[:, None] * np.linspace(-8, 8, 161)
loss = np.concatenate([huber_rho((Y[k:k + 100, None, :] - mu_g[k:k + 100, :, None]) / s[k:k + 100, None, None]).sum(-1)
for k in range(0, len(Y), 100)])
logp = -w[:, None] * loss + stats.norm.logpdf(mu_g, 0, PRIOR["level_sd"])
return quantile_draws(mu_g, np.exp(logp - logp.max(-1, keepdims=True)))
EXACT = {GAUSS: gaussian_location, BD1: lambda Y: beta_location(Y, BETA), BDM: lambda Y: beta_location(Y, BETA, "matched"),
HUBER: huber_location}
print("bench dataset, level: 5% / 50% / 95% of the posterior")
for label, exact in EXACT.items():
q_exact = np.quantile(exact(y_bench[None, :])[:, 0], [0.05, 0.5, 0.95])
q_nuts = np.quantile(BENCH[label].posterior["level"].values, [0.05, 0.5, 0.95])
print(f" {label:30s} exact {q_exact[0]:.3f} / {q_exact[1]:.3f} / {q_exact[2]:.3f} NUTS {q_nuts[0]:.3f} / {q_nuts[1]:.3f} / {q_nuts[2]:.3f}")
bench dataset, level: 5% / 50% / 95% of the posterior Gaussian exact 10.338 / 10.733 / 11.129 NUTS 10.346 / 10.734 / 11.124 beta-divergence, rate 1 exact 9.657 / 10.014 / 10.384 NUTS 9.656 / 10.012 / 10.388 beta-divergence, rate matched exact 9.810 / 10.011 / 10.216 NUTS 9.806 / 10.011 / 10.219 Huber loss, rate matched exact 10.005 / 10.234 / 10.463 NUTS 9.998 / 10.225 / 10.464
The exact quantiles and the NUTS quantiles agree to about 0.01, the Monte Carlo error of 4,000 draws. (For the Gaussian row this is also the check that the weak priors of the NUTS model and the flat priors of the closed form give the same posterior.)
Now the count, on data with no contamination at all: 1,000 clean datasets, the truth at 10. We do it three times, with the same readings written in three units: as they are, divided by ten and multiplied by ten, the priors rescaled to match. Think of micrograms, tens of micrograms and tenths of a microgram. A Gaussian analysis does not notice: every number in it scales along.
clean = WORLD[0]
z90 = stats.norm.ppf(0.5 + CI / 2)
rows = []
for unit in (0.1, 1.0, 10.0):
Yu, truth = unit * clean, unit * MU
g = summary(gaussian_location(Yu), truth)
b1 = summary(beta_location(Yu, BETA, 1.0, unit), truth)
bm = summary(beta_location(Yu, BETA, "matched", unit), truth)
hm = summary(huber_location(Yu), truth)
ratio = (2 * np.pi * (unit * SIGMA) ** 2) ** (BETA / 2) * ((1 + 2 * BETA) / (1 + BETA)) ** 1.5 # posterior variance / real variance
rows.append({"sd of a reading": unit * SIGMA, "Gaussian: coverage": g["coverage"],
"beta, rate 1: coverage": b1["coverage"], "predicted": 2 * stats.norm.cdf(z90 * np.sqrt(ratio)) - 1,
"its width / Gaussian width": b1["width"] / g["width"],
"beta, rate matched: coverage": bm["coverage"], "its width / Gaussian": bm["width"] / g["width"],
"Huber, rate matched: coverage": hm["coverage"], "its width / Gaussian ": hm["width"] / g["width"]})
h1 = summary(huber_location(clean, 1.0), MU)
print(f"1,000 clean datasets of {N} readings; counting error of a coverage near 90%: about {np.sqrt(0.9 * 0.1 / REPS_EXACT):.3f}")
print(f"Huber loss with the rate left at 1: coverage {h1['coverage']:.3f}; matched rates on clean data, median: "
f"Huber {np.median(huber_rate((clean - huber_pilot(clean)[0][:, None]) / huber_pilot(clean)[1][:, None])):.2f}, "
f"beta-divergence {np.median(beta_location(clean[:200], BETA, 'matched', full=True)[1]['rate']):.2f}")
pd.DataFrame(rows).set_index("sd of a reading").round(3).T
1,000 clean datasets of 100 readings; counting error of a coverage near 90%: about 0.009
Huber loss with the rate left at 1: coverage 0.916; matched rates on clean data, median: Huber 1.15, beta-divergence 2.42
| sd of a reading | 0.1 | 1 | 10 |
|---|---|---|---|
| Gaussian: coverage | 0.901 | 0.901 | 0.901 |
| beta, rate 1: coverage | 0.86 | 0.991 | 1 |
| predicted | 0.851 | 0.99 | 1 |
| its width / Gaussian width | 0.969 | 1.796 | 3.871 |
| beta, rate matched: coverage | 0.912 | 0.912 | 0.912 |
| its width / Gaussian | 1.111 | 1.111 | 1.111 |
| Huber, rate matched: coverage | 0.9 | 0.9 | 0.9 |
| its width / Gaussian | 1.013 | 1.013 | 1.013 |
Read the three columns as the same experiment in three units. The Gaussian interval covers 90% in each, as it must. The beta-divergence posterior at rate 1 covers 99% when a reading has standard deviation 1, with intervals 1.8 times as wide as the Gaussian ones. Write the same readings in units ten times larger and it covers 86%, with intervals slightly narrower than the Gaussian ones; in units ten times smaller its intervals are more than three times as wide and always cover. Nothing about the sensor changed.
The reason is in the loss. A density has units: one over the unit of $y$. So $f^\beta$ has units too, and rescaling the data by a factor $c$ multiplies the whole loss by $c^{-\beta}$, which is the same as changing the learning rate. The estimate does not move, since a minimiser does not care about a constant factor. The width does. For a clean Gaussian sample the calculation can be done by hand: with $J$ and $K$ as in part 2, the posterior variance of the level at rate 1 is $1/J$ and the real variance of the estimate is $K/J^2$, and their ratio is
$$\frac{J}{K} \;=\; (2\pi\sigma^2)^{\beta/2}\,\Big(\frac{1+2\beta}{1+\beta}\Big)^{3/2} .$$
The "predicted" row is the coverage this ratio implies, and it matches the count. The ratio is 1 when $\sigma$ is about 0.17 in whatever units the data happen to be in (for $\beta = 0.5$), and nowhere else. At $\sigma = 1$ the matched rate is about 2.4: at rate 1 each reading counts for less than half of what it is worth. The argument of Jewson, Smith and Holmes (2018) for $w = 1$ is that the loss is in its canonical form, with no arbitrary constant in front. That is true of its form and it does not settle its size: the choice of units is an arbitrary constant, and it enters the loss as a factor.
Matching the rate removes the dependence. The rate-matched beta-divergence posterior covers 91% in every unit, with intervals 11% wider than the Gaussian ones, and that tenth is the real price of $\beta = 0.5$ on clean data, which part 5 looks at. The Huber posterior is free of the problem from the start, because its residuals are divided by a scale before the loss sees them; its matched rate is close to 1.15 and leaving it at 1 gives 92%.
There is a second consequence of a bounded loss, which we note here and meet again in part 9. As $\sigma$ grows, both terms of the loss go to zero, so $\exp\{-\sum\ell_\beta\}$ tends to 1 and not to 0: far from the data the generalised posterior is the prior. With 100 readings and $\beta = 0.5$ the region near the estimate outweighs that plateau by many orders of magnitude and nothing is seen of it. With few data points, a large $\beta$ or awkward units it can win.
The choice. The rate-matched posterior, for anything that will be reported as an interval. We keep rate 1 in every comparison below because that is the method as published. Rejected: standardising the readings by their MAD before the fit and then using rate 1, which also removes the units and still leaves the interval too wide by a fixed factor (it is the middle column, where $\sigma$ is 1). What would change our mind: a contamination that biases the estimate; the sandwich calibrates the spread around the place the estimate converges to, and if that place is wrong no rate makes the interval honest.
5 · The price of $\beta$, and who chooses it
The tuning constant buys robustness with efficiency. On clean data the Gaussian posterior uses every reading at full weight and nothing can beat it; the beta-divergence estimate down-weights readings in the tails that were perfectly good. The sandwich of part 2 gives the price in closed form. For the level of a Gaussian sample,
$$\frac{\text{variance of the beta-divergence estimate}}{\text{variance of the mean}} = \frac{K}{J^2}\Big/\frac{\sigma^2}{n} = \frac{(1+\beta)^3}{(1+2\beta)^{3/2}} ,$$
so the root-mean-square error grows by the square root of that: 3% at $\beta = 0.25$, 9% at 0.5, 24% at 1. We check the formula on the 1,000 clean datasets, and then look at what $\beta$ buys: the bias that is left under contamination, as a function of $\beta$.
BETAS = np.array([0.05, 0.1, 0.2, 0.3, 0.5, 0.75, 1.0])
sweep_rows = []
gauss_clean = summary(gaussian_location(clean), MU)
for b_ in BETAS:
pilot = beta_pilot(clean, b_)[0]
post = summary(beta_location(clean[:300], b_, "matched", shape=(61, 31)), MU)
row = {"beta": b_, "RMSE / Gaussian RMSE, clean data": np.sqrt(np.mean((pilot - MU) ** 2)) / gauss_clean["rmse"],
"predicted": (1 + b_) ** 1.5 / (1 + 2 * b_) ** 0.75,
"matched interval: width / Gaussian": post["width"] / summary(gaussian_location(clean[:300]), MU)["width"],
"matched interval: coverage": post["coverage"]}
for kind, eps in (("second source", 0.10), ("second source", 0.20), ("humidity", 0.10), ("glitches", 0.10)):
row[f"bias, {kind} {eps:.0%}"] = float(np.mean(beta_pilot(contaminate(WORLD, kind, eps)[0], b_)[0] - MU))
sweep_rows.append(row)
beta_sweep = pd.DataFrame(sweep_rows).set_index("beta")
print(f"bias of the Gaussian mean: second source 10% {0.8:+.2f}, 20% {1.6:+.2f}, humidity 10% {0.25:+.2f} (by construction)")
beta_sweep.round(3).T
bias of the Gaussian mean: second source 10% +0.80, 20% +1.60, humidity 10% +0.25 (by construction)
| beta | 0.05 | 0.1 | 0.2 | 0.3 | 0.5 | 0.75 | 1 |
|---|---|---|---|---|---|---|---|
| RMSE / Gaussian RMSE, clean data | 1.003 | 1.008 | 1.024 | 1.045 | 1.096 | 1.166 | 1.239 |
| predicted | 1.002 | 1.006 | 1.021 | 1.042 | 1.092 | 1.164 | 1.241 |
| matched interval: width / Gaussian | 1.017 | 1.023 | 1.041 | 1.063 | 1.119 | 1.199 | 1.285 |
| matched interval: coverage | 0.92 | 0.917 | 0.923 | 0.92 | 0.913 | 0.913 | 0.907 |
| bias, second source 10% | 0.67 | 0.484 | 0.023 | 0.003 | 0.002 | 0.002 | 0.002 |
| bias, second source 20% | 1.496 | 1.377 | 0.727 | 0.122 | 0.006 | 0.002 | 0.002 |
| bias, humidity 10% | 0.238 | 0.222 | 0.193 | 0.168 | 0.129 | 0.098 | 0.079 |
| bias, glitches 10% | 0.005 | 0.004 | 0.003 | 0.003 | 0.002 | 0.002 | 0.002 |
The first two rows agree: the measured loss of accuracy on clean data follows the formula, from under 1% at $\beta = 0.1$ to about a quarter at $\beta = 1$. The rate-matched interval widens a little more than that and keeps its coverage between 91% and 92% for every $\beta$ (on 300 datasets the counting error is two points).
The bias rows show what is bought. Against the second source, which is 8 standard deviations away, $\beta = 0.2$ removes the bias at 10% contamination, and at 20% it takes 0.3 to 0.5; at $\beta = 0.05$ most of it is still there, because a weight of $e^{-0.05 \cdot 64 / 2} = 0.2$ on each bad reading is far from zero. Against the humidity, 2.5 standard deviations away, $\beta$ helps slowly: half the Gaussian bias of 0.25 is left at 0.5 and a third at 1. A loss that discounts by distance cannot do much about readings that are not far. The glitches bias nothing at any $\beta$.
Letting the data choose: the Hyvärinen score
So $\beta$ should be as small as the contamination allows, and the contamination is what we do not know. Warwick and Jones (2005) choose it by minimising an estimate of the mean squared error, which needs a pilot estimate. Yonekura and Sugasawa (2021) give a rule that needs none and uses the posterior itself. A marginal likelihood cannot rank values of $\beta$, because $\exp\{-\ell_\beta\}$ is not a density in $y$ and has no normalising constant; but the Hyvärinen score compares models through derivatives of the log-density with respect to the data, and the unknown constant drops out. Their criterion, written with posterior expectations at rate 1, is
$$H_n(\beta) = \sum_{i=1}^n \Big\{ 2\,E\Big[\frac{\partial^2 D_i}{\partial y_i^2} + \Big(\frac{\partial D_i}{\partial y_i}\Big)^2\Big] - \Big(E\Big[\frac{\partial D_i}{\partial y_i}\Big]\Big)^2 \Big\}, \qquad D_i = \tfrac1\beta f(y_i;\theta)^\beta ,$$
and the smallest $H_n$ wins. For a Gaussian $f$ the two derivatives are $-f^\beta (y - \mu)/\sigma^2$ and $f^\beta\{\beta (y-\mu)^2 - \sigma^2\}/\sigma^4$. The authors minimise over $\beta$ with a sequential Monte Carlo sampler; our posteriors are exact on a grid, so we simply evaluate $H_n$ on ten values of $\beta$ and take the smallest.
H_BETAS = np.array([0.02, 0.05, 0.1, 0.15, 0.2, 0.3, 0.4, 0.5, 0.75, 1.0])
def h_score(Y, beta):
"""The Hyvärinen-score criterion of Yonekura and Sugasawa for each row of Y, from the exact posterior at rate 1."""
_, g = beta_location(Y, beta, 1.0, shape=(61, 31), full=True)
out = np.empty(len(Y))
for r in range(len(Y)):
p = g["density"][r] / g["density"][r].sum()
mu, sigma = g["mu"][r][:, None, None], g["sigma"][r][None, :, None]
res = Y[r] - mu
f_beta = (2 * np.pi * sigma**2) ** (-beta / 2) * np.exp(-0.5 * beta * (res / sigma) ** 2)
d1 = -f_beta * res / sigma**2
d2 = f_beta * (beta * res**2 - sigma**2) / sigma**4
out[r] = np.sum(2 * np.einsum("ms,msn->n", p, d2 + d1**2) - np.einsum("ms,msn->n", p, d1) ** 2)
return out
def beta_by_h_score(Y):
"""The beta each dataset chooses, and the rate-matched posterior of its level at that beta."""
pick = H_BETAS[np.argmin([h_score(Y, b_) for b_ in H_BETAS], axis=0)]
draws = np.empty((len(QUANTILES), len(Y)))
for b_ in np.unique(pick):
draws[:, pick == b_] = beta_location(Y[pick == b_], b_, "matched")
return draws, pick
with sb.track(BDH):
bench_h = np.array([h_score(y_bench[None, :], b_)[0] for b_ in H_BETAS])
bench_pick = H_BETAS[bench_h.argmin()]
beta_location(y_bench[None, :], bench_pick, "matched")
print(f"bench dataset: H-score by beta {dict(zip(H_BETAS.tolist(), np.round(bench_h, 1).tolist()))}")
print(f"bench dataset: the H-score chooses beta = {bench_pick}")
FINE = np.array([0.02, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.4, 0.5, 0.6, 0.75, 1.0])
bench_by_beta = {rate: np.array([np.quantile(beta_location(y_bench[None, :], b_, rate)[:, 0], [0.05, 0.5, 0.95]) for b_ in FINE])
for rate in (1.0, "matched")}
fig, axes = plt.subplots(1, 3, figsize=(13.5, 4.1))
ax = axes[0]
fine = np.linspace(0.02, 1, 100)
ax.plot(fine, (1 + fine) ** 1.5 / (1 + 2 * fine) ** 0.75, color=INK, lw=1.3, label="formula")
ax.plot(BETAS, beta_sweep["RMSE / Gaussian RMSE, clean data"], "o", color=BLUE, label="error of the estimate, 1,000 clean datasets")
ax.plot(BETAS, beta_sweep["matched interval: width / Gaussian"], "s", color=BLUE, mfc="white", label="width of the matched interval")
ax.set_xlabel("$\\beta$")
ax.set_ylabel("relative to the Gaussian posterior")
ax.set_title("The price on clean data", loc="left", fontsize=11)
ax.legend(frameon=False, fontsize=8.5, loc="upper left")
tidy(ax)
ax = axes[1]
for col, color, ls in (("bias, second source 10%", RED, "-"), ("bias, second source 20%", RED, "--"), ("bias, humidity 10%", VIOLET, "-")):
ax.plot(BETAS, beta_sweep[col], "o-", color=color, ls=ls, lw=1.8, label=col.replace("bias, ", ""))
ax.axhline(0, color=INK, lw=0.8)
ax.set_xlabel("$\\beta$")
ax.set_ylabel("bias of the estimated level")
ax.set_title("What it buys under contamination", loc="left", fontsize=11)
ax.legend(frameon=False, fontsize=8.5)
tidy(ax)
ax = axes[2]
for rate, color, label in ((1.0, LIGHT, "rate 1"), ("matched", BLUE, "rate matched")):
q = bench_by_beta[rate]
ax.fill_between(FINE, q[:, 0], q[:, 2], color=color, alpha=0.55 if rate == 1.0 else 0.35, lw=0, label=f"90% interval, {label}")
ax.plot(FINE, bench_by_beta["matched"][:, 1], "o-", color=BLUE, ms=4, lw=1.5, label="posterior median")
ax.axhline(MU, color=INK, lw=1.1, ls="--")
ax.axhline(y_bench.mean(), color=ORANGE, lw=1.1)
ax.text(1.0, y_bench.mean() - 0.03, "Gaussian mean", color=ORANGE, fontsize=8.5, ha="right", va="top")
ax.axvline(bench_pick, color=AQUA, lw=1.4, ls=":")
ax.text(bench_pick + 0.02, 10.62, "H-score", color=AQUA, fontsize=8.5)
ax.set_xlabel("$\\beta$")
ax.set_ylabel("level, bench dataset")
ax.set_title("The bench dataset as $\\beta$ varies", loc="left", fontsize=11)
ax.legend(frameon=False, fontsize=8.5, loc="upper right")
tidy(ax);
bench dataset: H-score by beta {0.02: -17.8, 0.05: -19.5, 0.1: -23.2, 0.15: -33.8, 0.2: -49.8, 0.3: -48.9, 0.4: -42.0, 0.5: -35.2, 0.75: -21.7, 1.0: -12.1}
bench dataset: the H-score chooses beta = 0.2
The right panel is the sensitivity plot for the bench dataset. Below $\beta = 0.15$ the estimate is still on its way down from the Gaussian mean. From about 0.2 on, the median hardly moves: once the nine bad readings have no weight, more $\beta$ changes nothing except the width, which grows slowly for the matched interval and quickly for the interval at rate 1. That flat stretch is the plain answer to "how would one choose $\beta$": look for the smallest value beyond which the estimate stops moving. The Hyvärinen score formalises the same idea and lands at the start of the flat stretch.
One dataset proves little about a rule, so we apply it to 100 datasets of each kind.
PICKS = {}
for kind, eps in (("glitches", 0.0), ("glitches", 0.10), ("second source", 0.05), ("second source", 0.10),
("second source", 0.20), ("humidity", 0.10)):
Y = contaminate(WORLD, kind, eps, REPS)[0]
PICKS[(kind, eps)] = beta_by_h_score(Y)
q = np.quantile(PICKS[(kind, eps)][1], [0.1, 0.5, 0.9])
name = "clean data" if eps == 0 else f"{kind}, {eps:.0%}"
s_ = summary(PICKS[(kind, eps)][0], MU)
print(f"{name:22s}: beta chosen by the H-score, 10% / median / 90% of {REPS} datasets: {q[0]:.2f} / {q[1]:.2f} / {q[2]:.2f};"
f" level: bias {s_['bias']:+.3f}, RMSE {s_['rmse']:.3f}, coverage {s_['coverage']:.2f}")
for unit in (0.1, 10.0):
pick = H_BETAS[np.argmin([h_score(unit * contaminate(WORLD, "second source", 0.10, REPS)[0], b_) for b_ in H_BETAS], axis=0)]
print(f"second source, 10%, readings multiplied by {unit:g}: median beta chosen {np.median(pick):.2f}")
clean data : beta chosen by the H-score, 10% / median / 90% of 100 datasets: 0.02 / 0.02 / 0.05; level: bias -0.006, RMSE 0.099, coverage 0.90
glitches, 10% : beta chosen by the H-score, 10% / median / 90% of 100 datasets: 0.10 / 0.15 / 0.20; level: bias -0.018, RMSE 0.118, coverage 0.89
second source, 5% : beta chosen by the H-score, 10% / median / 90% of 100 datasets: 0.15 / 0.15 / 0.20; level: bias +0.001, RMSE 0.106, coverage 0.91
second source, 10% : beta chosen by the H-score, 10% / median / 90% of 100 datasets: 0.15 / 0.20 / 0.30; level: bias +0.001, RMSE 0.112, coverage 0.92
second source, 20% : beta chosen by the H-score, 10% / median / 90% of 100 datasets: 0.20 / 0.30 / 0.40; level: bias -0.008, RMSE 0.119, coverage 0.93
humidity, 10% : beta chosen by the H-score, 10% / median / 90% of 100 datasets: 0.02 / 0.02 / 0.10; level: bias +0.237, RMSE 0.263, coverage 0.42
second source, 10%, readings multiplied by 0.1: median beta chosen 0.20
second source, 10%, readings multiplied by 10: median beta chosen 0.20
On clean data the rule chooses the smallest $\beta$ on offer, 0.02, in nearly every dataset: it sees nothing to guard against and hands back what is in effect the Gaussian posterior. With a second source it chooses more as the contamination grows, about 0.15 at 5%, 0.2 at 10% and 0.3 at 20%, close to the values at which the bias rows above come down to zero. The price it pays on clean data is then nil, and under far contamination a few percent. Yonekura and Sugasawa report choices of 0.23 and 0.36 for a similar example with 5% and 10% of readings shifted by 5 standard deviations.
One limit is visible in the same lines. For the humidity the rule chooses a small $\beta$, as on clean data: readings 2.5 standard deviations away do not look like a second process to it, and the bias stays. The units, on the other hand, did not disturb it: with the readings multiplied or divided by ten the median choice was the same 0.2, on this grid of ten values.
The choice. We keep $\beta = 0.5$ as the fixed working value, since a fixed value is what most users will try first, and carry the H-score choice beside it as a method of its own. Rejected: $\beta = 1$, which costs a quarter of the accuracy on clean data for no further protection against far readings, and very small values, which leave the bias in. What would change our mind: contamination known to be close to the bulk, where a larger $\beta$ does buy something; but then the next part shows that nothing here is a remedy.
6 · The estimate against the contamination fraction
This is the picture the notebook is built around. For each kind of contamination and each share (0, 5, 10 and 20%), 100 datasets, and for each dataset the posterior of the level under every method. The Gaussian, beta-divergence and Huber posteriors are exact. The mixture and the Student-t are refitted by NUTS with the compiled models of part 3, two chains of 250 draws after 250 warm-up steps, each chain starting at the median. As a yardstick we add an oracle no analyst has: the Gaussian posterior of the good readings alone.
def refit_location(method, Y):
"""NUTS on every row of Y with one compiled model: draws (500, rows), divergences, datasets whose chains disagree."""
draws, div, split = np.empty((500, len(Y))), 0, 0
for r in range(len(Y)):
trace = nuts(COMPILED[method], RANDOM_SEED + r, **location_start(Y[r]))
level = trace.posterior["level"].values
draws[:, r] = level.ravel()
div += int(trace.sample_stats["diverging"].sum())
split += abs(level[0].mean() - level[1].mean()) > 0.3
return draws, div, split
def oracle_location(Y, bad):
return np.stack([gaussian_location(y[~b][None, :])[:, 0] for y, b in zip(Y, bad)], axis=1)
ORACLE = "oracle: Gaussian, good readings only"
SWEEP, BOARD_DRAWS, notes = {}, {}, []
t0 = time.time()
for kind in KINDS:
for eps in EPS:
if eps == 0 and kind != "glitches":
SWEEP[(kind, eps)] = SWEEP[("glitches", 0.0)] # the clean datasets are the same for every kind
continue
Y, bad = contaminate(WORLD, kind, eps, REPS)
draws = {label: exact(Y) for label, exact in EXACT.items()}
draws[BDH] = PICKS[(kind, eps)][0] if (kind, eps) in PICKS else beta_by_h_score(Y)[0]
for label in (MIX, STUDENT):
draws[label], div, split = refit_location(METHOD[label], Y)
notes.append({"kind": kind, "share": eps, "method": label, "divergent transitions": div, "datasets with chains apart": int(split)})
draws[ORACLE] = oracle_location(Y, bad)
SWEEP[(kind, eps)] = {label: summary(d, MU) for label, d in draws.items()}
if (kind, eps) == (BENCH_KIND, BENCH_EPS):
BOARD_DRAWS = draws
print(f"{len(notes) * REPS} NUTS refits and {7 * 10 * REPS} exact posteriors in {time.time() - t0:.0f} s")
notes = pd.DataFrame(notes).pivot(index=["kind", "share"], columns="method")
notes
2000 NUTS refits and 7000 exact posteriors in 158 s
| divergent transitions | datasets with chains apart | ||||
|---|---|---|---|---|---|
| method | Student-t | contamination mixture | Student-t | contamination mixture | |
| kind | share | ||||
| glitches | 0 | 0 | 72 | 0 | 0 |
| 0.05 | 0 | 1 | 0 | 0 | |
| 0.1 | 0 | 0 | 0 | 0 | |
| 0.2 | 0 | 0 | 0 | 0 | |
| humidity | 0.05 | 0 | 34 | 0 | 1 |
| 0.1 | 2 | 14 | 0 | 5 | |
| 0.2 | 0 | 7 | 0 | 18 | |
| second source | 0.05 | 0 | 1 | 0 | 0 |
| 0.1 | 0 | 0 | 0 | 0 | |
| 0.2 | 12 | 1 | 5 | 3 | |
LINES = [GAUSS, HUBER, STUDENT, MIX, BDM, BDH]
fig, axes = plt.subplots(2, 3, figsize=(13.5, 7.6), sharex=True)
pos = np.arange(len(EPS))
for j, (kind, title) in enumerate(KINDS.items()):
ax = axes[0, j]
ax.axhline(MU, color=INK, lw=1.1, ls="--")
for i, label in enumerate(LINES):
means = np.array([SWEEP[(kind, eps)][label]["mean"] for eps in EPS]) # (shares, datasets)
lo, mid, hi = np.quantile(means, 0.1, axis=1), means.mean(axis=1), np.quantile(means, 0.9, axis=1)
x = pos + (i - 2.5) * 0.11
ax.vlines(x, lo, hi, color=COLOR[label], lw=1.6)
ax.plot(x, mid, "o-", color=COLOR[label], ms=4.5, lw=1.3, label=label.replace(", rate matched", ""))
ax.set_title(title, loc="left", fontsize=11)
ax.set_ylim({"glitches": (9.3, 10.7), "second source": (9.6, 12.3), "humidity": (9.7, 10.7)}[kind])
tidy(ax)
ax = axes[1, j]
ax.axhline(CI, color=INK, lw=1.1, ls="--")
for label in [GAUSS, HUBER, STUDENT, MIX, BD1, BDM, BDH]:
cov = [SWEEP[(kind, eps)][label]["coverage"] for eps in EPS]
ax.plot(pos, cov, "o-", color=COLOR[label], ms=4.5, lw=1.5, ls=":" if label == BD1 else "-",
label=label, mfc="white" if label == BD1 else COLOR[label])
ax.set_ylim(-0.03, 1.03)
ax.set_xticks(pos, [f"{eps:.0%}" for eps in EPS])
ax.set_xlabel("share of readings from the other process")
tidy(ax)
axes[0, 0].set_ylabel("estimated level: mean over 100 datasets,\nbar from the 10th to the 90th percentile")
axes[1, 0].set_ylabel("coverage of the 90% interval")
axes[0, 1].legend(frameon=False, fontsize=8.5, loc="upper left")
axes[1, 0].legend(frameon=False, fontsize=8, loc="lower left", ncol=2)
fig.suptitle("Estimate and coverage against the contamination fraction, by kind of contamination", x=0.01, ha="left", fontsize=12);

def sweep_table(column, kinds=KINDS):
table = {(kind, f"{eps:.0%}"): {label: SWEEP[(kind, eps)][label][column] for label in [ORACLE, GAUSS, HUBER, STUDENT, MIX, BD1, BDM, BDH]}
for kind in kinds for eps in EPS if not (eps == 0 and kind != "glitches")}
return pd.DataFrame(table).rename(columns={"glitches": "clean / glitches"}, level=0)
print("root-mean-square error of the estimated level (posterior mean), 100 datasets per column")
display(sweep_table("rmse").round(3))
print("coverage of the 90% interval (counting error about 0.03 near 0.90)")
sweep_table("coverage").round(2)
root-mean-square error of the estimated level (posterior mean), 100 datasets per column
| clean / glitches | second source | humidity | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| 0% | 5% | 10% | 20% | 5% | 10% | 20% | 5% | 10% | 20% | |
| oracle: Gaussian, good readings only | 0.099 | 0.104 | 0.106 | 0.109 | 0.104 | 0.106 | 0.109 | 0.104 | 0.106 | 0.109 |
| Gaussian | 0.099 | 0.268 | 0.348 | 0.49 | 0.457 | 0.872 | 1.643 | 0.164 | 0.276 | 0.509 |
| Huber loss, rate matched | 0.102 | 0.116 | 0.124 | 0.151 | 0.143 | 0.244 | 0.559 | 0.135 | 0.215 | 0.427 |
| Student-t | 0.1 | 0.115 | 0.129 | 0.142 | 0.117 | 0.131 | 0.475 | 0.145 | 0.242 | 0.472 |
| contamination mixture | 0.101 | 0.11 | 0.114 | 0.124 | 0.105 | 0.106 | 0.202 | 0.143 | 0.215 | 0.373 |
| beta-divergence, rate 1 | 0.109 | 0.116 | 0.122 | 0.13 | 0.115 | 0.118 | 0.12 | 0.128 | 0.183 | 0.369 |
| beta-divergence, rate matched | 0.109 | 0.117 | 0.123 | 0.13 | 0.115 | 0.119 | 0.122 | 0.127 | 0.18 | 0.361 |
| beta-divergence, beta by H-score | 0.099 | 0.11 | 0.118 | 0.127 | 0.106 | 0.112 | 0.119 | 0.154 | 0.263 | 0.501 |
coverage of the 90% interval (counting error about 0.03 near 0.90)
| clean / glitches | second source | humidity | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| 0% | 5% | 10% | 20% | 5% | 10% | 20% | 5% | 10% | 20% | |
| oracle: Gaussian, good readings only | 0.9 | 0.91 | 0.91 | 0.92 | 0.91 | 0.91 | 0.92 | 0.91 | 0.91 | 0.92 |
| Gaussian | 0.9 | 0.91 | 0.91 | 0.88 | 0.32 | 0.02 | 0 | 0.73 | 0.34 | 0.03 |
| Huber loss, rate matched | 0.88 | 0.88 | 0.87 | 0.87 | 0.77 | 0.48 | 0.07 | 0.78 | 0.55 | 0.1 |
| Student-t | 0.88 | 0.88 | 0.88 | 0.86 | 0.88 | 0.85 | 0.8 | 0.78 | 0.48 | 0.05 |
| contamination mixture | 0.91 | 0.89 | 0.91 | 0.91 | 0.92 | 0.89 | 0.91 | 0.81 | 0.68 | 0.56 |
| beta-divergence, rate 1 | 1 | 1 | 1 | 0.99 | 1 | 1 | 1 | 1 | 0.98 | 0.78 |
| beta-divergence, rate matched | 0.9 | 0.9 | 0.89 | 0.92 | 0.9 | 0.9 | 0.93 | 0.87 | 0.75 | 0.22 |
| beta-divergence, beta by H-score | 0.9 | 0.9 | 0.89 | 0.92 | 0.91 | 0.92 | 0.93 | 0.76 | 0.42 | 0.03 |
The first table is the sampler's side of the story for the two models that needed one. The Student-t fits are clean except at 20% of a second source, where five datasets had their two chains in different places. The mixture's divergent transitions are concentrated on the clean datasets and on the humidity, the two places where its second component has little or nothing to hold on to; and in a few datasets its two chains ended in different places. Both are warnings a user would see, and both are part of the cost of naming a second process that may not be there.
Now the figure, top row first: each point is the mean of the estimated level over 100 datasets and each bar runs from the 10th to the 90th percentile of the 100 estimates.
Glitches bias nobody. Every line stays on 10 and the methods differ only in the length of their bars. The Gaussian mean is three to five times as far from the truth as the oracle (an error of 0.27 to 0.49 against 0.10), and all the alternatives stay within a third of the oracle, Huber's loss a little behind the others at 20%. Coverage is near 90% for everyone, the Gaussian model included: its intervals are honest about a poor estimate.
A second source separates the methods. The Gaussian estimate climbs by $8\varepsilon$. Huber's climbs more slowly and is 0.2 too high at 10% and 0.5 at 20%: a bounded pull is still a pull, and the MAD it is scaled by grows with the contamination. The Student-t holds until 10%, with a small bias, and at 20% it gives way in part: in a few datasets its chains settle on a wide scale that takes the second source in, and its error is more than four times the oracle's. The mixture, which is the true model here, matches the oracle at 5% and 10%; at 20% a few fits with chains in two places double its error. The beta-divergence line is flat from 0 to 20%, with an error of about 0.12, a tenth above the oracle, and the matched interval covers between 90% and 93%. The version that chooses $\beta$ by the H-score does the same at a slightly lower price. At rate 1 the interval covers every time, for the reason part 4 gave.
Humidity defeats everything. All the lines rise together. The beta-divergence estimate has the smallest error at 5% and 10% (0.13 and 0.18 against the Gaussian 0.16 and 0.28), but its matched interval covers 87%, then 75%, then 22%: the sandwich calibrates the spread around the place the estimate is heading for, and that place is no longer 10. The mixture is again the true model and does no better at these shares, because 100 readings cannot separate two Gaussians 2.5 standard deviations apart when one of them holds a tenth of the data. Its intervals are the least dishonest at 20% (56%). The H-score, seeing nothing far away, picks a small $\beta$ and returns the Gaussian answer. The high coverage at rate 1 is the accident of units again, an interval twice as wide as it should be that happens to reach the truth.
So the expected lesson holds for contamination that is far from the bulk, on either side or both: no model of the outliers, no bias up to a fifth of the data, and a cost of about a tenth in accuracy at $\beta = 0.5$. It does not hold for contamination close to the bulk, where the method is the best of a bad lot and its interval is not to be trusted.
The choice. For readings that may contain far outliers of unknown kind, the rate-matched beta-divergence posterior, with $\beta$ from the H-score when a few percent of accuracy matter. Rejected: the Huber loss, whose bias under one-sided contamination grows with the share; and the Student-t as a general-purpose answer, since it starts to fail between 10% and 20%. The mixture is not rejected: when its second component is the right one it is as good as the oracle. What would change our mind: knowing what the second process is. Then the mixture, with an informative prior on its component, is the better tool, and for a shift as small as the humidity's it is the only one with a chance, given more data than we have here.
7 · Leverage: a sensor that saturates
The second test is the calibration line. On ordinary days the reference concentration is around 5 (standard deviation 1.5) and the sensor reads $1 + 2x$ plus noise of standard deviation 1. On a share $\varepsilon$ of days the air is very dirty, the reference shows about 15, and the sensor saturates: it reports about 17, where the line would say 31.
These are leverage points: they are far away in $x$, not only in $y$. E131 met them in the star cluster CYG OB1 and found that a Student-t likelihood did nothing for them. The reason carries over to every method that judges a point by its residual, and the beta-divergence loss is one: a line tilted towards the far points leaves them with small residuals, and then there is nothing to discount. Whether the method ends on the tilted line or on the sensor's line is a question about two valleys of the same loss, and the flat tails of part 2 are what make room for two.
So the start matters, and we control it. Every run samples the same posterior, with the priors $\mathcal N(0, 100)$ on the level at the median $x$, $\mathcal N(0, 10)$ on the slope and Half-Normal(10) on $\sigma$; only the place where the chains begin differs.
- A robust start: Siegel's repeated-median line (Siegel 1982), for each point the median of its slopes to all the others, then the median of those. It tolerates up to half the points being bad, and it is what we recommend and report.
- The least-squares start, the natural one that is not robust: with a large scale every one of these losses behaves like least squares.
- The true line, for diagnosis only, at 10% and 20%: if a run started on the right answer walks away from it, the posterior itself prefers the wrong line.
The mixture's second component is a level and a spread for the reading that do not depend on $x$, as in E131: it names "a cluster of readings somewhere else", which is what saturation produces. The Huber posterior has a single valley, so it gets one start, at its own pilot estimate. The matched rate of the beta-divergence line is computed for the slope, at the posterior means of the rate-1 fit from the same start. The Gaussian posterior of the slope is in closed form (a Student-t around least squares), checked against NUTS in the first lines of output.
A_TRUE, B_TRUE = 1.0, 2.0
X_MEAN, X_SD, X_HIGH, Y_SATURATED = 5.0, 1.5, 15.0, 17.0
def simulate_lines(seed, reps, n=N):
"""Clean pairs, the uniform numbers that decide which days are replaced, and the saturated days."""
rng = np.random.default_rng(seed)
x = X_MEAN + X_SD * rng.standard_normal((reps, n))
y = A_TRUE + B_TRUE * x + SIGMA * rng.standard_normal((reps, n))
u = rng.random((reps, n))
return x, y, u, X_HIGH + rng.standard_normal((reps, n)), Y_SATURATED + SIGMA * rng.standard_normal((reps, n))
def saturate(world, eps, reps=None):
x, y, u, x_high, y_sat = world
bad = u[:reps] < eps
return np.where(bad, x_high[:reps], x[:reps]), np.where(bad, y_sat[:reps], y[:reps]), bad
def design(x):
return np.stack([np.ones_like(x), x], axis=-1)
def least_squares(x, y):
b = ((x - x.mean()) * (y - y.mean())).sum() / ((x - x.mean()) ** 2).sum()
return y.mean() - b * x.mean(), b
def repeated_median(x, y):
"""Siegel's repeated-median line: for each point the median slope to the others, then the median of those."""
with np.errstate(divide="ignore", invalid="ignore"):
slopes = (y[None, :] - y[:, None]) / (x[None, :] - x[:, None])
slopes[~np.isfinite(slopes)] = np.nan
b = np.nanmedian(np.nanmedian(slopes, axis=1))
return np.median(y - b * x), b
def gaussian_line(x, y):
"""Slope of the Gaussian model under flat priors: quantile draws of a Student-t around least squares."""
a, b = least_squares(x, y)
s2 = ((y - a - b * x) ** 2).sum() / (len(x) - 2)
return b + np.sqrt(s2 / ((x - x.mean()) ** 2).sum()) * stats.t.ppf(QUANTILES, len(x) - 2)
def line_start(x, y, how):
"""Data, start and sampler units for a line; `how` is "robust", "ls" or "truth" (the true line, for diagnosis only).
The units come from the robust line whichever start is used, so that runs from different starts
sample the same density in the same coordinates and their log-densities can be compared."""
a_r, b_r = repeated_median(x, y)
s_r = robust_scale(y - a_r - b_r * x)
a, b = {"robust": (a_r, b_r), "truth": (A_TRUE, B_TRUE)}.get(how) or least_squares(x, y)
xc = np.median(x)
return dict(x=x, y=y, x_centre=xc, start_level=a + b * xc, start_slope=b, start_scale=robust_scale(y - a - b * x),
unit_level=0.3 * s_r, unit_slope=0.3 * s_r / robust_scale(x))
def huber_line(x, y, start):
"""Huber's M-estimate of the line from the robust start (scale fixed), its matched rate for the slope, and the new start."""
X, s = design(x), start["start_scale"]
coef = np.array([start["start_level"] - start["start_slope"] * start["x_centre"], start["start_slope"]])
for _ in range(100):
res = (y - X @ coef) / s
w = np.where(np.abs(res) <= C_HUBER, 1.0, C_HUBER / np.maximum(np.abs(res), 1e-12))
coef = np.linalg.solve((X * w[:, None]).T @ X, (X * w[:, None]).T @ y)
rate = huber_rate((y - X @ coef) / s, X, k=1)
return dict(start, start_level=coef[0] + coef[1] * start["x_centre"], start_slope=coef[1], rate=rate)
def fit_line(method, x, y, how="robust", seed=RANDOM_SEED, rate=None, **sampler):
"""One NUTS fit of a line. Returns the trace and the values it was started with."""
start = line_start(x, y, how)
if method == "huber":
start = huber_line(x, y, start)
elif rate is not None:
start["rate"] = rate
return nuts(COMPILED_LINE[method], seed, **start, **sampler), start
def slope_rate(trace, x, y):
"""Matched rate for the slope of the beta-divergence line, at the posterior means of a rate-1 fit."""
a, b, sigma = (float(trace.posterior[k].mean()) for k in ("intercept", "slope", "sigma"))
rate = float(beta_rate(y - a - b * x, sigma, BETA, design(x), k=1))
return rate if np.isfinite(rate) and rate > 0 else 1.0
def refit_lines(method, X, Y, how="robust", matched=False):
"""NUTS on every dataset: slope draws (500, rows), mean intercepts, mean log-density, divergences, split chains."""
out = dict(draws=np.empty((500, len(X))), intercept=np.empty(len(X)), logp=np.empty(len(X)), div=0, split=0)
for r in range(len(X)):
trace, _ = fit_line(method, X[r], Y[r], how, RANDOM_SEED + r)
if matched:
trace, _ = fit_line(method, X[r], Y[r], how, RANDOM_SEED + r, rate=slope_rate(trace, X[r], Y[r]))
slope = trace.posterior["slope"].values
out["draws"][:, r] = slope.ravel()
out["intercept"][r] = float(trace.posterior["intercept"].mean())
out["logp"][r] = float(trace.sample_stats["logp"].mean())
out["div"] += int(trace.sample_stats["diverging"].sum())
out["split"] += abs(slope[0].mean() - slope[1].mean()) > 0.3
return out
LINE_WORLD = simulate_lines([RANDOM_SEED, 2], REPS)
x_line, y_line, bad_line = (v[0] for v in saturate(LINE_WORLD, 0.10, 1))
COMPILED_LINE = {method: nutpie.compile_pymc_model(robust_model(method, y_line, x_line)) for method in ("gauss", "mixture", "student", "beta", "huber")}
trace, _ = fit_line("gauss", x_line, y_line, "ls", draws=1000, tune=500, chains=4)
q_nuts, q_exact = np.quantile(trace.posterior["slope"].values, [0.05, 0.5, 0.95]), np.quantile(gaussian_line(x_line, y_line), [0.05, 0.5, 0.95])
print(f"bench line, {bad_line.sum()} saturated days of {N}: Gaussian slope 5% / 50% / 95% closed form {q_exact[0]:.3f} / {q_exact[1]:.3f} / {q_exact[2]:.3f}"
f" NUTS {q_nuts[0]:.3f} / {q_nuts[1]:.3f} / {q_nuts[2]:.3f} (truth {B_TRUE:.0f})")
print(f"least-squares slope {least_squares(x_line, y_line)[1]:.2f}; repeated-median slope {repeated_median(x_line, y_line)[1]:.2f}; "
f"largest residual of a saturated day from the least-squares line, in residual sd: "
f"{np.abs((y_line - np.polyval(np.polyfit(x_line, y_line, 1), x_line))[bad_line]).max() / (y_line - np.polyval(np.polyfit(x_line, y_line, 1), x_line)).std(ddof=2):.1f}")
bench line, 8 saturated days of 100: Gaussian slope 5% / 50% / 95% closed form 0.814 / 0.927 / 1.041 NUTS 0.813 / 0.928 / 1.044 (truth 2) least-squares slope 0.93; repeated-median slope 1.98; largest residual of a saturated day from the least-squares line, in residual sd: 1.9
RIGHT = lambda mean: np.abs(mean - B_TRUE) < 0.5 # the fitted line is the sensor's line, not the one through the saturated days
LINE, line_rows, mode_rows = {}, [], []
t0 = time.time()
for eps in EPS:
X, Y, bad = saturate(LINE_WORLD, eps)
fits = {GAUSS: dict(draws=np.stack([gaussian_line(x, y) for x, y in zip(X, Y)], axis=1)),
ORACLE: dict(draws=np.stack([gaussian_line(x[~b], y[~b]) for x, y, b in zip(X, Y, bad)], axis=1)),
HUBER: refit_lines("huber", X, Y), STUDENT: refit_lines("student", X, Y), MIX: refit_lines("mixture", X, Y),
BD1: refit_lines("beta", X, Y), BDM: refit_lines("beta", X, Y, matched=True)}
from_ls = {label: refit_lines(METHOD[label], X, Y, "ls") for label in (STUDENT, MIX, BD1)} if eps > 0 else {}
from_truth = {label: refit_lines(METHOD[label], X, Y, "truth") for label in (STUDENT, MIX, BD1)} if eps >= 0.10 else {}
for label, fit in fits.items():
fit.update(summary(fit["draws"], B_TRUE))
line_rows.append({"share": f"{eps:.0%}", "method": label, "bias": fit["bias"], "RMSE": fit["rmse"], "coverage": fit["coverage"],
"width": fit["width"], "right line": RIGHT(fit["mean"]).mean(), "divergences": fit.get("div", 0),
"chains apart": int(fit.get("split", 0))})
for label, fit in from_ls.items():
runs = [fits[label], fit] + ([from_truth[label]] if from_truth else []) # robust, least squares, true line
means, logps = np.array([run["draws"].mean(0) for run in runs]), np.array([run["logp"] for run in runs])
highest = means[logps.argmax(0), np.arange(REPS)] # the run with the highest log-density
mode_rows.append({"share": f"{eps:.0%}", "method": label, "robust start": RIGHT(means[0]).mean(),
"least-squares start": RIGHT(means[1]).mean(),
"started at the true line": RIGHT(means[2]).mean() if from_truth else np.nan,
"the two starts end apart": np.mean(np.abs(means[0] - means[1]) > 0.3),
"run with the highest log-density": RIGHT(highest).mean()})
LINE[eps] = fits
print(f"{(len(EPS) * 5 + 3 * 3 + 2 * 3) * REPS} NUTS fits in {time.time() - t0:.0f} s")
line_table = pd.DataFrame(line_rows).set_index(["share", "method"])
line_table.round(3)
3500 NUTS fits in 126 s
| bias | RMSE | coverage | width | right line | divergences | chains apart | ||
|---|---|---|---|---|---|---|---|---|
| share | method | |||||||
| 0% | Gaussian | 0.005 | 0.069 | 0.91 | 0.222 | 1 | 0 | 0 |
| oracle: Gaussian, good readings only | 0.005 | 0.069 | 0.91 | 0.222 | 1 | 0 | 0 | |
| Huber loss, rate matched | 0.005 | 0.071 | 0.89 | 0.228 | 1 | 0 | 0 | |
| Student-t | 0.005 | 0.07 | 0.94 | 0.22 | 1 | 1 | 0 | |
| contamination mixture | 0.005 | 0.068 | 0.92 | 0.223 | 1 | 16 | 0 | |
| beta-divergence, rate 1 | 0.005 | 0.076 | 1 | 0.403 | 1 | 0 | 0 | |
| beta-divergence, rate matched | 0.006 | 0.076 | 0.88 | 0.232 | 1 | 0 | 0 | |
| 5% | Gaussian | -0.911 | 0.928 | 0 | 0.253 | 0.05 | 0 | 0 |
| oracle: Gaussian, good readings only | 0.005 | 0.068 | 0.9 | 0.228 | 1 | 0 | 0 | |
| Huber loss, rate matched | -0.484 | 0.559 | 0.39 | 0.806 | 0.59 | 0 | 0 | |
| Student-t | -0.151 | 0.323 | 0.73 | 0.334 | 0.86 | 0 | 9 | |
| contamination mixture | -0.001 | 0.069 | 0.88 | 0.231 | 1 | 6 | 0 | |
| beta-divergence, rate 1 | 0.003 | 0.073 | 1 | 0.427 | 1 | 0 | 0 | |
| beta-divergence, rate matched | 0.004 | 0.074 | 0.86 | 0.237 | 1 | 0 | 0 | |
| 10% | Gaussian | -1.135 | 1.139 | 0 | 0.209 | 0 | 0 | 0 |
| oracle: Gaussian, good readings only | 0.006 | 0.068 | 0.93 | 0.236 | 1 | 0 | 0 | |
| Huber loss, rate matched | -1.02 | 1.049 | 0.07 | 0.646 | 0.05 | 0 | 0 | |
| Student-t | -0.748 | 0.898 | 0.34 | 0.427 | 0.3 | 1 | 20 | |
| contamination mixture | -0.023 | 0.131 | 0.9 | 0.274 | 0.97 | 0 | 3 | |
| beta-divergence, rate 1 | -0.025 | 0.162 | 0.99 | 0.517 | 0.97 | 0 | 4 | |
| beta-divergence, rate matched | -0.028 | 0.178 | 0.85 | 0.304 | 0.95 | 0 | 5 | |
| 20% | Gaussian | -1.26 | 1.261 | 0 | 0.163 | 0 | 0 | 0 |
| oracle: Gaussian, good readings only | 0.007 | 0.075 | 0.92 | 0.25 | 1 | 0 | 0 | |
| Huber loss, rate matched | -1.283 | 1.285 | 0 | 0.165 | 0 | 0 | 0 | |
| Student-t | -1.261 | 1.267 | 0 | 0.162 | 0.01 | 1 | 0 | |
| contamination mixture | -0.306 | 0.527 | 0.8 | 0.58 | 0.62 | 0 | 29 | |
| beta-divergence, rate 1 | -0.502 | 0.769 | 0.71 | 0.7 | 0.54 | 0 | 20 | |
| beta-divergence, rate matched | -0.334 | 0.596 | 0.73 | 0.867 | 0.62 | 0 | 26 |
print("share of the 100 datasets in which the fitted slope is within 0.5 of the true slope, by where the chains started")
pd.DataFrame(mode_rows).set_index(["share", "method"]).round(2)
share of the 100 datasets in which the fitted slope is within 0.5 of the true slope, by where the chains started
| robust start | least-squares start | started at the true line | the two starts end apart | run with the highest log-density | ||
|---|---|---|---|---|---|---|
| share | method | |||||
| 5% | Student-t | 0.86 | 0.84 | NaN | 0.12 | 0.88 |
| contamination mixture | 1 | 0.86 | NaN | 0.16 | 1 | |
| beta-divergence, rate 1 | 1 | 1 | NaN | 0 | 1 | |
| 10% | Student-t | 0.3 | 0.19 | 0.34 | 0.29 | 0.36 |
| contamination mixture | 0.97 | 0.25 | 1 | 0.76 | 1 | |
| beta-divergence, rate 1 | 0.97 | 0.95 | 0.97 | 0.05 | 0.97 | |
| 20% | Student-t | 0.01 | 0 | 0.01 | 0.01 | 0.01 |
| contamination mixture | 0.62 | 0 | 0.95 | 0.91 | 0.95 | |
| beta-divergence, rate 1 | 0.54 | 0.25 | 0.58 | 0.46 | 0.49 |
fig, axes = plt.subplots(1, 3, figsize=(14, 4.5), gridspec_kw={"width_ratios": [1.05, 1, 1]})
ax = axes[0]
gx = np.array([0.5, 18.0])
ax.scatter(x_line[~bad_line], y_line[~bad_line], s=13, color=BLUE, alpha=0.6, lw=0, label="ordinary days")
ax.scatter(x_line[bad_line], y_line[bad_line], s=30, color=RED, marker="s", lw=0, label="saturated days")
ax.plot(gx, A_TRUE + B_TRUE * gx, color=INK, lw=1.2, ls="--", label="true line")
for label in (GAUSS, STUDENT, BDM):
fit = LINE[0.10][label] if label != GAUSS else None
a, b = least_squares(x_line, y_line) if label == GAUSS else (fit["intercept"][0], fit["mean"][0])
ax.plot(gx, a + b * gx, color=COLOR[label], lw=1.8, label=f"{label.replace(', rate matched', '')}: slope {b:.2f}")
ax.set_xlim(0, 18.5)
ax.set_ylim(0, 40)
ax.set_xlabel("reference concentration")
ax.set_ylabel("sensor reading")
ax.set_title("One dataset, 10% saturated days", loc="left", fontsize=11)
ax.legend(frameon=False, fontsize=8.5, loc="upper left")
tidy(ax)
ax = axes[1]
ax.axhline(B_TRUE, color=INK, lw=1.1, ls="--")
shown = [GAUSS, HUBER, STUDENT, MIX, BDM]
for i, label in enumerate(shown):
means = np.array([LINE[eps][label]["mean"] for eps in EPS])
lo, mid, hi = np.quantile(means, 0.1, axis=1), means.mean(axis=1), np.quantile(means, 0.9, axis=1)
x = pos + (i - 2) * 0.12
ax.vlines(x, lo, hi, color=COLOR[label], lw=1.6)
ax.plot(x, mid, "o-", color=COLOR[label], ms=4.5, lw=1.3, label=label.replace(", rate matched", ""))
ax.set_xticks(pos, [f"{eps:.0%}" for eps in EPS])
ax.set_xlabel("share of saturated days")
ax.set_ylabel("estimated slope: mean over 100 datasets,\nbar from the 10th to the 90th percentile")
ax.set_title("Slope against contamination (robust start)", loc="left", fontsize=11)
ax.legend(frameon=False, fontsize=8.5, loc="lower left")
tidy(ax)
ax = axes[2]
modes = pd.DataFrame(mode_rows)
for label in (STUDENT, MIX, BD1):
sub = modes[modes["method"] == label]
ax.plot(pos[1:], sub["robust start"], "o-", color=COLOR[label], lw=1.8, label=label)
ax.plot(pos[1:], sub["least-squares start"], "o:", color=COLOR[label], lw=1.8, mfc="white")
ax.plot([], [], "o-", color=MUTED, lw=1.8, label="from the robust start")
ax.plot([], [], "o:", color=MUTED, lw=1.8, mfc="white", label="from the least-squares start")
ax.set_xticks(pos[1:], [f"{eps:.0%}" for eps in EPS[1:]])
ax.set_ylim(-0.03, 1.03)
ax.set_xlabel("share of saturated days")
ax.set_ylabel("share of datasets fitted with the right line")
ax.set_title("The start decides", loc="left", fontsize=11)
ax.legend(frameon=False, fontsize=8, loc="lower left")
tidy(ax);

The bench dataset in the left panel shows the mechanism. Eight saturated days in a hundred pull the least-squares slope from 2 down to 0.93, and from that line the worst of them is 1.9 residual standard deviations away: nothing a residual plot would flag. The repeated-median slope is 1.98.
The first table gives, for each share of saturated days, the slope from the robust start. With no contamination every method has the oracle's error, the beta-divergence about a tenth more. From there on:
- The Gaussian and Huber posteriors follow the saturated days at once. Huber's loss, the most classical robust device of all, puts the slope 0.5 too low at 5% and 1.0 too low at 10%: a bounded pull multiplied by a large leverage is a large pull.
- The Student-t fits the right line in 86% of the datasets at 5%, in 30% at 10% and in 1% at 20%. This is the E131 result again, on simulated data, and it sets in early.
- The mixture and the beta-divergence posterior both fit the right line in every dataset at 5%, with an error close to the oracle's, and in 95 to 97% at 10%. At 20% they are down to about six datasets in ten for the mixture and the matched beta-divergence, and about half for the beta-divergence at rate 1.
So the answer to the question E131 left open is: no, the beta-divergence posterior does not fail where the Student-t does, and yes, it fails further on. In this design it protects the slope against 5% and 10% of leverage points and loses it for something like half the datasets at 20%.
The second table and the right panel say how much of this is the posterior and how much is the sampler, and the answer differs by method. Each row gives the share of right lines by where the chains started, and in the last column the share for whichever run reached the highest log-density, which is our stand-in for the deeper valley.
For the Student-t it is the posterior. Started on the true line at 10%, it stays there in a third of the datasets and walks away in the rest, and the deepest run is the wrong line about as often. Its likelihood prefers the tilted line, as it did for the stars.
For the mixture it is the sampler. At 10% the deepest run is the right line in every dataset, and the chains find it in 97% from the robust start and in a quarter from least squares. At 20% the right line is still the deeper valley in 95% of the datasets, the run started there nearly always stays there, and the chains from the repeated-median start reach it in only 62%. The model that names the problem has the right posterior and is hard to sample.
For the beta-divergence the start hardly matters up to 10% (97% and 95%). At 20% it is the posterior that gives way: started on the true line the chains stay in 58% of the datasets, and the deepest run is the right line in about half. With a fifth of the points far out in $x$ and off the line, a line through both groups with a wider $\sigma$ scores as well as the sensor's line, and which valley is deeper becomes a matter of the particular dataset. The bars at 20% in the middle panel are that coin toss.
One more number from the first table: the rate-matched interval of the beta-divergence slope covers 88%, 86% and 85% at 0, 5 and 10%, a little under its target and within two counting errors of it. The plug-in sandwich is estimated from 100 points and is slightly optimistic for a slope; it is still far closer than rate 1, which covers every time with intervals nearly twice as wide.
The choice. Start robust losses and mixtures from a robust fit, run more than one chain, and look at the chains one by one; with the repeated-median start the beta-divergence posterior is our choice for a line with up to a tenth of bad points of unknown kind. Rejected: the default start, which turns a method that works into one that does not without a single warning from r_hat when all chains fall into the same wrong valley. What would change our mind: a fifth or more of the points with leverage. Then no residual-based loss is safe and the contamination has to be modelled, or the design fixed.
8 · The scoreboard
One setting gets every number in one table: the level, with 10% of readings from a second source, the setting of the bench dataset. Error, coverage and width are over the 100 datasets of part 6 (NUTS refits for the mixture and the Student-t, exact posteriors for the rest). Time, memory and effective sample size are those of the bench fits of part 3, compilation included. The H-score row has no NUTS behind it: its time is that of ten exact posteriors on a grid, and it reports no effective sample size, since it has no chains.
for label in sb.table().index:
sb.score(label, {"level": BOARD_DRAWS[label]}, ess=ESS.get(label))
board = sb.table()
board
| seconds | peak_gb | added_gb | ess | ess_per_s | rmse | coverage | width | |
|---|---|---|---|---|---|---|---|---|
| method | ||||||||
| Gaussian | 2.845 | 0.4511 | 0.1366 | 3863 | 1358 | 0.8718 | 0.02 | 0.8713 |
| contamination mixture | 1.956 | 0.4765 | 0.02485 | 5643 | 2885 | 0.1064 | 0.89 | 0.3416 |
| Student-t | 1.687 | 0.5004 | 0.02356 | 3412 | 2023 | 0.1312 | 0.85 | 0.394 |
| beta-divergence, rate 1 | 2.066 | 0.5216 | 0.02089 | 3034 | 1468 | 0.1181 | 1 | 0.658 |
| beta-divergence, rate matched | 1.811 | 0.5467 | 0.02466 | 3822 | 2111 | 0.119 | 0.9 | 0.3868 |
| Huber loss, rate matched | 1.482 | 0.5626 | 0.0155 | 1821 | 1229 | 0.2438 | 0.48 | 0.4188 |
| beta-divergence, beta by H-score | 0.03709 | 0.9029 | 0.0007373 | NaN | NaN | 0.1118 | 0.92 | 0.3707 |
sb.plot(columns=("seconds", "ess_per_s", "rmse", "coverage", "width"), highlight=[BDM, BDH]);

Error splits the table in three. The Gaussian posterior is off by 0.87. Huber's loss cuts that to 0.24 and stops there. The other five rows are between 0.11 and 0.13, where the oracle of part 6 has 0.106: the mixture on the oracle's own figure, the H-score version of the beta-divergence next, then the fixed $\beta = 0.5$ at 0.12 and the Student-t at 0.13.
Coverage and width have to be read together. The mixture and the two matched beta-divergence rows are near 90% with intervals of 0.34 to 0.39. The Student-t is slightly short at 85%. The beta-divergence posterior at rate 1 covers 100% with an interval of 0.66: the right centre and nearly twice the width it needs. Huber's interval is as narrow as the good ones and covers 48%, because it is narrow around the wrong place.
Time is not a consideration at this size. A first fit takes a few seconds for every model, most of it compilation, and all of them deliver several hundred effective draws a second or more. The two generalised posteriors are no harder for NUTS than the models with a likelihood. The mixture, the model that has to find a second component, is not slower here either; its cost was the divergent transitions and split chains of part 6, which this table does not show.
9 · Real gross errors: telephone calls and stars
Two small datasets from Rousseeuw and Leroy (1987), each with a documented reason for its outliers and each of a different kind.
International telephone calls from Belgium, 1950 to 1973. One number a year, in tens of millions of calls. Six of the 24 values are far above the rest. Purkayastha and Basu (2020), who reanalyse the table, give the reason as Rousseeuw and Leroy state it: from 1964 to 1969 another recording system was in use, which gave the total number of minutes of these calls instead of their number, and 1963 and 1970 are partly affected. (We quote the paper; we did not consult the book.) These are gross errors in the response, all on one side, a quarter of the data or a third with the two partial years, more than anything we simulated. They are not leverage points: they sit inside the range of years. The known answer is the line through the 16 unaffected years.
The stars of CYG OB1, from E131: log light intensity against log surface temperature for 47 stars, four of which are giants, cool and bright, far to the left of the others. These are leverage points, 9% of the data, and the reference is the line through the other 43.
Each dataset is fitted with every method from the robust start and, for the three that can have two valleys, from the least-squares start as well: four chains of 1,000 draws after 1,000 warm-up steps, with the compiled models of part 7 and $\beta = 0.5$.
data.describe("e133_telef")
calls = data.load("e133_telef")
data.describe("e131_stars_cyg")
stars = data.load("e131_stars_cyg")
REAL = {"telephone calls": dict(x=calls["year"].to_numpy() - 1950.0, y=calls["calls"].to_numpy(),
good=(calls["recording"] == "calls").to_numpy()),
"stars": dict(x=stars["log_te"].to_numpy(), y=stars["log_light"].to_numpy(), good=(stars["giant"] == 0).to_numpy())}
print()
print(calls.groupby("recording")["calls"].agg(["count", "min", "max"]).to_string())
def real_fits(x, y, good):
"""Every method on one real dataset, from the robust start and from least squares: 4 chains of 1,000 draws."""
rows = {}
ref = gaussian_line(x[good], y[good])
rows["reference: Gaussian, documented errors removed"] = dict(slope=ref.mean(), lo=np.quantile(ref, 0.05), hi=np.quantile(ref, 0.95))
for how in ("robust", "least squares"):
for label in (GAUSS, HUBER, STUDENT, MIX, BD1, BDM):
if how == "least squares" and label in (GAUSS, HUBER):
continue # one mode: the start cannot matter
rate = slope_rate(pilot, x, y) if label == BDM else None
trace, _ = fit_line(METHOD[label], x, y, "robust" if how == "robust" else "ls", rate=rate, draws=1000, tune=1000, chains=4)
if label == BD1:
pilot = trace
slope = trace.posterior["slope"].values
rows[f"{label} | {how} start"] = dict(
slope=slope.mean(), lo=np.quantile(slope, 0.05), hi=np.quantile(slope, 0.95),
intercept=float(trace.posterior["intercept"].mean()), chains=np.round(slope.mean(1), 2).tolist(),
shares=[float(np.mean(slope < 0)), float(np.mean((slope >= 0) & (slope < 1))), float(np.mean(slope >= 1))],
r_hat=float(az.rhat(trace.posterior["slope"].to_dataset())["slope"]), divergences=int(trace.sample_stats["diverging"].sum()),
note=f"rate {rate:.2f}" if rate else f"nu {float(trace.posterior['nu'].median()):.1f}" if label == STUDENT else "")
return rows
REAL_FITS = {}
for name, d in REAL.items():
REAL_FITS[name] = real_fits(d["x"], d["y"], d["good"])
print(f"\n{name}: slope and 90% interval; least-squares slope on all points {least_squares(d['x'], d['y'])[1]:.3f}, "
f"repeated-median slope {repeated_median(d['x'], d['y'])[1]:.3f}")
print(pd.DataFrame(REAL_FITS[name]).T.drop(columns=["intercept", "shares"]).fillna("").to_string(float_format=lambda v: f"{v:.3f}"))
for label in (BD1, BDM, MIX):
below, between, above = REAL_FITS["stars"][f"{label} | robust start"]["shares"]
print(f"stars, {label}: share of the slope's draws below 0: {below:.3f}, between 0 and 1: {between:.3f}, above 1: {above:.3f}")
e133_telef: One row per year (24): year (1950 to 1973), calls (international calls from Belgium, in tens of millions as the table gives them), recording ('calls' for the 16 years said to be unaffected, 'minutes' for 1964-1969 when the other recording system was in use, 'partial' for 1963 and 1970).
source: International telephone calls from Belgium, 1950-1973: the data frame `telef` of the R package robustbase (Maechler et al.), from Rousseeuw & Leroy (1987), Robust Regression and Outlier Detection, Wiley, page 26, table 2 ('taken from the Belgian Statistical Survey, published by the Ministry of Economy'), as exported by Rdatasets (https://vincentarelbundock.github.io/Rdatasets/doc/robustbase/telef.html). Licence, as read on https://cran.r-project.org/web/packages/robustbase/index.html on 2026-11-24 (robustbase 0.99-7): 'License: GPL-2 | GPL-3 [expanded from: GPL (>= 2)]'. The gross errors are not described in the package documentation; they are quoted from Purkayastha & Basu (2020, arXiv:2008.06987, appendix B.0.2), who reanalyse the table: 'due to the use of another recording system (giving the total number of minutes of these calls) from the year 1964 to 1969, the data contain heavy contamination in the y-direction in that range. The years 1963 and 1970 are also partially affected for the same reason.' DERIVED by tools/build_e133_telef.py (columns renamed, four-digit year, `recording` added; the url is the unrenamed table) - keep the cached file in data/ (md5 cecc9e6eefb1b2c43c69f303879f4ded).
url: https://vincentarelbundock.github.io/Rdatasets/csv/robustbase/telef.csv
e131_stars_cyg: One row per star (47): star (number in the table), log_te (logarithm of the effective surface temperature), log_light (logarithm of the light intensity relative to the sun's), giant (1 for the four stars the package documentation calls giants, points 11, 20, 30 and 34; the other 43 'are said to lie on the main sequence').
source: Hertzsprung-Russell diagram of the star cluster CYG OB1: the data frame `starsCYG` of the R package robustbase (Maechler et al.), from Rousseeuw & Leroy (1987), Robust Regression and Outlier Detection, Wiley, p. 27, table 3, as exported by Rdatasets (https://vincentarelbundock.github.io/Rdatasets/doc/robustbase/starsCYG.html). Licence, as read on https://cran.r-project.org/web/packages/robustbase/index.html on 2026-11-24 (robustbase 0.99-7): 'License: GPL-2 | GPL-3 [expanded from: GPL (>= 2)]'. DERIVED by tools/build_e131_stars_cyg.py (columns renamed, `giant` added; the url is the unrenamed table) - keep the cached file in data/ (md5 a7409e14efcf3810e1388c734caacb12).
url: https://vincentarelbundock.github.io/Rdatasets/csv/robustbase/starsCYG.csv
count min max
recording
calls 16 0.44 2.9
minutes 6 11.9 21.2
partial 2 2.12 4.3telephone calls: slope and 90% interval; least-squares slope on all points 0.504, repeated-median slope 0.140
slope lo hi chains r_hat divergences note
reference: Gaussian, documented errors removed 0.108 0.102 0.114
Gaussian | robust start 0.504 0.215 0.789 [0.51, 0.5, 0.51, 0.5] 1.000 0
Huber loss, rate matched | robust start 0.217 0.088 0.389 [0.22, 0.22, 0.21, 0.22] 1.004 0
Student-t | robust start 0.113 0.103 0.120 [0.11, 0.11, 0.11, 0.11] 1.002 0 nu 0.4
contamination mixture | robust start 0.110 0.101 0.120 [0.11, 0.11, 0.11, 0.11] 1.001 0
beta-divergence, rate 1 | robust start 0.109 0.099 0.119 [0.11, 0.11, 0.11, 0.11] 1.001 0
beta-divergence, rate matched | robust start 0.110 0.100 0.119 [0.11, 0.11, 0.11, 0.11] 1.001 0 rate 1.05
Student-t | least squares start 0.112 0.102 0.120 [0.11, 0.11, 0.11, 0.11] 1.002 0 nu 0.4
contamination mixture | least squares start 0.950 0.103 2.117 [1.78, 0.11, 1.8, 0.11] 1.734 1
beta-divergence, rate 1 | least squares start 0.336 -1.222 2.521 [0.62, 0.11, 0.51, 0.11] 1.617 0
beta-divergence, rate matched | least squares start 0.110 0.106 0.114 [0.11, 0.11, 0.11, 0.11] 1.002 0 rate 3.68stars: slope and 90% interval; least-squares slope on all points -0.413, repeated-median slope 2.500
slope lo hi chains r_hat divergences note
reference: Gaussian, documented errors removed 2.047 1.341 2.752
Gaussian | robust start -0.412 -0.884 0.067 [-0.41, -0.41, -0.41, -0.42] 1.000 0
Huber loss, rate matched | robust start -0.244 -1.091 0.827 [-0.27, -0.22, -0.25, -0.23] 1.001 0
Student-t | robust start -0.399 -0.926 0.137 [-0.4, -0.41, -0.38, -0.41] 1.001 0 nu 22.5
contamination mixture | robust start 2.920 1.785 3.930 [2.9, 2.92, 2.93, 2.93] 1.000 0
beta-divergence, rate 1 | robust start 2.414 -0.426 4.054 [2.3, 2.36, 2.54, 2.45] 1.011 0
beta-divergence, rate matched | robust start 2.626 0.424 3.900 [2.65, 2.67, 2.47, 2.71] 1.004 0 rate 1.31
Student-t | least squares start -0.400 -0.923 0.137 [-0.4, -0.39, -0.4, -0.41] 1.000 0 nu 22.5
contamination mixture | least squares start 1.241 -0.802 3.695 [2.92, -0.43, 2.91, -0.43] 1.733 8
beta-divergence, rate 1 | least squares start 2.264 -0.571 4.100 [2.28, 2.34, 2.32, 2.12] 1.005 0
beta-divergence, rate matched | least squares start 2.504 -0.258 3.940 [2.61, 2.32, 2.42, 2.67] 1.009 0 rate 1.21
stars, beta-divergence, rate 1: share of the slope's draws below 0: 0.080, between 0 and 1: 0.054, above 1: 0.866
stars, beta-divergence, rate matched: share of the slope's draws below 0: 0.038, between 0 and 1: 0.029, above 1: 0.933
stars, contamination mixture: share of the slope's draws below 0: 0.000, between 0 and 1: 0.002, above 1: 0.998d = REAL["telephone calls"]
trace, _ = fit_line("beta", d["x"], d["y"], "robust", draws=1000, tune=1000, chains=4, beta=1.0)
slope, sigma = trace.posterior["slope"].values, trace.posterior["sigma"].values
print(f"telephone calls, beta = 1, rate 1: slope {slope.mean():.2f}, 90% interval [{np.quantile(slope, 0.05):.1f}, {np.quantile(slope, 0.95):.1f}]; "
f"sigma, posterior mean {sigma.mean():.1f} and 95% quantile {np.quantile(sigma, 0.95):.1f} (prior: Half-Normal(10), 95% quantile {stats.halfnorm.ppf(0.95, scale=10):.1f})")
fig, axes = plt.subplots(2, 2, figsize=(13.5, 8.6), gridspec_kw={"width_ratios": [1, 1.2]})
SHOW = {GAUSS: f"{GAUSS} | robust start", STUDENT: f"{STUDENT} | robust start", MIX: f"{MIX} | robust start", BDM: f"{BDM} | robust start"}
for i, (name, d) in enumerate(REAL.items()):
fits = REAL_FITS[name]
ax = axes[i, 0]
x, y, good = d["x"], d["y"], d["good"]
shift = 1950 if name == "telephone calls" else 0
ax.scatter(x[good] + shift, y[good], s=22, color=BLUE, label="as documented: good")
ax.scatter(x[~good] + shift, y[~good], s=40, color=RED, marker="s" if name == "telephone calls" else "*",
label="other recording system (or partly)" if name == "telephone calls" else "giants")
gx = np.array([x.min() - 0.02 * np.ptp(x), x.max() + 0.02 * np.ptp(x)])
a_ref, b_ref = least_squares(x[good], y[good])
ax.plot(gx + shift, a_ref + b_ref * gx, color=INK, lw=1.2, ls="--", label="reference")
for label, key in SHOW.items():
ax.plot(gx + shift, fits[key]["intercept"] + fits[key]["slope"] * gx, color=COLOR[label], lw=1.7,
ls=":" if label == STUDENT else "-", label=label.replace(", rate matched", ""))
ax.set_ylim(y.min() - 0.1 * np.ptp(y), y.max() + 0.1 * np.ptp(y))
ax.set_xlabel("year" if name == "telephone calls" else "log surface temperature")
ax.set_ylabel("international calls, tens of millions" if name == "telephone calls" else "log light intensity")
ax.set_title("Belgium, 1950-1973: six years in another unit" if name == "telephone calls" else "CYG OB1: four giants with leverage",
loc="left", fontsize=11)
ax.legend(frameon=False, fontsize=8.5, loc="upper left" if name == "telephone calls" else "upper center")
tidy(ax)
ax = axes[i, 1]
keys = list(fits)
ref = fits[keys[0]]
ax.axvspan(ref["lo"], ref["hi"], color=LIGHT, alpha=0.5, lw=0)
ax.axvline(ref["slope"], color=INK, lw=1, ls="--")
for j, key in enumerate(keys):
row = fits[key]
label = key.split(" | ")[0]
color = COLOR.get(label, INK)
ax.plot([row["lo"], row["hi"]], [j, j], color=color, lw=2.2, ls=":" if key.endswith("least squares start") else "-")
ax.plot([row["slope"]], [j], "o", color=color, ms=5.5, mfc="white" if key.endswith("least squares start") else color)
ax.set_yticks(range(len(keys)), [k.replace(" | robust start", "").replace(" | least squares start", " (least-squares start)")
.replace("reference: Gaussian, documented errors removed", "reference: documented errors removed") for k in keys], fontsize=8.5)
ax.set_ylim(len(keys) - 0.5, -0.5)
lim = (-0.05, 0.85) if name == "telephone calls" else (-1.6, 4.6)
ax.set_xlim(*lim)
ax.set_xlabel("slope, with 90% interval" + ("" if name == "telephone calls" else " (clipped to the axis)"))
tidy(ax, grid="x");
telephone calls, beta = 1, rate 1: slope -0.03, 90% interval [-16.5, 16.3]; sigma, posterior mean 10.6 and 95% quantile 21.0 (prior: Half-Normal(10), 95% quantile 19.6)

Telephone calls. The Gaussian slope is 0.50, nearly five times the reference of 0.108. Huber's is 0.22: with a quarter of the points pulling one way, it goes a quarter of the way. The Student-t, the mixture and both beta-divergence posteriors all recover the reference, 0.11 with an interval from 0.10 to 0.12, and their lines in the left panel cannot be told apart from it. The Student-t does it with 0.4 degrees of freedom, a distribution heavier-tailed than a Cauchy, which is what it takes to absorb six values around a hundred standard deviations out. For the beta-divergence, Purkayastha and Basu (2020) report the same slope of 0.11 from the minimum-divergence estimate at this $\beta$. The matched rate is 1.05: the residual scale of these data happens to be about 0.15 in their units, close to the value at which part 4 found rate 1 to be calibrated. That is luck, and expressing the calls in millions would undo it.
The start matters here too. From least squares the Student-t finds the same answer, but in our run two of the four chains of the mixture and two of the beta-divergence at rate 1 stay on a steep line, with r_hat at 1.7 and 1.6. A user would see that. The danger is the case where all four go the same way.
The line printed above the figure is the plateau of part 4 made visible. With $\beta = 1$ and 24 points, the beta-divergence posterior at rate 1 has a slope interval from $-16$ to 16, which is the 90% interval of the slope's $\mathcal N(0, 10)$ prior, and a scale that follows its Half-Normal(10) prior: the region where the model ignores the data has more mass than the region near the fit. With $\beta = 0.5$ the same data give a sharp answer. A bounded loss needs enough data, or a small enough $\beta$, to outweigh its own flat tail.
Stars. The Gaussian slope is $-0.41$ against a reference of 2.05, and the Student-t agrees with it ($-0.40$, with 22 degrees of freedom, a Gaussian in all but name), as E131 found. Huber's loss does no better. The mixture finds the giants and gives 2.9, with an interval from 1.8 to 3.9 that contains the reference. The beta-divergence posterior is on the same side: 2.4 at rate 1 and 2.6 with the matched rate, and much the same from the least-squares start, where the estimate of Purkayastha and Basu is 2.9. But look at its interval, from $-0.4$ to 4.1 at rate 1 and from 0.4 to 3.9 matched. With 47 stars the two valleys are not far apart in height and the chains visit both: 8% of the draws at rate 1 have a negative slope, 4% with the matched rate, and none of the mixture's. So on the data where E131 saw the Student-t fail, the beta-divergence posterior does not fail, and it is less sure of itself than the model that names the giants.
The choice. For the telephone calls, any of the three methods that found 0.11, and the beta-divergence posterior if nothing is known about the bad years. For the stars, the mixture. Rejected: Huber's loss in both cases, and the Student-t for the stars. What would change our mind: for the stars, more data: the beta-divergence posterior's doubt between two lines is a small-sample effect, and the simulations of part 7 with 100 points and 10% of leverage points show it settling on the right one.
10 · Which method for which contamination
The figure collects what was measured, one row per situation and one column per method. For the level, a cell gives the error relative to the oracle that sees only the good readings and the coverage of the 90% interval. For the calibration line it gives the share of datasets fitted with the right line, from the robust start, and the coverage for the slope. For the two real datasets it gives the slope, to be read against the reference.
SHADE = {"good": "#cdeedd", "wide": "#d5e5f8", "partial": "#fbe7b3", "bad": "#f8cfcc", "none": "#f1f0ec"}
COLUMNS = [GAUSS, HUBER, STUDENT, MIX, BD1, BDM, BDH]
def simulated_cell(result, oracle):
"""Error relative to the oracle that only sees the good readings, and coverage, with a verdict."""
ratio, cov = result["rmse"] / oracle["rmse"], result["coverage"]
verdict = ("good" if 0.83 <= cov <= 0.97 else "wide" if cov > 0.97 else "partial") if ratio <= 1.3 else "partial" if ratio <= 2 else "bad"
return f"error x{ratio:.1f}\ncovers {cov:.0%}", verdict
def line_cell(result):
"""Share of datasets fitted with the right line, and coverage of the slope's interval."""
right, cov = RIGHT(result["mean"]).mean(), result["coverage"]
verdict = ("good" if 0.83 <= cov <= 0.97 else "wide" if cov > 0.97 else "partial") if right >= 0.95 else "partial" if right >= 0.5 else "bad"
return f"right line {right:.0%}\ncovers {cov:.0%}", verdict
def real_cell(fits, label):
"""Slope from the robust start against the reference: inside the interval, close to it, and not much wider."""
row, ref = fits[f"{label} | robust start"], fits["reference: Gaussian, documented errors removed"]
inside = row["lo"] <= ref["slope"] <= row["hi"]
close = abs(row["slope"] - ref["slope"]) <= ref["hi"] - ref["lo"]
wide = (row["hi"] - row["lo"]) > 3 * (ref["hi"] - ref["lo"])
verdict = "bad" if not inside else "partial" if not close else "wide" if wide else "good"
return f"slope {row['slope']:.2f}\n(ref. {ref['slope']:.2f})", verdict
cells = {}
for name, key in (("clean readings", ("glitches", 0.0)), ("glitches, 10%\n(symmetric, far)", ("glitches", 0.10)),
("second source, 10%\n(one-sided, far)", ("second source", 0.10)), ("second source, 20%", ("second source", 0.20)),
("humidity, 10%\n(one-sided, close)", ("humidity", 0.10))):
cells[name] = [simulated_cell(SWEEP[key][label], SWEEP[key][ORACLE]) for label in COLUMNS]
for eps in EPS[1:]:
cells[f"saturation, {eps:.0%}\n(leverage, slope)"] = [line_cell(LINE[eps][label]) for label in COLUMNS[:-1]] + [("not run", "none")]
cells["telephone calls\n(6 to 8 years of 24)"] = [real_cell(REAL_FITS["telephone calls"], label) for label in COLUMNS[:-1]] + [("not run", "none")]
cells["stars of CYG OB1\n(4 giants of 47)"] = [real_cell(REAL_FITS["stars"], label) for label in COLUMNS[:-1]] + [("not run", "none")]
fig, ax = plt.subplots(figsize=(13.8, 9.2))
for i, (row, values) in enumerate(cells.items()):
ax.text(-0.6, i, row, ha="right", va="center", fontsize=9.5, color=INK, linespacing=1.3)
for j, (text, verdict) in enumerate(values):
ax.add_patch(plt.Rectangle((j - 0.47, i - 0.44), 0.94, 0.88, fc=SHADE[verdict], ec="white", lw=1.5))
ax.text(j, i, text, ha="center", va="center", fontsize=8.8, color=INK if verdict != "none" else MUTED, linespacing=1.35)
for j, col in enumerate(COLUMNS):
ax.text(j, -0.62, col.replace(", ", ",\n").replace("contamination mixture", "contamination\nmixture"), ha="center", va="bottom",
fontsize=9.3, fontweight="bold", color=INK, linespacing=1.2)
for k, (verdict, text) in enumerate((("good", "does the job"), ("wide", "right place, interval too wide"),
("partial", "helps, not enough"), ("bad", "wrong"), ("none", "not run here"))):
ax.add_patch(plt.Rectangle((-1.9 + 1.75 * k, len(cells) - 0.32), 0.22, 0.22, fc=SHADE[verdict], ec="white"))
ax.text(-1.9 + 1.75 * k + 0.3, len(cells) - 0.21, text, va="center", fontsize=9, color=INK)
ax.set_xlim(-2.5, len(COLUMNS) - 0.5)
ax.set_ylim(len(cells) + 0.05, -1.5)
ax.axis("off")
ax.set_title("When to reach for which: every contamination in this notebook against every method", loc="left", fontsize=12);

Green means the method did its job: an error within 30% of the oracle's (or the right line in at least 95% of datasets) and coverage between 83% and 97%, which is 90% give or take the counting error of 100 datasets; for the real data, an interval that contains the reference, a slope within one reference-interval width of it, and an interval at most three times as wide. Blue is the right place with an interval that is too wide. Amber helps and is not enough: an error up to twice the oracle's, the right line in at least half the datasets, or an interval that contains the reference around a slope that is off. Red is wrong.
Read down the columns. The Gaussian posterior is right on clean data and nowhere else. Huber's loss handles symmetric glitches and little more. The Student-t handles far contamination up to a tenth and vertical outliers in a regression, and fails on leverage points. The mixture is green wherever its second component matches what happened and the contamination is not too heavy. The beta-divergence posterior at rate 1 is blue across the top: the right place and an interval that reflects the units of the data. With the rate matched it is green for every far contamination we tried, for leverage points up to 10%, and for both real datasets. The humidity row has no green in it, and neither has the last row of the simulated line.
In practice we would work in this order. Plot the data; if a second process can be seen and named, write the mixture, with a prior that says what you know about it. If it cannot, fit the beta-divergence posterior from a robust start, with several chains, look at the estimate as $\beta$ varies (or let the H-score choose), match the learning rate to the sandwich for the parameter you report, and say that you did. Compare with the Gaussian fit: if the two agree, report the Gaussian one. And treat any robust answer with suspicion when the suspected contamination is close to the bulk, or when a large share of the points has leverage.
Summary
- Far contamination did not move the beta-divergence estimate, and it needed no model of the outliers. With 5, 10 or 20% of readings from a second source 8 standard deviations away, or from glitches ten times as noisy, its error stayed at about 0.12 against 0.10 for an oracle that knows which readings are good (0.13 against 0.11 at the worst), while the Gaussian mean was off by up to 1.6. Limit: one sample size (100) and Gaussian bulk data.
- There are two tuning constants, not one. The loss has the units of a density to the power $\beta$, so at learning rate 1 the interval's width depends on the units of the data: on clean data its 90% interval covered 86%, 99% or 100% as the same readings were rescaled by ten each way. Matching the rate to the sandwich gave 91% in every unit, and 89 to 93% under far contamination.
- The price of $\beta$ on clean data is small and follows a formula. The error grows by $(1+\beta)^{3/2}/(1+2\beta)^{3/4}$: 3% at 0.25, 9% at 0.5, 24% at 1. The Hyvärinen-score rule of Yonekura and Sugasawa chose $\beta$ near 0.02 on clean data and 0.15 to 0.3 under far contamination, which removed the price where there was nothing to buy.
- Contamination close to the bulk defeated every method. With readings shifted by 2.5 standard deviations, all estimates rose with the share; the beta-divergence was the least biased and its matched interval still covered only 75% at 10% and 22% at 20%. The mixture, the true model there, was no better with 100 readings.
- Huber's loss bounds the pull and does not remove it. Under one-sided contamination its bias grew with the share (0.2 at 10%, 0.5 at 20%), and with leverage points its slope was 0.5 too low at 5% and 1.0 too low at 10%.
- With leverage points the beta-divergence posterior outlasted the Student-t and then failed too. The Student-t fitted the right line in 86%, 30% and 1% of datasets at 5, 10 and 20% of saturated days; the beta-divergence posterior in 100%, about 96% and about 55%. At 20% its two valleys were about equally deep: started on the true line, the chains stayed in 58% of datasets.
- A robust loss has several valleys, and the start chooses. The mixture found the right line in 97% of datasets at 10% from a repeated-median start and in a quarter from least squares; at 20% its right valley was the deeper one in 95% of datasets and the chains reached it in 62%. Limit: we compared starts, not samplers; tempering or a mixture of starts might do better.
- On real gross errors the picture held. For the Belgian telephone calls (6 to 8 bad years in 24) the Student-t, the mixture and the beta-divergence posterior all recovered the slope of the unaffected years, 0.11, where least squares gives 0.50. For the stars of CYG OB1 the beta-divergence slope was 2.4 to 2.6 against a reference of 2.0, where the Student-t stays at $-0.4$, with an interval wide enough to show that 47 points did not settle the matter. With $\beta = 1$ and 24 points the posterior fell back on its prior.
Try it yourself
- Find the breaking point. Extend
EPSto 0.30 and 0.40 for the second source and rerun part 6 for the exact methods. At what share does the beta-divergence estimate at $\beta = 0.5$ leave 10, and does the H-score's choice of $\beta$ keep up? Then make the bad readings 4 standard deviations away instead of 8 and find the share again. - A Student-t inside the beta-divergence. Replace the Gaussian density in the
"beta"branch ofrobust_modelby a Student-t with 5 degrees of freedom. The integral term has no elementary form now: compute it by quadrature on a fixed grid inside the potential. Does the heavier-tailed model lose less on the humidity data, and what happens to the matched rate? - Leverage by design. In part 7 the ordinary days have a spread of 1.5 in $x$. Halve it and
double it (
X_SD), and redo the table of starts at 10% of saturated days. How does the share of right lines move for the Student-t and for the beta-divergence posterior, and what does that say about collecting calibration data over a wide range of concentrations?
print(f"total run time: {time.time() - T_START:.0f} s")
total run time: 368 s