Parameter estimation¶
A probabilistic ODE solver turns an ODE with unknown parameters into a Gaussian model of the data. Its marginal likelihood is the probability of the data under the ODE, the solver's numerical uncertainty and the measurement noise. It is a differentiable function of the parameters, so it can be maximized, sampled or evaluated like any other likelihood. This notebook fits two parameters of the Lotka-Volterra equations to noisy data and checks the fit against the data.
The script
examples/parameter_estimation.py
fits the single parameter of a decay in the same way.
import logging
import jax
import jax.numpy as np
import matplotlib.pyplot as plt
import numpy as onp
import optax
from matplotlib_inline.backend_inline import set_matplotlib_formats
from scipy.integrate import solve_ivp
from tueplots import bundles, cycler
from tueplots.constants.color import palettes
from ode_filters import (
IWP,
InferenceProblem,
Measurement,
ODEFilter,
ODEInformation,
PositiveReal,
fit,
fit_scipy,
gaussian_filter,
marginal_loglik,
nis,
observation_predictive,
residual_autocorrelation,
rts_smoother,
taylor_mode_initialization,
whitened_residuals,
)
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] # grey: true values and other references
The data¶
Prey $x$ and predators $y$ follow
$$\dot x = \alpha x - \beta x y, \qquad \dot y = \delta x y - \gamma y.$$
The interaction rates $\beta = 0.5$ and $\delta = 0.25$ are known. The growth
rate of the prey $\alpha$ and the death rate of the predators $\gamma$ are not.
Both populations are counted every 0.2 time units, with noise of standard
deviation 0.15. The true trajectory comes from SciPy at the tolerances
rtol = atol = 1e-11.
BETA, DELTA = 0.5, 0.25 # known
ALPHA, GAMMA = 1.0, 0.75 # to be estimated
X0 = np.array([2.0, 1.0])
NOISE = 0.15
ts = np.linspace(0.0, 20.0, 201) # the solver's grid, step 0.1
t_obs = ts[2::2] # every second node
def lotka_volterra(t, z, alpha, gamma):
x, y = z
return [alpha * x - BETA * x * y, DELTA * x * y - gamma * y]
truth = solve_ivp(
lotka_volterra,
(0.0, 20.0),
onp.asarray(X0),
args=(ALPHA, GAMMA),
t_eval=onp.asarray(t_obs),
rtol=1e-11,
atol=1e-11,
).y.T
y = truth + NOISE * jax.random.normal(jax.random.PRNGKey(0), truth.shape)
fig, ax = plt.subplots()
for i, name in enumerate(["prey $x$", "predators $y$"]):
ax.plot(t_obs, truth[:, i], color=REFERENCE, lw=2.5)
ax.plot(t_obs, y[:, i], "o", ms=2.5, color=palette[i], label=name)
ax.plot([], [], color=REFERENCE, lw=2.5, label="true trajectory")
ax.set_xlabel("$t$")
ax.set_ylabel("population")
ax.legend(loc="upper right", ncols=3)
ax.set_ylim(top=1.25 * float(y.max())) # room for the legend
plt.show()
The model¶
An InferenceProblem maps the parameters $\theta = (\alpha, \gamma)$ to the
inputs of the solver: build(theta) returns the initial state and the ODE
information. The initial derivatives depend on $\theta$, so build computes
them by Taylor-mode differentiation. The grid, the prior and the calibration
stay fixed. The calibration is "none", the recommended setting for inference,
so that the scale of the likelihood does not change with the parameters.
The data enter as a list of Measurement objects, and each measurement is
conditioned on at its grid node. Here every measurement time is a node of the
grid.
prior = IWP(q=2, d=2)
data = [Measurement(np.eye(2), y, t_obs, noise=NOISE**2)]
def build(theta):
def vf(z, *, t):
x, y = z
return np.array(
[theta["alpha"] * x - BETA * x * y, DELTA * x * y - theta["gamma"] * y]
)
m_0, P_0_sqr = taylor_mode_initialization(vf, X0, q=2)
return m_0, P_0_sqr, ODEInformation(vf, prior.E0, prior.E1)
problem = InferenceProblem(build=build, prior=prior, ts=ts)
@jax.jit
def loglik(alpha, gamma):
return marginal_loglik({"alpha": alpha, "gamma": gamma}, data, model=problem)
print(f"log-likelihood at the true parameters: {loglik(ALPHA, GAMMA):.2f}")
log-likelihood at the true parameters: 92.24
Fitting¶
fit_scipy minimizes an objective of a parameter pytree with SciPy's
quasi-Newton method L-BFGS-B, using gradients from JAX. With the rates wrapped
in PositiveReal, the optimizer works on unconstrained values (through a
softplus) and cannot propose a negative rate. The initial guess,
$\alpha = 0.8$ and $\gamma = 0.9$, deviates by 20% from each true value:
def objective(theta):
return -marginal_loglik(theta, data, model=problem)
theta_hat, optimization = fit_scipy(
objective, {"alpha": PositiveReal(0.8), "gamma": PositiveReal(0.9)}
)
alpha_hat = float(theta_hat["alpha"].unwrap())
gamma_hat = float(theta_hat["gamma"].unwrap())
print(
f"alpha = {alpha_hat:.4f} (true {ALPHA}), gamma = {gamma_hat:.4f} (true {GAMMA})"
)
print(f"{optimization.nfev} evaluations of the likelihood and its gradient")
alpha = 1.0018 (true 1.0), gamma = 0.7479 (true 0.75) 11 evaluations of the likelihood and its gradient
For comparison, the cell below runs the same fit with the object API. An
ODEFilter holds the vector field with its trainable ode_params, and fit
runs an Optax optimizer for a fixed number of steps. On a smooth,
low-dimensional problem such as this one, a first-order method such as Adam
needs more evaluations than L-BFGS-B (here 300 steps against 11 evaluations),
but first-order methods scale to many parameters and to stochastic
objectives.
def vf_params(z, params, *, t):
x, y = z
return np.array([params[0] * x - BETA * x * y, DELTA * x * y - params[1] * y])
def init_fn(params):
return taylor_mode_initialization(
lambda z, *, t: vf_params(z, params, t=t), X0, q=2
)
model = ODEFilter(
vf=vf_params, init_fn=init_fn, prior=prior, ts=ts, ode_params=np.array([0.8, 0.9])
)
fitted, losses = fit(model, data, optax.adam(0.01), steps=300)
print(
f"Adam after {losses.shape[0]} steps: alpha, gamma = {onp.round(onp.asarray(fitted.ode_params), 4)}"
)
Adam after 300 steps: alpha, gamma = [1.0018 0.7479]
The likelihood around the estimate¶
marginal_loglik is a pure JAX function, so jax.vmap evaluates it on a grid
of parameters in one call. Relative to its maximum, the contours at $-1.15$
and $-3.0$ bound the 68% and 95% likelihood-ratio regions for two parameters.
The two rates are negatively correlated. The period of the oscillation depends
approximately on their product, so a larger $\alpha$ partly compensates for a
smaller $\gamma$. The true values lie inside the 68% region:
alphas = np.linspace(0.988, 1.016, 81)
gammas = np.linspace(0.738, 0.758, 81)
landscape = jax.vmap(lambda a: jax.vmap(lambda g: loglik(a, g))(gammas))(alphas)
relative = landscape - landscape.max()
fig, ax = plt.subplots()
ax.contour(
gammas,
alphas,
relative,
levels=[-3.0, -1.15],
colors=palette[0],
linestyles=["--", "-"],
)
ax.plot([], [], color=palette[0], label="68% region")
ax.plot([], [], color=palette[0], ls="--", label="95% region")
ax.plot(GAMMA, ALPHA, "+", color=REFERENCE, ms=10, mew=2, label="true value")
ax.plot(gamma_hat, alpha_hat, "x", color=palette[1], ms=6, mew=1.5, label="estimate")
ax.set_xlabel(r"$\gamma$")
ax.set_ylabel(r"$\alpha$")
ax.legend(loc="upper right")
plt.show()
The fitted model against the data¶
At the estimate, a filter pass over the data and the smoother give the
posterior over the trajectory. The filter takes the data as measurements=,
with the noise level as an argument of solve for the checks below.
observation_predictive maps the posterior through the observation matrix,
here prior.E0, since the measurement matrix is the identity. Without the
noise, the predictive describes the uncertainty about the trajectory. With the
noise, it is the distribution of a new measurement.
def solve(alpha, gamma, noise=NOISE):
"""A filter pass with the data, assuming the given noise level."""
m_0, P_0_sqr, measure = build({"alpha": alpha, "gamma": gamma})
sensor = Measurement(np.eye(2), y, t_obs, noise=noise**2)
return gaussian_filter(
m_0, P_0_sqr, prior, measure, ts, calibration="none", measurements=[sensor]
)
result = solve(alpha_hat, gamma_hat)
posterior = rts_smoother(result)
trajectory = observation_predictive(posterior, prior.E0)
new_data = observation_predictive(posterior, prior.E0, NOISE * np.eye(2))
at_obs = onp.asarray(ts.searchsorted(t_obs))
inside = np.abs(y - new_data.m[at_obs]) <= 2.0 * new_data.std[at_obs]
print(f"std of the trajectory: {float(trajectory.std.mean()):.1e} (on average)")
print(f"std of a new measurement: {float(new_data.std.mean()):.3f}")
print(
f"measurements inside the 2-std band: {100 * float(inside.mean()):.0f}% (expected about 95%)"
)
std of the trajectory: 1.7e-03 (on average) std of a new measurement: 0.150 measurements inside the 2-std band: 94% (expected about 95%)
With the parameters fixed, the ODE determines the trajectory, and its standard deviation is the solver's numerical uncertainty, about a hundred times smaller than the noise. The spread of a new measurement therefore consists almost entirely of the noise, and the band contains about the expected fraction of the data:
fig, ax = plt.subplots()
for i, name in enumerate(["prey $x$", "predators $y$"]):
m, s = new_data.m[:, i], new_data.std[:, i]
ax.fill_between(ts, m - 2 * s, m + 2 * s, color=palette[i], alpha=0.25, lw=0)
ax.plot(ts, m, color=palette[i], label=name)
ax.plot(t_obs, y[:, i], "o", ms=2.0, color=palette[i])
ax.set_xlabel("$t$")
ax.set_ylabel("population")
ax.legend(loc="upper right", ncols=2)
ax.set_ylim(top=1.2 * float(y.max()))
plt.show()
Checking the fit¶
A high likelihood value does not show that the model is correct. The filter
provides a further test. Before each measurement it predicts the measurement,
as a Gaussian with mean result.mz_obs (the residual) and square-root
covariance result.Pz_obs_sqr. If the model is consistent with the data, the
residuals whitened by their predicted covariance, the whitened residuals,
are independent standard normal draws. We use two summaries of them:
- the normalized innovation squared (NIS), the squared norm of the whitened residual of a step, follows a $\chi^2$ distribution with as many degrees of freedom as the step has measurements, here with mean 2;
- the autocorrelation of the whitened residuals stays within about $\pm 2/\sqrt{n}$ of zero for $n$ measurements (a 95% range, so an occasional excursion is expected).
We compare the fit with two misspecified models: one that assumes a noise three times smaller than the true one, and one with the growth rate of the prey 10% too low.
# The steps that carry a measurement: step n ends at node n + 1.
has_data = onp.isin(onp.arange(1, ts.shape[0]), at_obs)
models = {
"fit": solve(alpha_hat, gamma_hat),
"noise too small": solve(alpha_hat, gamma_hat, noise=NOISE / 3),
"alpha 10% low": solve(0.9 * alpha_hat, gamma_hat),
}
residuals = {}
for name, r in models.items():
residuals[name] = whitened_residuals(r.mz_obs, r.Pz_obs_sqr)[has_data]
rho = residual_autocorrelation(residuals[name], max_lag=1)[0]
mean_nis = float(nis(r.mz_obs, r.Pz_obs_sqr)[has_data].mean())
print(
f"{name:16s} mean NIS {mean_nis:6.1f} lag-1 autocorrelation (x, y): {onp.round(onp.asarray(rho), 2)}"
)
print(f"{'':16s} expected: 2.0 and within +-{2 / onp.sqrt(has_data.sum()):.2f}")
fit mean NIS 2.1 lag-1 autocorrelation (x, y): [-0.08 -0.02]
noise too small mean NIS 18.5 lag-1 autocorrelation (x, y): [-0.08 -0.02]
alpha 10% low mean NIS 63.1 lag-1 autocorrelation (x, y): [0.93 0.89]
expected: 2.0 and within +-0.20
The fit passes both checks. The noise level that is too small inflates the NIS ninefold and leaves the residuals uncorrelated, since only the noise level of the model is wrong. The wrong rate makes the residuals large and correlated in time, because the model's trajectory drifts away from the data and stays away:
n_obs = residuals["fit"].shape[0]
lags = onp.arange(1, 11)
fig, (left, right) = plt.subplots(1, 2)
for name, color in (("fit", palette[0]), ("alpha 10% low", palette[1])):
left.plot(t_obs, residuals[name][:, 0], "o", ms=2.0, color=color, label=name)
rho = residual_autocorrelation(residuals[name], max_lag=10)[:, 0]
right.plot(lags, rho, "o-", ms=3, color=color)
for ax, bound in ((left, 2.0), (right, 2.0 / onp.sqrt(n_obs))):
ax.axhspan(-bound, bound, color=REFERENCE, alpha=0.2, lw=0)
left.set_xlabel("$t$")
left.set_ylabel("whitened residual of $x$")
right.set_xlabel("lag")
right.set_ylabel("autocorrelation")
left.legend(loc="lower left")
plt.show()
The grey bands mark the approximate 95% ranges of a consistent model. The residuals of the predators show the same pattern. Each check costs one filter pass, and it detects misfits that the likelihood value alone does not rank.
See also¶
- Bayesian posterior sampling: the full posterior over the parameters instead of a point estimate.
- Recovering a hidden input: estimating an unknown forcing function instead of a finite number of parameters.
- Selecting hyperparameters from data: which evidence to maximize, and the conditional evidence.
- The inference API.