AI-generated. An AI assistant drafted this page, and no maintainer has reviewed it yet. Please report errors on the issue tracker.
Tutorial 7: Working with the posterior¶
This tutorial continues from Tutorial 2, whose model and posterior it rebuilds below.
# @title Setup: install ProbPipe on Colab (run this first)
# On Google Colab, install ProbPipe and download the data; elsewhere this cell does nothing.
try:
import google.colab # noqa: F401
IN_COLAB = True
except ImportError:
IN_COLAB = False
if IN_COLAB:
import os
import urllib.request
%pip install --quiet "probpipe-core[pymc] @ git+https://github.com/TARPS-group/prob-pipe.git@main"
os.makedirs("data", exist_ok=True)
urllib.request.urlretrieve(
"https://raw.githubusercontent.com/TARPS-group/prob-pipe/main/"
"docs/tutorials/data/moose.csv",
"data/moose.csv",
)
Setup: the model and posterior from tutorial 2¶
The cells below load the data, build the model, and draw the posterior, as tutorial 2 does.
import warnings
import arviz as az
import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from probpipe import (
Beta,
LogNormal,
Poisson,
condition_on,
conditional_distribution,
function,
summarize,
mean,
standard_deviation,
variance,
quantile,
predictive_check,
sample,
workflow_run,
)
from probpipe.diagnostics import add_mcmc_diagnostics
# TensorFlow Probability warns that JAX runs in 32-bit precision, which these models use.
warnings.filterwarnings("ignore", message=r"Explicitly requested dtype float64")
# Cleaner printing for floats
np.set_printoptions(precision=3, suppress=True)
# set random seed for reproducibility
workflow_run.set_default(seed=532431)
# data
data = pd.read_csv("data/moose.csv")
years = data["year"].to_numpy()
observed_counts = jnp.asarray(data["count"], dtype=jnp.float32)
n_years = observed_counts.shape[0]
# population model
@function
def ricker(r: jax.Array, K: jax.Array, n0: float, years: int) -> jax.Array:
"""The population in each of the *years* after the year of *n0*."""
def step(N: jax.Array, _: None) -> tuple[jax.Array, jax.Array]:
N_next = N * jnp.exp(r * (1.0 - N / K))
return N_next, N_next
_, N = jax.lax.scan(step, jnp.asarray(n0, dtype=jnp.float32), None, length=years)
return N
# prior model
prior = LogNormal("K", jnp.log(350.0), 0.4) & LogNormal("r", jnp.log(0.4), 0.4) & Beta("phi", 2.0, 2.0)
prior = prior.with_label("prior")
# observation model
@conditional_distribution(given_spec=prior.event_spec)
def likelihood(K: jax.Array, r: jax.Array, phi: jax.Array, n0: float = 50.0) -> Poisson:
return Poisson("y", phi * ricker(r, K, n0, n_years))
# the full model
model = likelihood & prior
# observed data
observed = {"y": observed_counts}
# assign a shorter label, for brevity
model = model.with_label("model")
# condition on observation
posterior = condition_on(model, observed).with_label("posterior")
1. The posterior is just another distribution¶
All of the operations we explored in tutorial 1 can also be applied to the posterior,
just like any other distribution in ProbPipe. Let's take a look at the structure of posterior
and apply some operations to it.
posterior
We see that posterior is an EmpiricalDistribution, the distribution implied by the set of MCMC samples. EmpiricalDistribution generically calls the items that the empirical distribution is defined over atoms (here, the MCMC samples are the atoms). The above summary also shows that the default settings ran 4 MCMC chains, returning 1000 samples per chain. The mean, variance, and quantile operations of an empirical distribution are simply the sample mean, variance, and quantiles computed over this set of samples.
posterior.num_atoms
mean(posterior).raw
variance(posterior).raw
levels = jnp.array([0.05, 0.95])
quantile(posterior, levels).raw
2. MCMC Diagnostics¶
An important step in a Bayesian workflow is evaluating the performance of the inference algorithm. ProbPipe makes it easy to report standard MCMC diagnostics, including:
- R-hat: compares the chains with one another, and a value above 1.01 is cause for concern.
- effective sample size (ESS): the number of independent draws with the equivalent amount of information as the correlated MCMC samples.
- divergences: transitions where the sampler failed. There should be none.
add_mcmc_diagnostics(posterior)
print(posterior.diagnostics.summary_table())
print("divergent transitions:", posterior.diagnostics.mcmc.n_divergences)
The diagnostics in posterior.diagnostics are a view on data stored in posterior.annotations. Annotations in ProbPipe are just
metadata that are carried along in an object. For the most part, ProbPipe objects are immutable: they cannot be modified in place
once they are created. Annotations are the one exception.
Below we see that add_mcmc_diagnostics added annotations stored as an xarray object, using
ArviZ conventions. This allows us to use the many great exploratory analysis and visualization
functionality offered by the ArviZ package.
posterior.annotations
az.plot_pair(posterior.annotations["arviz"], var_names=["K", "phi", "r"])
plt.show()
The plot suggests shows that, under our model, a larger carrying capacity is consistent with a smaller observation probability.
3. ProbPipe functions: computing model predictions¶
The trade-off between $K$ and $\phi$ suggests that $\phi K$ might be an interesting quantity to look at. This is the count that a survey
expects to record when the population is at its carrying capacity. We write this quantity below as a function of the two parameters, and
wrap the function using ProbPipe's @function decorator.
This turns the raw function into a ProbPipe Function, which gives it some useful additional functionality.
@function
def capacity_count(K: jax.Array, phi: jax.Array) -> jax.Array:
return phi * K
capacity_count
We see that the function prints a useful summary. Similar to other ProbPipe objects we have seen, the .raw property stores the
underlying wrapped object, which in this case is the original Python function.
print(capacity_count)
print(capacity_count.raw)
The function can be called just like the normal Python function, but the result is wrapped as a ProbPipe NumericArray.
result = capacity_count(K=100, phi=0.6)
print(result)
result
Now let's look at one of the major capabilities that a ProbPipe function possesses: distributions can be passed to the function
in place of the original arguments. That is, instead of passing a scalar value of K directly, we can pass in a probability
distribution over K. And similarly for phi.
So what is actually returned here? ProbPipe does the following:
- Samples of
Kandphiare drawn jointly from the prior. - Each sample is fed through the function.
- The returned result is an empirical distribution over the output of the function.
We emphasize in step 1 that the samples are drawn jointly. ProbPipe knows that the arguments are coming from the same joint distribution and thus preserves the correlation between them when sampling the function inputs.
with workflow_run(seed=2):
prior_capacity_count = capacity_count(prior["K"], prior["phi"])
prior_capacity_count
We can also configure the call to return (an empirical approximation of) the joint distribution over the function inputs and outputs.
The computation is the same as the previous call, but not the samples of the inputs are retained in the empirical distribution. Other call options, such as the number of samples, can also be set using <function>.using().
with workflow_run(seed=21):
func_with_options = capacity_count.using(include_inputs=True, n_broadcast_samples=300)
prior_capacity_count_with_inputs = func_with_options(prior["K"], prior["phi"])
prior_capacity_count_with_inputs
atoms = prior_capacity_count_with_inputs.atoms
fields = atoms.element_spec.fields
fig, axes = plt.subplots(ncols=len(fields), figsize=(10, 3), layout="constrained")
for field, ax in zip(fields, axes):
ax.hist(atoms[field].raw, bins=20, density=True)
ax.set(xlabel=field)
axes[0].set_ylabel("density")
plt.show()
We can also pass in the posterior distribution over these arguments instead of the prior. The below code compares the 90% interval of $\phi K$ under the prior and the posterior.
with workflow_run(seed=2):
posterior_capacity_count = capacity_count(posterior["K"], posterior["phi"])
print("phi * K, prior 90% interval:", quantile(prior_capacity_count, levels).raw)
print("phi * K, posterior 90% interval:", quantile(posterior_capacity_count, levels).raw)
4. Posterior predictions of moose counts¶
Recall that we constructed the joint probability model as model = likelihood * prior. We can do the same thing, but
replacing prior with posterior. This gives us a predictive joint distribution.
predictive_joint = likelihood.with_path_names(y="y_pred") * posterior.with_label("posterior")
print(predictive_joint)
predictive_joint
Let's draw samples from the predictive joint. Recall that posterior is an empirical distribution defined over the MCMC
samples. Thus, the sample call here does the following to draw each joint sample:
- Draw one sample from
posterior, which is done by re-sampling the MCMC draws. - Draw a sample from the conditional distribution, conditional on the sampled parameter values from step 1.
The result is samples from the predictive joint: $$ p(y^{\mathrm{pred}}, r, \phi, K \mid y=y^{\mathrm{obs}}) = p(y^{\mathrm{pred}} \mid r, \phi, K) \cdot p(r, \phi, K \mid y=y^{\mathrm{obs}}). $$
with workflow_run(seed=3):
predicted = sample(predictive_joint, 1000)
predicted
Extracting the y component yields samples from the posterior predictive distribution: the model's predictions of the
counts after we have conditioned on the observed data.
low, high = np.percentile(predicted["y"].raw, [5, 95], axis=0)
fig, ax = plt.subplots(figsize=(7, 3))
ax.fill_between(years, low, high, color="tab:blue", alpha=0.3, label="90% predictive band")
ax.plot(years, counts, "o", color="black", label="moose counted")
ax.set(xlabel="year", ylabel="count", title="Posterior predictions of moose counts")
ax.legend()
plt.show()
Our model looks a little overconfident here. We hope to see the 90% interval containing 90% of hte observed data points, but this doesn't appear to be the case. We will investigate this more formally below.
5. A predictive check¶
Let's make the above visual observation formal with a posterior predictive check. We compare a statistic of the observed counts to replicates of same quantity computed from the fit model. The p-value is the fraction of replicates whose statistic is at least as large as the observed statistic. A p-value near 0 or 1 means the model rarely produces data that look like the observed data (with respect to the particular statistic).
ProbPipe makes computing predictive checks easy with predictive_check. We run this below with two different statistics: the spread of year-to-year population changes (how much the counts jump), and the maximum count.
def change_spread(y: jax.Array) -> jax.Array:
return jnp.std(jnp.diff(y))
def largest_count(y: jax.Array) -> jax.Array:
return jnp.max(y)
with workflow_run(seed=4):
check = predictive_check(likelihood, posterior, [change_spread, largest_count], counts)
check
# TODO: make visual
change_spread_obs = check["change_spread/observed_statistic"]
largest_count_obs = check["largest_count/observed_statistic"]
change_spread_pvalue = check["change_spread/p_value"]
largest_count_pvalue = check["largest_count/p_value"]
print(f"change_spread: observed {change_spread_obs}, p-value {change_spread_pvalue}")
print(f"largest_count: observed {largest_count_obs}, p-value {largest_count_pvalue}")
We see that the simulated spread of the year-to-year jumps is very rarely as large as the observed change spread. We will consider improving the model to address this limitation in Tutorial 3.
6. Choosing an inference method¶
We saw above that ProbPipe automatically dispatched BlackJAX's NUTS sampler when condition_on was run on this
model with the default settings. We now see how we can manually choose an alternative method. We'll try another
NUTS sampler, this time from Tensorflow Probability (TFP).
with workflow_run(seed=6):
tfp_posterior = condition_on.using(method="tfp_nuts")(model, observed)
add_mcmc_diagnostics(tfp_posterior)
print("method:", tfp_posterior.provenance.metadata["method"])
print("divergent transitions:", tfp_posterior.diagnostics.mcmc.n_divergences)
TFP's sampler is reporting divergent transitions, something we'll investigate more in a bit. Before doing that, let's see how the mean estimates of the TFP samples compare to those from BlackJAX.
param_names = tuple(prior.event_spec.components)
blackjax_means = mean(posterior[param_names])
tfp_means = mean(tfp_posterior[param_names])
for name, blackjax_mean in blackjax_means.items():
print(f"{name}: {blackjax_mean} vs. {tfp_means[name]}")
Despite the divergences, the TFP means mostly agree with those of the BlackJAX algorithm. We'll investigate the TFP algorithm further below.
7. Algorithm settings¶
Up to this point, we have been running algorithms with their default settings. While the default settings are chosen to be reasonable for many problems, they won't always be acceptable for every application. Let's try to play around with the TFP NUTS settings to deal with those divergences. We'll increase the target acceptance probability and also increase the number of samples. Algorithm-specific settings are passed via the method_options argument.
tfp_settings = {"target_accept_prob": 0.9, "num_results": 2000}
with workflow_run(seed=6):
tfp_posterior = condition_on.using(method="tfp_nuts", method_options=tfp_settings)(model, observed)
add_mcmc_diagnostics(tfp_posterior)
print("divergent transitions:", tfp_posterior.diagnostics.mcmc.n_divergences)
print("largest R-hat:", round(max(tfp_posterior.diagnostics.mcmc.rhat.values()), 3))
print("mean of K:", round(float(mean(tfp_posterior["K"])), 1))
These settings have reduced, but not completely eliminated, the divergences.
8. Trying a different MCMC algorithm¶
Let's see how a simpler MCMC algorithm would do here: random walk Metropolis-Hastings. Unlike NUTS, this algorithm does not make use of gradients of the log-density, and doesn't tend to scale as well to higher-dimensional parameter spaces.
with workflow_run(seed=7):
rwmh_posterior = condition_on.using(method="blackjax_rwmh")(model, observed)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
add_mcmc_diagnostics(rwmh_posterior)
rwmh_diagnostics = rwmh_posterior.diagnostics.mcmc
print("largest R-hat:", round(max(rwmh_diagnostics.rhat.values()), 2))
print("smallest bulk ESS:", round(min(rwmh_diagnostics.ess_bulk.values())))
These diagnostics show that random walk Metropolis-Hastings completely failed here: the R-hats are very large and the effective sample sizes are tiny.
9. Restricting to exact inference¶
MCMC, while a gold standard for Bayesian inference, is an approximate method. ProbPipe keeps track of whether various operations on probability distributions are exact or approximate. We can demand an exact method by specifying exact_only=True in condition_on. Exact methods are available in certain special settings (e.g., conjugate models).
We see below that no exact method is applicable to our current problem. An error is thrown if exact_only=True is specified when no exact method is applicable.
condition_on.using(exact_only=True).check(model, observed)
Exercises¶
Each exercise is followed by a solution, which Colab shows collapsed.
Exercise 1. A small population doubles in about $\log(2) / r$ years. Apply one function that computes the doubling time to the prior and to the posterior, and compare the two 90% intervals.
# @title Solution
@function
def doubling_time(r: jax.Array) -> jax.Array:
return jnp.log(2.0) / r
with workflow_run(seed=5):
for name, law in [("prior", prior), ("posterior", posterior)]:
low, high = quantile(doubling_time(law["r"]), levels).raw
print(f"doubling time under the {name}: 90% interval ({low:.1f}, {high:.1f}) years")
Exercise 2. Write a third statistic, the number of years in which the count fell, and check the model with it. Does it detect the misfit, as the spread of the changes does?
# @title Solution
def declines(y: jax.Array) -> jax.Array:
return jnp.sum(jnp.diff(y) < 0).astype(jnp.float32)
with workflow_run(seed=6):
decline_check = predictive_check(likelihood, posterior, declines, counts)
print("observed number of declines:", float(decline_check["observed_statistic"]))
print("p-value:", round(float(decline_check["p_value"]), 3))
# A p-value near 0.07 is weaker evidence of misfit than the spread of the changes gave.
Exercise 3. Fit the model again with two chains of 250 draws each, through condition_on.using(method_options={"num_chains": 2, "num_results": 250}).
How do the effective sample sizes change?
# @title Solution
with workflow_run(seed=7):
short_posterior = condition_on.using(method_options={"num_chains": 2, "num_results": 250})(
model, observed
)
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
add_mcmc_diagnostics(short_posterior)
messages = [str(caught_warning.message) for caught_warning in caught]
diagnostic_warnings = [message for message in messages if message.startswith(("R-hat", "Low ESS"))]
print("warnings from add_mcmc_diagnostics:", len(diagnostic_warnings))
for message in diagnostic_warnings:
if message.startswith("R-hat"):
print("warning:", message)
print("number of draws:", short_posterior.num_atoms)
print("smallest bulk ESS with 2 chains of 250:", round(min(short_posterior.diagnostics.mcmc.ess_bulk.values())))
print("smallest bulk ESS with 4 chains of 1,000:", round(min(posterior.diagnostics.mcmc.ess_bulk.values())))
Summary¶
condition_onon the counts returns the posterior, by the same call that fixed parameter values in tutorial 1. No formula gives this posterior, so it applies Bayes' rule and draws from the result with NUTS, and it reports the result as approximate.- The posterior is a distribution like the prior:
mean,quantile,sample, and*apply to it, and its draws are anEmpiricalDistribution. add_mcmc_diagnosticschecks the sampler, andpredictive_checkchecks the model against the data.- A Python function applied to the posterior returns the distribution of its output, and one function applied to the prior and the posterior shows what the counts taught.
- The model's counts vary less from year to year than the observed counts.
Tutorial 3 revises the model and checks the posterior with other algorithms and another modeling language.