Prediction uncertainty¶
Parameter confidence intervals (identifiability) answer how well the data determines the parameters. Often the more relevant question is how well it determines a prediction: the value of a variable, flux or derived quantity at some time, possibly in a condition that wasn't measured. A prediction can be well determined even if the parameters aren't, and the other way around.
mxlpy.identify computes likelihood-based answers to that question:
prediction_profile: the profile likelihood and confidence interval of one predictionprediction_band: pointwise confidence bands of a prediction over timevalidation_profile: whether a new data point is consistent with the calibrated modelprofile_likelihood_2d: joint confidence regions of two parameters, or of a parameter and a prediction
Unlike bands from parameter ensembles or Monte Carlo samples, these don't depend on how samples were drawn and have the right coverage even for sloppy or non-identifiable models.
import matplotlib.pyplot as plt
import numpy as np
from mxlpy import Model, Simulator, fit, fns, identify, plot
We use the SIR model of the identifiability tutorial, but only observe the first 25 days of the epidemic.
def sir() -> Model:
return (
Model()
.add_variables({"s": 0.9, "i": 0.1, "r": 0.0})
.add_parameters({"beta": 0.2, "gamma": 0.1})
.add_reaction(
"infection",
fns.mass_action_2s,
args=["s", "i", "beta"],
stoichiometry={"s": -1, "i": 1},
)
.add_reaction(
"recovery",
fns.mass_action_1s,
args=["i", "gamma"],
stoichiometry={"i": -1, "r": 1},
)
)
times = np.linspace(0, 25, 26)
truth = Simulator(sir()).simulate_time_course(times).get_result().unwrap_or_err()
rng = np.random.default_rng(42)
data = truth.variables.loc[1:, ["i", "r"]]
data = data + rng.normal(0, 0.01, data.shape)
nll = fit.GaussianNll(0.01)
res = fit.time_course(
sir(),
p0={"beta": 0.3, "gamma": 0.05},
data=data,
loss_fn=nll,
minimizer=fit.LeastSquaresMinimizer(),
).unwrap_or_err()
res.best_pars
{'beta': np.float64(0.20057059957098053),
'gamma': np.float64(0.09898402861473458)}
Prediction profiles¶
A Prediction names the predicted output, its time (None for the steady state) and optionally a condition: parameters and y0 overriding the fitted model's, or a protocol.
The prediction profile is the best objective of all parameters predicting a value z.
Thresholding it at chi2.ppf(alpha, 1) / 2 (with a likelihood loss like fit.GaussianNll) gives the confidence interval of the prediction.
Here we ask for the number of infected at day 60, long after the data ends.
prediction = identify.Prediction("i", time=60.0)
pred = identify.prediction_profile(
sir(), data, res, prediction=prediction, loss_fn=nll, transform="log"
)
_ = plot.prediction_profile(pred)
pred.ci
prediction profile: 0%| | 0/2 [00:00<?, ?it/s]
prediction profile: 50%|█████ | 1/2 [00:01<00:01, 2.00s/it]
prediction profile: 100%|██████████| 2/2 [00:01<00:00, 1.00it/s]
(0.030623608066642875, 0.034422882728003555)
The profile is traced by refits with a pseudo data point z ± σ of the prediction.
The best fit with it is also the best fit among all parameters predicting the same value, so each refit gives an exact point of the profile, whatever σ.
pred.parameters holds the refitted parameters along it, pred.z the pseudo data points.
A prediction in another condition, here a treatment doubling the recovery rate after the observed period, only needs the overriding values:
treated = identify.prediction_profile(
sir(),
data,
res,
prediction=identify.Prediction("i", time=60.0, parameters={"gamma": 0.2}),
loss_fn=nll,
transform="log",
)
treated.value, treated.ci
prediction profile: 0%| | 0/2 [00:00<?, ?it/s]
prediction profile: 50%|█████ | 1/2 [00:02<00:02, 2.25s/it]
prediction profile: 100%|██████████| 2/2 [00:02<00:00, 1.14s/it]
(0.0020775238738206634, (0.0019984258945940267, 0.002154321475948335))
Prediction bands¶
prediction_band computes the confidence interval at many times.
The default method="integrated" tracks the bounds along time: the refit at the bound of one time predicts the next one, and a few corrective refits move it onto the threshold, which is much cheaper for dense time grids.
method="pointwise" computes a full prediction profile at every time instead (in parallel) and keeps them in band.profiles.
band = identify.prediction_band(
sir(),
data,
res,
prediction="i",
times=np.linspace(0, 100, 51),
loss_fn=nll,
transform="log",
)
fig, ax = plot.prediction_band(band)
ax.scatter(data.index, data["i"], color="0.3", s=8, label="data")
ax.legend()
plt.show()
prediction band: 0%| | 0/2 [00:00<?, ?it/s]
prediction band: 50%|█████ | 1/2 [00:04<00:04, 4.77s/it]
prediction band: 100%|██████████| 2/2 [00:04<00:00, 2.38s/it]
Predictions of non-identifiable models¶
If the infection rate is the product of a contact rate c and a transmission probability beta, the data can't tell them apart: their profiles are flat.
The predictions only depend on the product, so they are just as well determined as before.
def sir_contacts() -> Model:
return (
Model()
.add_variables({"s": 0.9, "i": 0.1, "r": 0.0})
.add_parameters({"beta": 0.2, "gamma": 0.1, "c": 1.0})
.add_derived("rate", fns.mul, args=["beta", "c"])
.add_reaction(
"infection",
fns.mass_action_2s,
args=["s", "i", "rate"],
stoichiometry={"s": -1, "i": 1},
)
.add_reaction(
"recovery",
fns.mass_action_1s,
args=["i", "gamma"],
stoichiometry={"i": -1, "r": 1},
)
)
res_c = fit.time_course(
sir_contacts(),
p0={"beta": 0.3, "gamma": 0.05, "c": 1.5},
data=data,
loss_fn=nll,
minimizer=fit.LeastSquaresMinimizer(),
).unwrap_or_err()
bounds = {"beta": (1e-3, 10.0), "c": (1e-2, 100.0)}
pred_c = identify.prediction_profile(
sir_contacts(),
data,
res_c,
prediction=prediction,
loss_fn=nll,
transform="log",
bounds=bounds,
)
pred.ci, pred_c.ci
prediction profile: 0%| | 0/2 [00:00<?, ?it/s]
prediction profile: 50%|█████ | 1/2 [00:02<00:02, 2.00s/it]
prediction profile: 100%|██████████| 2/2 [00:02<00:00, 1.00s/it]
((0.030623608066642875, 0.034422882728003555), (0.030623608066718055, 0.03442288272805373))
Validation profiles¶
Before (or after) measuring a new data point, validation_profile tells which values are consistent with the calibrated model.
It adds the data point with its measurement error sigma to the fit and steps its value: a measured value is consistent if adding it increases the objective by less than the threshold (a likelihood-ratio test).
The consistent values are wider than the prediction's confidence interval, as they include the measurement error.
val = identify.validation_profile(
sir(), data, res, prediction=prediction, noise=0.01, loss_fn=nll, transform="log"
)
_ = plot.prediction_profile(val)
print(val.validation_ci)
measured = float(
Simulator(sir()).simulate(60).get_result().unwrap_or_err().variables["i"].iloc[-1]
)
val.is_consistent(measured), val.is_consistent(measured + 0.1)
validation profile: 0%| | 0/2 [00:00<?, ?it/s]
validation profile: 50%|█████ | 1/2 [00:01<00:01, 1.73s/it]
validation profile: 100%|██████████| 2/2 [00:01<00:00, 1.10it/s]
(0.012790615677440581, 0.05216639826441801)
(True, False)
Two-dimensional profiles¶
1D profiles show that a parameter is uncertain, not which others compensate for it.
profile_likelihood_2d profiles two parameters jointly, refitting all others at each point, and gives their joint confidence region (threshold chi2.ppf(alpha, 2) / 2).
With only early data, beta and gamma compensate along the initial growth rate 0.9 beta - gamma, so the region is a narrow tilted valley.
method="slices"(default) profilesx, then at each of its points profilesywithxfixed until the threshold, so no fits are spent outside the region.ycan also be aPredictionmethod="grid"refits on ann_stepsxn_stepsgrid with warm starts along each row
pl2d = identify.profile_likelihood_2d(
sir(), data.loc[:10], res, x="beta", y="gamma", loss_fn=nll
)
_ = plot.profile_likelihood_2d(pl2d)
pl2d.region().head()
profile of beta: 0%| | 0/2 [00:00<?, ?it/s]
profile of beta: 50%|█████ | 1/2 [00:01<00:01, 1.73s/it]
profile of beta: 100%|██████████| 2/2 [00:01<00:00, 1.16it/s]
slices: 0%| | 0/38 [00:00<?, ?it/s]
slices: 3%|▎ | 1/38 [00:02<01:22, 2.23s/it]
slices: 29%|██▉ | 11/38 [00:02<00:04, 6.34it/s]
slices: 55%|█████▌ | 21/38 [00:02<00:01, 13.42it/s]
slices: 100%|██████████| 38/38 [00:02<00:00, 14.89it/s]
| lower | upper | |
|---|---|---|
| beta | ||
| 0.185365 | 0.089644 | 0.089727 |
| 0.185837 | 0.088166 | 0.091686 |
| 0.186729 | 0.087345 | 0.093397 |
| 0.187725 | 0.086970 | 0.094770 |
| 0.188855 | 0.086800 | 0.096069 |
region() gives the boundary of the region as a y interval per x slice, pl2d.points all refitted points with their increase of the objective and pl2d.parameters the refitted parameters.
Points much worse than a neighbour (failed fits) are refitted from the neighbour's parameters, pl2d.n_repaired counts them.