AI-generated. An AI assistant drafted this page, and no maintainer has reviewed it yet. Please report errors on the issue tracker.
Conditioning and inference methods¶
condition_on fixes some fields of a model at given values and returns the distribution of the other fields.
Conditioning a model on its data gives the posterior, which condition_on computes exactly when an exact route applies and with an inference method otherwise.
This chapter shows how condition_on chooses that method, how we choose one ourselves, and how to condition models written in PyMC and models that can only be simulated.
We need it whenever we fit a model to data, or when the method that condition_on selects does not suit a model.
# On Google Colab, install ProbPipe with PyMC, nutpie, and pyabc; elsewhere this cell does nothing.
try:
import google.colab # noqa: F401
IN_COLAB = True
except ImportError:
IN_COLAB = False
if IN_COLAB:
%pip install --quiet "probpipe-core[pymc,nutpie,pyabc] @ git+https://github.com/TARPS-group/prob-pipe.git@main"
import logging
import jax
import jax.numpy as jnp
import numpy as np
import pymc as pm
from probpipe import (
Distribution,
EmpiricalDistribution,
Normal,
NumericArrayBatch,
NumericArraySpec,
PyMCModel,
condition_on,
conditional_distribution,
distribution,
inference_method_registry,
mean,
prob,
quantile,
sample,
variance,
workflow_run,
)
from probpipe.families import BernoulliFamily, glm_likelihood
# PyMC and pyabc report their progress as log messages, which this line silences.
logging.disable(logging.INFO)
Conditioning a model on data¶
Most sections use one small model. The prior of a mean $\mu$ is a normal distribution with mean 0 and standard deviation 2, and given $\mu$, ten measurements $y$ are independent normal draws with mean $\mu$ and standard deviation 1.
y = jnp.array([1.2, 0.4, 2.1, 1.7, 0.9, 1.5, 0.3, 1.1, 2.4, 1.0])
n = y.shape[0]
prior = Normal("mu", 0.0, 2.0, label="prior")
def y_given_mu(mu: jax.Array) -> Normal:
return Normal("y", jnp.full(n, mu), 1.0)
likelihood = conditional_distribution(
y_given_mu, label="likelihood", given_spec=prior.event_spec
)
model = (likelihood & prior).with_label("model")
print("the model:", model)
the model: model(y, mu)
condition_on(model, given) takes the given values as a mapping keyed by field path, so {"y": y} fixes the field y of the model at the measurements.
The result is the posterior of the other field, mu:
with workflow_run(seed=0):
posterior = condition_on(model, {"y": y})
print("posterior:", posterior)
print("kind of posterior:", type(posterior).__name__)
print("number of draws:", posterior.num_atoms)
record = posterior.provenance.metadata
print(f"provenance: route={record['route']}, method={record['method']}, exact={record['exact']}")
posterior: model(mu; y) kind of posterior: EmpiricalDistribution number of draws: 4000 provenance: route=inference_methods, method=blackjax_nuts, exact=False
No exact route applies to this model, so condition_on took the route inference_methods.
The route multiplies the likelihood by the prior at the given values, by Bayes' rule, and passes that unnormalized posterior to an inference method, here BlackJAX's No-U-Turn Sampler (NUTS).
The posterior keeps the model's label, and its notation model(mu; y) states that it is the distribution of mu with y fixed at the given values.
It is an EmpiricalDistribution of draws, and its provenance records that it is approximate, as How a result was computed explains.
This posterior has a formula, which lets us check the draws. With a prior variance of 4 and $n$ measurements of variance 1, the posterior of $\mu$ is normal with precision $n + 1/4$ and mean $\sum_i y_i / (n + 1/4)$:
exact_mean = jnp.sum(y) / (n + 0.25)
exact_sd = (n + 0.25) ** -0.5
print(f"posterior mean of mu from the draws: {float(mean(posterior['mu'])):.3f}")
print(f"posterior mean of mu from the formula: {float(exact_mean):.3f}")
posterior_sd = jnp.sqrt(variance(posterior["mu"]).raw)
print(f"posterior sd of mu from the draws: {float(posterior_sd):.3f}")
print(f"posterior sd of mu from the formula: {float(exact_sd):.3f}")
posterior mean of mu from the draws: 1.231 posterior mean of mu from the formula: 1.229 posterior sd of mu from the draws: 0.300 posterior sd of mu from the formula: 0.312
Conditioning on parameter values¶
Conditioning the same model on a value of $\mu$ gives the distribution of the measurements at that value:
y_at_1 = condition_on(model, {"mu": 1.0})
print("result:", y_at_1)
print("kind of result:", type(y_at_1).__name__)
print("mean of y at mu = 1:", mean(y_at_1).raw)
record = y_at_1.provenance.metadata
print(f"provenance: route={record['route']}, exact={record['exact']}")
result: likelihood(y; mu) kind of result: Normal mean of y at mu = 1: [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.] provenance: route=slice, exact=True
The prior produces $\mu$, and the likelihood depends on it, so the conditional law of $y$ is the likelihood at $\mu = 1$.
condition_on took the route slice, which assembles that law from the model's factors, and the result is an exact Normal distribution.
It keeps the label of the factor likelihood, and ; mu in its notation records the conditioned path.
Conditioning the likelihood itself on $\mu$ takes the exact route curry, which Joint models and conditional distributions shows.
Exact posteriors from an empirical prior¶
An EmpiricalDistribution is a distribution on finitely many weighted points, which are called its atoms.
When the prior is one, Bayes' rule has an exact answer: the posterior keeps the prior's atoms and multiplies each weight by the likelihood of the data at that atom.
The inference method empirical_reweighting computes it.
Here the prior of $\mu$ is a grid of 401 points from −1 to 3, each weighted by the density of the normal prior.
prob evaluates the density at each element of a batch, here the batch of grid points.
EmpiricalDistribution takes the atoms first, output_name= names the output that the atoms fill, and label= names the distribution:
grid = jnp.linspace(-1.0, 3.0, 401)
grid_weights = prob(prior, NumericArrayBatch(grid, "point", label="grid"))
grid_prior = EmpiricalDistribution(grid, weights=grid_weights, output_name="mu", label="grid_prior")
grid_model = (likelihood & grid_prior).with_label("grid_model")
grid_posterior = condition_on.using(exact_only=True)(grid_model, {"y": y})
record = grid_posterior.provenance.metadata
print(f"provenance: route={record['route']}, method={record['method']}, exact={record['exact']}")
print(f"posterior mean of mu on the grid: {float(mean(grid_posterior['mu'])):.3f}")
grid_sd = jnp.sqrt(variance(grid_posterior["mu"]).raw)
print(f"posterior sd of mu on the grid: {float(grid_sd):.3f}")
provenance: route=inference_methods, method=empirical_reweighting, exact=True posterior mean of mu on the grid: 1.229 posterior sd of mu on the grid: 0.312
The control exact_only=True refuses every approximate route and method, and the call succeeds because empirical_reweighting is exact.
The grid posterior matches the formula of the first section to three decimals, and it draws nothing, so it needs no seed.
A prior given as draws, such as EmpiricalDistribution(sample(prior, sample_shape=5000), output_name="mu"), is reweighted the same way.
Choosing an inference method¶
The route inference_methods passes the unnormalized posterior to the registry of inference methods, which is inference_method_registry.
Its method list_methods names the registered methods in the order that selection considers them: the exact methods first, and then the approximate ones by priority.
print("registered inference methods:", inference_method_registry.list_methods())
registered inference methods: ['empirical_reweighting', 'nutpie_nuts', 'blackjax_nuts', 'cmdstan_nuts', 'pymc_nuts', 'blackjax_elliptical_slice', 'blackjax_rwmh', 'blackjax_sgld', 'pyabc_smcabc', 'tfp_nuts', 'blackjax_hmc', 'blackjax_sghmc', 'pymc_advi']
Each method checks whether it applies to a model, from the capabilities the model claims, and condition_on runs the first method that applies.
inference_method_registry.check(model, given, method=name) reports whether one method applies, and why it declines when it does not:
observed = {"y": y}
applicable = [
name
for name in inference_method_registry.list_methods()
if inference_method_registry.check(model, observed, method=name).feasible
]
print("methods that apply to the model:", applicable)
declined = inference_method_registry.check(model, observed, method="empirical_reweighting")
print("why empirical_reweighting declines:", declined.description)
methods that apply to the model: ['blackjax_nuts', 'blackjax_elliptical_slice', 'blackjax_rwmh', 'pyabc_smcabc', 'tfp_nuts', 'blackjax_hmc'] why empirical_reweighting declines: the prior must be an EmpiricalDistribution; got Normal 'prior'
blackjax_nuts is the first method that applies, so condition_on selected it.
The last four methods of the listing have no priority, so selection skips them and they run only when a call names them.
condition_on.using(method=name) runs the named method, and method_options holds that method's settings, such as the number of chains and of draws.
A method takes its seed from the enclosing workflow_run, so its settings hold no seed.
The method blackjax_rwmh runs random-walk Metropolis, which needs no gradient:
with workflow_run(seed=1):
rwmh_posterior = condition_on.using(
method="blackjax_rwmh", method_options={"num_chains": 4, "num_results": 2000}
)(model, observed)
print("method:", rwmh_posterior.provenance.metadata["method"])
print("number of draws:", rwmh_posterior.num_atoms)
rwmh_mean = float(mean(rwmh_posterior["mu"]))
print(f"posterior mean of mu from random-walk Metropolis: {rwmh_mean:.3f}")
method: blackjax_rwmh number of draws: 8000 posterior mean of mu from random-walk Metropolis: 1.231
A method refuses a setting it does not read, and its error lists the settings it reads:
try:
condition_on.using(method="blackjax_rwmh", method_options={"num_draws": 2000})(
model, observed
)
except TypeError as error:
print("error:", error)
error: inference method 'blackjax_rwmh': unknown method option 'num_draws'; available method options: ['adapt', 'init', 'n_windows', 'num_chains', 'num_results', 'num_warmup', 'proposal_cov', 'step_size']
The registered methods fit different models, as their documentation states:
blackjax_nutsandtfp_nuts: a log density written in JAX, which JAX differentiates for the gradient that NUTS follows;blackjax_elliptical_slice: a normal prior and a likelihood written in JAX, and it tunes itself;blackjax_rwmh: a log density without a gradient, at the cost of slow mixing in many dimensions;blackjax_sgld: many conditionally independent observations, and it estimates the gradient from a random subset of them at each step;pyabc_smcabc: a simulator, which draws data and has no density;empirical_reweighting: an empirical prior, for which it is exact;nutpie_nuts,pymc_nuts,cmdstan_nuts, andpymc_advi: a model written in PyMC or Stan, which the next section conditions.
The stochastic-gradient method blackjax_sgld needs a likelihood that scores a subset of the observations, which glm_likelihood builds, and the setting batch_size, which is the size of each subset.
We fit a logistic regression to 2,000 simulated outcomes, in subsets of 100:
rng = np.random.default_rng(0)
x = jnp.asarray(rng.normal(size=2000), dtype=jnp.float32)
X = jnp.stack([jnp.ones_like(x), x], axis=1)
outcome_given_beta = glm_likelihood("outcome", BernoulliFamily(), X=X)
regression = ((outcome_given_beta & Normal("beta", jnp.zeros(2), 2.0))).with_label("regression")
true_beta = jnp.array([-0.5, 1.5])
with workflow_run(seed=2):
outcomes = sample(condition_on(outcome_given_beta, {"beta": true_beta})).raw
sgld_posterior = condition_on.using(
method="blackjax_sgld", method_options={"batch_size": 100, "num_results": 1000}
)(regression, {"outcome": outcomes})
print("coefficients that simulated the outcomes:", true_beta)
print("posterior mean of beta from SGLD:", mean(sgld_posterior["beta"]).raw)
coefficients that simulated the outcomes: [-0.5 1.5] posterior mean of beta from SGLD: [-0.43948644 1.5708932 ]
Each step of SGLD evaluates the likelihood of 100 of the 2,000 outcomes, and the posterior mean is close to the coefficients that simulated the data. Checking results shows how to check any of these posteriors with diagnostics.
Models written in PyMC or Stan¶
PyMCModel wraps a function that builds a PyMC model, and its outputs are the model's variables.
The function takes the data as an argument that defaults to None and passes it as the observed value of y, so it also builds the model without data.
We write the normal model in PyMC, with the standard deviation of the measurements as a second parameter.
condition_on.check reports the method that a call would select, without running it:
def build_normal_model(y: np.ndarray | None = None) -> pm.Model:
with pm.Model() as pymc_model:
mu = pm.Normal("mu", mu=0.0, sigma=2.0)
sigma = pm.HalfNormal("sigma", sigma=1.0)
pm.Normal("y", mu=mu, sigma=sigma, observed=y, shape=n)
return pymc_model
normal_in_pymc = PyMCModel(build_normal_model, label="normal_in_pymc")
print("outputs of the PyMC model:", list(normal_in_pymc.event_spec.outputs))
print("method condition_on selects:", condition_on.check(normal_in_pymc, observed).method)
outputs of the PyMC model: ['mu', 'sigma', 'y'] method condition_on selects: nutpie_nuts
When nutpie is installed, condition_on selects nutpie_nuts, which runs nutpie's implementation of NUTS and ranks first for a PyMC model because it is the fastest.
Without nutpie, it selects pymc_nuts.
The setting progress_bar=False of nutpie_nuts keeps it from drawing a progress bar:
with workflow_run(seed=3):
pymc_posterior = condition_on.using(method_options={"progress_bar": False})(
normal_in_pymc, observed
)
print("kind of posterior:", type(pymc_posterior).__name__)
print(f"posterior mean of mu: {float(mean(pymc_posterior['mu'])):.3f}")
print(f"posterior mean of sigma: {float(mean(pymc_posterior['sigma'])):.3f}")
kind of posterior: EmpiricalDistribution posterior mean of mu: 1.240 posterior mean of sigma: 0.753
The PyMC posterior is a distribution like the others, so the operations of the earlier sections apply to it.
StanModel wraps a Stan program in the same way: its inputs are the variables of the program's data block, and conditioning on them returns the posterior, which condition_on draws from with nutpie_nuts or cmdstan_nuts.
It needs the stan extra, and Distributions and families documents both classes.
Models that can only be simulated¶
A simulator is a program that draws data at random given its parameters, and no formula gives the probability of the data.
In ProbPipe, a simulator is a conditional distribution whose function returns a law built by distribution(sample=..., event_spec=..., output_name=...), which can only draw, as Distributions shows.
Our example is the g-and-k distribution, which is a standard test of simulation-based inference. A draw transforms a standard normal draw $z$ into $A + (1 + 0.8 \tanh(g z / 2)) \sqrt{1 + z^2}\, z$, where $A$ sets the location and $g$ the skewness. Its quantiles have a formula, and its density has none. The simulator draws 100 values at a time:
def g_and_k(A: jax.Array, g: jax.Array) -> Distribution:
def draw(key: jax.Array) -> jax.Array:
z = jax.random.normal(key, (100,))
return A + (1.0 + 0.8 * jnp.tanh(g * z / 2.0)) * jnp.sqrt(1.0 + z**2) * z
return distribution(sample=draw, event_spec=NumericArraySpec((100,)), output_name="x")
simulator_prior = ((Normal("A", 0.0, 5.0) & Normal("g", 0.0, 2.0))).with_label("simulator_prior")
simulator = conditional_distribution(
g_and_k, label="simulator", given_spec=simulator_prior.event_spec
)
simulator_model = (simulator & simulator_prior).with_label("simulator_model")
with workflow_run(seed=4):
x_observed = sample(condition_on(simulator, {"A": 3.0, "g": 1.5})).raw
simulator_method = condition_on.check(simulator_model, {"x": x_observed}).method
print("method condition_on selects:", simulator_method)
method condition_on selects: pyabc_smcabc
The likelihood has no density, so every method that evaluates one declines, and condition_on selects pyabc_smcabc: SMC-ABC from the package pyabc.
It draws parameters, simulates data at each draw, and keeps the draws whose simulations resemble the observed data, which it measures by the distance between a few summaries of each data set.
Each generation perturbs the draws the last one kept and lowers the largest distance it accepts.
The summaries are a setting of the method, which we set to five quantiles of the data. We run eight generations of 200 draws each:
def quantile_summaries(x: jax.Array) -> jax.Array:
"""Five quantiles of each row of data."""
levels = jnp.array([0.05, 0.25, 0.5, 0.75, 0.95])
return jnp.quantile(jnp.atleast_2d(x), levels, axis=-1).T
with workflow_run(seed=5):
abc_posterior = condition_on.using(
method_options={
"summary_fn": quantile_summaries,
"n_particles": 200,
"max_populations": 8,
}
)(simulator_model, {"x": x_observed})
interval = jnp.array([0.05, 0.95])
for name, truth in [("A", 3.0), ("g", 1.5)]:
low, high = quantile(abc_posterior[name], interval).raw
print(
f"{name}: value that simulated the data {truth}, posterior mean "
f"{float(mean(abc_posterior[name])):.2f}, 90% interval ({low:.2f}, {high:.2f})"
)
A: value that simulated the data 3.0, posterior mean 2.96, 90% interval (2.60, 3.30) g: value that simulated the data 1.5, posterior mean 2.06, 90% interval (0.88, 4.11)
Both 90% intervals contain the values that simulated the data, and the interval of the skewness $g$ is wider than that of the location $A$.
The posterior is an EmpiricalDistribution of weighted draws, and its quality depends on the summaries and on the number of generations, as tutorial 6 shows.
SMC-ABC runs its simulations for one data set.
learn_amortized_posterior(prior, simulator, ...) instead trains a neural network with BayesFlow on pairs of parameters and simulated data, and it returns the posterior as a conditional distribution of the parameters given any data set, which condition_on evaluates at the observed data.
It needs the bayesflow extra, and tutorial 6 fits a model both ways.
See also¶
- Operations:
condition_on,sample,mean,variance,quantile, andprob. - Inference methods:
inference_method_registryandlearn_amortized_posterior. - Distributions and families:
EmpiricalDistribution,distribution,conditional_distribution,glm_likelihood,PyMCModel, andStanModel. - Registries for extensions: how to register a new inference method, and the priorities of the built-in ones.
- Joint models and conditional distributions: conditional distributions and the joint models that
condition_onconditions. - Checking results: diagnostics and calibration of a posterior.
- Converting and updating distributions: empirical distributions, and updating a posterior as data arrive.
- How a result was computed: routes, options, seeds, and provenance.
- Tutorial 2 fits a model with NUTS, tutorial 7 compares samplers, and tutorial 6 fits a simulator with SMC-ABC and an amortized posterior.