Bayesian posterior sampling¶
Parameter estimation finds the most likely
parameters. A Bayesian analysis asks for all parameters consistent with the
data and a prior, weighted by how consistent they are. Because
marginal_loglik is a differentiable JAX function, any gradient-based sampler
can draw from that posterior. This notebook uses the No-U-Turn sampler (NUTS)
of NumPyro on the growth rate of the logistic equation,
then shows why the solver's own uncertainty has to be part of the likelihood.
The script
examples/numpyro_inference.py
is a minimal version of the first part;
examples/blackjax_inference.py
does the same with BlackJAX's NUTS, which takes the log-density as a plain
function.
import warnings
# NumPyro's progress bars, switched off below, would look for Jupyter widgets.
warnings.filterwarnings("ignore", message="IProgress not found")
import logging
import jax
import jax.numpy as np
import matplotlib.pyplot as plt
import numpyro
import numpyro.distributions as dist
from matplotlib_inline.backend_inline import set_matplotlib_formats
from numpyro.infer import MCMC, NUTS, init_to_median
from tueplots import bundles, cycler
from tueplots.constants.color import palettes
from ode_filters import (
IWP,
InferenceProblem,
Measurement,
ODEInformation,
PositiveReal,
fit_scipy,
gaussian_filter,
marginal_loglik,
taylor_mode_initialization,
)
jax.config.update("jax_enable_x64", True)
plt.rcParams.update(bundles.tue_ai_beamer())
plt.rcParams.update(cycler.cycler(color=palettes.paultol_bright))
set_matplotlib_formats("svg") # vector figures stay sharp at any size
# Fall back to the default font quietly where Roboto Condensed is not installed.
logging.getLogger("matplotlib.font_manager").setLevel(logging.ERROR)
palette = plt.rcParams["axes.prop_cycle"].by_key()["color"]
REFERENCE = palette[6] # gray: true values and other references
The data¶
A population grows logistically, $\dot x = r x (1 - x)$ from $x(0) = 0.01$, at an unknown rate $r$. It is measured five times, at $t = 2, 4, \dots, 10$, precisely: the noise has standard deviation 0.005. The truth is $r = 1.5$.
R_TRUE, X0, NOISE = 1.5, 0.01, 0.005
def logistic(t, r):
return 1.0 / (1.0 + (1.0 / X0 - 1.0) * np.exp(-r * t))
t_obs = np.linspace(2.0, 10.0, 5)
y = (
logistic(t_obs, R_TRUE)
+ NOISE * jax.random.normal(jax.random.PRNGKey(2), t_obs.shape)
)[:, None]
t_plot = np.linspace(0.0, 10.0, 201)
fig, ax = plt.subplots()
ax.plot(
t_plot, logistic(t_plot, R_TRUE), color=REFERENCE, lw=2.5, label="true solution"
)
ax.plot(t_obs, y[:, 0], "o", ms=4, color=palette[0], label="measurements")
ax.set_xlabel("$t$")
ax.set_ylabel("$x$")
ax.legend(loc="lower right")
plt.show()
The likelihood on a fine grid¶
As in Parameter estimation, an InferenceProblem
maps the parameters to the solver's inputs. make_problem also takes the
prior's diffusion xi and the calibration, which matter only later. On a grid
of 200 steps the solver's error at the measurement times is about 2e-7, four
orders of magnitude below the measurement noise, so the likelihood is in effect
that of the exact ODE solution.
def make_problem(ts, xi=1.0, calibration="none"):
prior = IWP(q=2, d=1, Xi=xi * np.eye(1))
def build(theta):
def vf(x, *, t):
return theta["r"] * x * (1.0 - x)
m_0, P_0_sqr = taylor_mode_initialization(vf, np.array([X0]), q=2)
return m_0, P_0_sqr, ODEInformation(vf, prior.E0, prior.E1)
data = [Measurement(np.eye(1), y, t_obs, noise=NOISE**2)]
return InferenceProblem(
build=build, prior=prior, ts=ts, calibration=calibration
), data
fine, fine_data = make_problem(np.linspace(0.0, 10.0, 201))
Sampling with NumPyro¶
The NumPyro model draws $r$ from a log-normal prior and adds the
log-likelihood to the joint density with numpyro.factor. NUTS then explores
the posterior using gradients that flow through the whole filter; its chain
starts at the prior median, $r = 1$.
def model(problem, data):
r = numpyro.sample("r", dist.LogNormal(0.0, 1.0))
numpyro.factor("loglik", marginal_loglik({"r": r}, data, model=problem))
def sample(problem, data, seed=0):
mcmc = MCMC(
NUTS(model, init_strategy=init_to_median),
num_warmup=1000,
num_samples=2000,
progress_bar=False,
)
mcmc.run(jax.random.PRNGKey(seed), problem, data)
return mcmc.get_samples()["r"]
r_fine = sample(fine, fine_data)
theta_hat, _ = fit_scipy(
lambda theta: -marginal_loglik(theta, fine_data, model=fine),
{"r": PositiveReal(1.0)},
)
r_hat = float(theta_hat["r"].unwrap())
print(
f"posterior: r = {float(r_fine.mean()):.3f} +- {float(r_fine.std()):.3f} (truth {R_TRUE})"
)
print(f"maximum likelihood: r = {r_hat:.3f}")
posterior: r = 1.493 +- 0.007 (truth 1.5) maximum likelihood: r = 1.493
fig, ax = plt.subplots()
ax.hist(
r_fine,
bins=40,
density=True,
color=palette[0],
alpha=0.6,
label="posterior samples",
)
ax.axvline(R_TRUE, color=REFERENCE, lw=2.5, label="true value")
ax.axvline(r_hat, color=palette[1], label="maximum likelihood")
ax.set_xlabel("growth rate $r$")
ax.set_ylabel("density")
ax.legend(loc="upper right")
plt.show()
Five precise measurements determine the rate to within half a percent. With the broad log-normal prior, the posterior is close to the likelihood, so it is centered near the maximum-likelihood estimate.
Why the solver's uncertainty matters¶
A sampler evaluates the likelihood thousands of times, and the cost of each evaluation grows linearly with the number of grid steps. A coarse grid reduces this cost but is less accurate. Take ten steps of size 1:
coarse_ts = np.linspace(0.0, 10.0, 11)
plugin, coarse_data = make_problem(coarse_ts, xi=1e-12)
def solver_mean(problem):
"""The solver's mean at the grid nodes for the true rate, without data."""
m_0, P_0_sqr, measure = problem.build({"r": R_TRUE})
return gaussian_filter(
m_0, P_0_sqr, problem.prior, measure, problem.ts, calibration="none"
).m[:, 0]
at_obs = np.searchsorted(coarse_ts, t_obs)
solver_error = np.abs(solver_mean(plugin)[at_obs] - logistic(t_obs, R_TRUE))
print(
f"solver error at the measurement times: up to {float(solver_error.max()):.3f} "
f"(measurement noise: {NOISE})"
)
spread = np.max(np.abs(solver_mean(plugin) - solver_mean(make_problem(coarse_ts)[0])))
print(f"change of the solver's mean between xi = 1e-12 and xi = 1: {float(spread):.0e}")
solver error at the measurement times: up to 0.019 (measurement noise: 0.005)
change of the solver's mean between xi = 1e-12 and xi = 1: 2e-16
The numerical error, up to 0.019, is almost four times the measurement noise
of 0.005. A classical solver would hand its trajectory to the likelihood as if
it were exact. The same happens here when the diffusion xi shrinks towards
zero: the solver's mean does not change, but it reports almost no uncertainty,
so the likelihood treats the inaccurate trajectory as the truth. We call this
the plug-in likelihood.
A probabilistic solver improves on the plug-in likelihood only if its uncertainty has the right size, and the data do not determine that size. The data cannot see the numerical error, so they always prefer the most confident solver:
def best_loglik(xi):
"""The data log-likelihood at the best rate, for a diffusion xi."""
problem, _ = make_problem(coarse_ts, xi=xi)
rates = np.linspace(1.3, 1.7, 401)
return jax.vmap(lambda r: marginal_loglik({"r": r}, coarse_data, model=problem))(
rates
).max()
for xi in (1e-12, 1.0):
print(f"xi = {xi:g}: best log-likelihood of the data {float(best_loglik(xi)):.1f}")
xi = 1e-12: best log-likelihood of the data 21.6
xi = 1: best log-likelihood of the data 8.8
The size of the numerical error is visible in the ODE residuals instead, which
measure how far each step's prediction misses the ODE. Calibration measures
exactly this (Diffusion calibration). With
calibration="dynamic" the solver estimates the diffusion from the residuals
at every step, so its error bars track its actual error. We sample $r$ three
times: on the fine grid, on the coarse grid with the plug-in likelihood, and
on the coarse grid with the calibrated solver:
calibrated, _ = make_problem(coarse_ts, calibration="dynamic")
r_plugin = sample(plugin, coarse_data)
r_calibrated = sample(calibrated, coarse_data)
for name, r in (
("fine grid", r_fine),
("coarse, plug-in", r_plugin),
("coarse, calibrated", r_calibrated),
):
print(f"{name:19s} r = {float(r.mean()):.3f} +- {float(r.std()):.3f}")
fig, ax = plt.subplots()
bins = np.linspace(1.36, 1.58, 89)
for r, color, label in (
(r_fine, palette[0], "fine grid"),
(r_plugin, palette[1], "coarse grid, plug-in"),
(r_calibrated, palette[2], "coarse grid, calibrated"),
):
ax.hist(
r, bins=bins, density=True, histtype="step", lw=1.5, color=color, label=label
)
ax.axvline(R_TRUE, color=REFERENCE, lw=2.5, label="true value")
ax.set_xlabel("growth rate $r$")
ax.set_ylabel("density")
ax.legend(loc="upper left")
plt.show()
fine grid r = 1.493 +- 0.007 coarse, plug-in r = 1.513 +- 0.005 coarse, calibrated r = 1.464 +- 0.033
The plug-in posterior excludes the true rate. It is about as narrow as the
fine-grid posterior, but it is conditioned on an inaccurate trajectory. The
calibrated solver widens the posterior until it covers both the truth and the
fine-grid posterior, so the numerical error becomes part of the uncertainty
about $r$ instead of a bias. On the coarse grid the posterior loses
information but still covers the truth; a finer grid recovers the information
at a higher cost per likelihood evaluation. On a grid as fine as the first one,
where the numerical error is negligible, the default calibration="none" is
the better choice for inference, because the likelihood's scale then does not
move with the parameters.
See also¶
- Parameter estimation: point estimates with
fit_scipyandfit, and checking a fit against the data. - Diffusion calibration: what the diffusion is and how it is estimated without sampling.
- The inference API.