AI-generated. An AI assistant drafted this page, and no maintainer has reviewed it yet. Please report errors on the issue tracker.
Joint models and conditional distributions¶
A Bayesian model is built from pieces, such as a prior of the parameters and a distribution of the data given the parameters.
This chapter writes the second kind of piece as a conditional distribution, merges the pieces into a joint model with &, and works with the draws, the fields, and the marginals of the result.
Read it when you specify a model of your own, before you fit it as Conditioning and inference methods describes.
The examples follow a toy survey that counts the birds at four sites on three visits each.
# On Google Colab, install ProbPipe; elsewhere this cell does nothing.
try:
import google.colab # noqa: F401
IN_COLAB = True
except ImportError:
IN_COLAB = False
if IN_COLAB:
# Colab's preinstalled PyMC 5 does not work with ArviZ 1.x, so the install upgrades PyMC.
%pip install --quiet "probpipe-core[pymc] @ git+https://github.com/TARPS-group/prob-pipe.git@main"
import warnings
import jax
import jax.numpy as jnp
import numpy as np
from probpipe import (
Gamma,
HalfNormal,
Normal,
NumericArraySpec,
Poisson,
condition_on,
conditional_distribution,
factor,
joint,
log_prob,
marginal,
mean,
positive,
sample,
workflow_run,
)
from probpipe.families import PoissonFamily, glm_likelihood
# TensorFlow Probability warns that JAX runs in 32-bit precision, which these models use.
warnings.filterwarnings("ignore", message=r"Explicitly requested dtype float64")
A conditional distribution from a function¶
A conditional distribution assigns a distribution of one quantity to each value of another.
We write it as a Python function that takes the given value and returns a distribution, and conditional_distribution turns the function into a ProbPipe object.
Here the function returns the distribution of the counts on three visits to one site, given the site's rate of birds per visit.
def visit_counts(rate: jax.Array) -> Poisson:
return Poisson("counts", jnp.full(3, rate))
counts_given_rate = conditional_distribution(
visit_counts, label="counts_given_rate", given_spec={"rate": NumericArraySpec((), support=positive)}
)
print("conditional distribution:", counts_given_rate)
print("inputs:", list(counts_given_rate.given_spec))
print("outputs:", list(counts_given_rate.event_spec.outputs))
conditional distribution: counts_given_rate(counts | rate) inputs: ['rate'] outputs: ['counts']
Each parameter of the function is an input, and given_spec declares the type of each input's value, which here is a positive scalar.
conditional_distribution evaluates the function once, abstractly, to read the distribution it returns.
A model compiles the function when it draws or scores the conditional distribution at many given values, so the function must be pure, and a value that changes between calls belongs in an input.
The conditional distribution therefore produces the output counts, which the Poisson inside the function names.
label= names the conditional distribution, and without it the label is the function's name.
The conditional distribution displays as counts_given_rate(counts | rate), which is its label followed by its output counts and, after |, its input rate.
A parameter with a default is an optional input, which takes its default when no value is bound to it, as the initial population n0 of tutorial 1 does.
condition_on binds inputs to values.
Once every input is bound, the result is an ordinary distribution:
counts_at_rate_4 = condition_on(counts_given_rate, {"rate": 4.0})
print("distribution at rate 4:", counts_at_rate_4)
print("kind of the distribution at rate 4:", type(counts_at_rate_4).__name__)
print("mean counts at rate 4:", mean(counts_at_rate_4).raw)
print("route of condition_on:", counts_at_rate_4.provenance.metadata["route"])
distribution at rate 4: counts_given_rate(counts; rate) kind of the distribution at rate 4: Poisson mean counts at rate 4: [4. 4. 4.] route of condition_on: bind_inputs
The result is the Poisson distribution that visit_counts returns at a rate of 4, so the mean count on each of the three visits is 4.
It keeps the label of the conditional distribution, and ; rate in its notation records the input that condition_on bound.
condition_on took the route curry, which calls the function at the bound values, so the result is exact.
Binding some of the inputs of a conditional distribution with several inputs returns a conditional distribution of the rest.
An operation on a conditional distribution takes the given values as the keyword given=, which binds them for that call alone.
Here log_prob scores three counts at a rate of 4:
three_counts = jnp.array([3.0, 4.0, 5.0])
log_density = log_prob(counts_given_rate, three_counts, given={"rate": 4.0})
print("label of the log density:", log_density.label)
print("log density of the counts at rate 4:", log_density.raw)
print("same, after condition_on:", log_prob(counts_at_rate_4, three_counts).raw)
label of the log density: log counts_given_rate(counts; rate) log density of the counts at rate 4: -5.1217756 same, after condition_on: -5.1217756
The two log densities agree, and the label log counts_given_rate(counts; rate) records the bound input as condition_on does.
Merging a joint model with &¶
A prior of the rate and the conditional distribution of the counts together define a joint distribution of the rate and the counts.
& merges them:
rate_prior = Gamma("rate", 2.0, 0.5)
model = (counts_given_rate & rate_prior).with_label("model")
print("the product:", (counts_given_rate & rate_prior))
print("the model:", model)
print("outputs of the model:", list(model.event_spec.outputs))
the product: counts_given_rate(counts | rate)·Gamma(rate) the model: model(counts, rate) outputs of the model: ['counts', 'rate']
The conditional distribution goes on the left of &, and the distribution that produces its given value goes on the right.
& connects each input to the output of the same name, so the prior's output rate supplies the input rate.
& joins the labels of its operands with ·, so the product displays factor by factor, and with_label names the joint distribution model.
The model is a distribution, and one draw from it is a record with one field per output:
with workflow_run(seed=0):
draw = sample(model)
print("one draw:", repr(draw))
print("rate in the draw:", draw["rate"].raw)
print("counts in the draw:", draw["counts"].raw)
one draw: NumericRecord('(counts, rate) ~ model')
counts [12. 4. 13.]
rate 7.1253343
rate in the draw: 7.1253343
counts in the draw: [12. 4. 13.]
The draw takes a rate from the prior and then three counts from the conditional distribution at that rate.
Its label (counts, rate) ~ model reads as the outputs counts and rate drawn from model.
With sample_shape, sample returns a batch of records, and indexing the batch by a field returns that field's values with the draws along the first axis:
with workflow_run(seed=1):
draws = sample(model, sample_shape=1000)
with np.printoptions(threshold=10):
print("draws:", repr(draws))
print("shape of the counts:", draws["counts"].raw.shape)
draws: NumericRecordBatch('(counts, rate) ~ model', levels={'sample': 1000})
counts [[1. 2. 2.]
[9. 2. 5.]
[1. 1. 0.]
...
[3. 3. 3.]
[4. 0. 1.]
[2. 7. 2.]] shape=(1000, 3)
rate [1.1453754 3.9537182 0.45794517 ... 3.153685 0.39057472
2.6908512 ] shape=(1000,)
shape of the counts: (1000, 3)
The batch carries the label of one draw and has the single level sample of size 1,000, and the counts have one row per draw and one column per visit.
NumPy's print options set how many values the repr shows, so np.printoptions(threshold=10) shortens each field to its first and last draws.
When a prior names its output differently from the input it supplies, joint renames the prior's fields before it merges.
joint(A, B, old="new") equals A & B after B's field old is renamed to new:
expected_count_prior = Gamma("expected_count", 2.0, 0.5)
renamed_model = joint(counts_given_rate, expected_count_prior, expected_count="rate")
print("outputs of the renamed model:", list(renamed_model.event_spec.outputs))
outputs of the renamed model: ['counts', 'rate']
Generalized linear models¶
glm_likelihood builds the conditional distribution of a generalized linear model from a family and a design matrix X.
The family BernoulliFamily gives logistic regression, as in the quickstart, and PoissonFamily gives Poisson regression.
The input is the coefficient vector beta, and the mean of the response is the inverse link of X @ beta.
Here one Poisson regression covers all four sites.
Each row of X is one visit and selects that visit's site, so beta holds the four sites' log rates:
site = jnp.array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3])
X = jax.nn.one_hot(site, 4)
observations = glm_likelihood("counts", PoissonFamily(), X=X)
print("inputs:", list(observations.given_spec))
print("shape of beta:", observations.given_spec["beta"].shape)
print("shape of the counts:", observations.event_spec.outputs["counts"].shape)
inputs: ['beta'] shape of beta: (4,) shape of the counts: (12,)
glm_likelihood fixes X when it builds the conditional distribution, so beta is the only input.
The canonical link of PoissonFamily is the logarithm, so binding beta to the log of each site's rate gives a Poisson distribution of the 12 counts whose means are those rates:
site_rates = jnp.array([4.0, 10.0, 1.0, 6.0])
counts_at_site_rates = condition_on(observations, {"beta": jnp.log(site_rates)})
print("mean count on each visit:", mean(counts_at_site_rates).raw)
mean count on each visit: [ 4. 4. 4. 10. 10. 10. 1. 1. 1. 6. 6. 6.]
Chaining factors: a hierarchical model¶
A hierarchical model relates the groups' parameters through a distribution of them.
Here the four log rates beta are normal around a common mean mu with a spread tau, and a hyperprior is the distribution of mu and tau.
The model has three factors:
- the hyperprior: the distribution of
muandtau; - the group level: the conditional distribution of
betagivenmuandtau; - the observations: the conditional distribution of the counts given
beta, which isobservationsfrom the last section.
& of two distributions with no inputs is their independent joint, so Normal("mu", ...) & HalfNormal("tau", ...) is the hyperprior.
given_spec=hyperprior.event_spec declares each input of the group level with the type of the hyperprior's output of the same name.
hyperprior = (Normal("mu", 1.5, 0.5) & HalfNormal("tau", 0.5))
def site_log_rates(mu: jax.Array, tau: jax.Array) -> Normal:
return Normal("beta", jnp.full(4, mu), tau)
log_rates = conditional_distribution(site_log_rates, given_spec=hyperprior.event_spec)
counts_given_hyperparameters = observations & log_rates
print("inputs of observations & log_rates:", list(counts_given_hyperparameters.given_spec))
inputs of observations & log_rates: ['mu', 'tau']
Python evaluates a chain of & from left to right.
observations & log_rates is itself a conditional distribution given mu and tau, because neither factor produces them.
Merging it with the hyperprior supplies those inputs, and the result is the joint distribution of all four outputs:
hierarchical_model = (observations & (log_rates & hyperprior)).with_label("hierarchical_model")
print("outputs of the model:", list(hierarchical_model.event_spec.outputs))
with workflow_run(seed=2):
draw = sample(hierarchical_model)
for name, value in draw.items():
print(f"{name} in the draw:", value.raw)
outputs of the model: ['counts', 'beta', 'mu', 'tau'] counts in the draw: [0. 5. 1. 2. 2. 3. 1. 2. 2. 2. 2. 6.] beta in the draw: [0.82577616 1.0145189 0.69392425 1.078266 ] mu in the draw: 0.89440393 tau in the draw: 0.12847582
The draw takes mu and tau from the hyperprior, then the four log rates given them, and then the 12 counts given the log rates.
Fields of a joint model¶
Indexing a distribution by an output name returns a coupled marginal, which is the distribution of that field.
The operations of Distributions, such as mean and sample, apply to it:
mu_view = hierarchical_model["mu"]
print("coupled marginal of mu:", mu_view)
print("class of the coupled marginal:", type(mu_view).__name__)
print("label of its parent:", mu_view.parent.label)
print("path of the coupled marginal:", mu_view.path)
with workflow_run(seed=3):
for name in ["mu", "beta"]:
field_mean = mean(hierarchical_model[name])
route = field_mean.provenance.metadata["route"]
print(f"mean of {name}:", field_mean.raw, f"(route {route})")
coupled marginal of mu: Normal(mu) class of the coupled marginal: CoupledMarginal label of its parent: hierarchical_model path of the coupled marginal: mu mean of mu: 1.5 (route closed_form) mean of beta: [1.49294 1.5190805 1.4734262 1.504573 ] (route monte_carlo)
The view of mu displays as the factor that produces mu, Normal(mu), and it is a CoupledMarginal of hierarchical_model at the path mu.
That factor is a normal distribution with a closed-form mean, so mean took the exact route closed_form.
The factor of beta conditions on mu and tau, so mean took the route monte_carlo, which averages 1,024 draws of the model.
Its four estimates scatter around the exact mean of 1.5.
A tuple of paths selects several fields at once. The view's draws of the fields come from the same draws of the model, so they keep the dependence between the fields:
with workflow_run(seed=4):
beta_and_mu = sample(hierarchical_model[("beta", "mu")], sample_shape=2000)
first_site = beta_and_mu["beta"].raw[:, 0]
correlation = jnp.corrcoef(first_site, beta_and_mu["mu"].raw)[0, 1]
print("correlation of the first site's log rate with mu:", round(float(correlation), 2))
correlation of the first site's log rate with mu: 0.7
The first site's log rate is mu plus normal noise of scale tau.
Both mu and the noise have variance 0.25, so the exact correlation is $1/\sqrt{2} \approx 0.71$, which the draws reproduce.
Marginals and factors¶
marginal(d, paths) returns the marginal distribution at a path, or at a list of paths, as a standalone distribution with no reference to d.
It applies when the marginal is exact, as it is for a group of fields whose factors condition on no field outside the group:
tau_marginal = marginal(hierarchical_model, "tau")
print("marginal of tau:", tau_marginal)
print("exact:", tau_marginal.provenance.metadata["exact"])
print("marginal of mu and tau:", marginal(hierarchical_model, ("mu", "tau")))
marginal of tau: HalfNormal(tau) exact: True marginal of mu and tau: Normal(mu)·HalfNormal(tau)
The marginal of tau is its factor in the hyperprior, and the marginal of mu and tau together is the hyperprior.
The marginal of beta integrates mu and tau out of its factor, which has no exact form here, so marginal(hierarchical_model, "beta") raises ResolutionError.
The coupled marginal hierarchical_model["beta"] draws that field and estimates its moments, as the last section showed.
factor(d, output_name) returns the factor of a joint that produces an output.
The factor is a conditional distribution when it conditions on another factor's outputs:
beta_factor = factor(hierarchical_model, "beta")
print("label of the factor that produces beta:", beta_factor.label)
print("inputs of that factor:", list(beta_factor.given_spec))
label of the factor that produces beta: site_log_rates inputs of that factor: ['mu', 'tau']
The factor that produces beta is site_log_rates, given mu and tau.
To fit a model such as hierarchical_model to observed counts, condition_on computes the posterior of its parameters, as Conditioning and inference methods describes.
See also¶
- Distributions and families:
conditional_distribution,CoupledMarginal, the factored distributions,glm_likelihood, and the familiesPoissonFamilyandBernoulliFamily. - Operations:
sample,mean,condition_on,joint,marginal, andfactor. - Input and output specs:
NumericArraySpecand the constraintpositive. - Terms: the batches of records that
samplereturns. - Distributions: the operations on a single distribution.
- Functions on values and distributions: functions of the fields of a joint model.
- Conditioning and inference methods: the posterior of a joint model.
- Tutorial 1 writes a likelihood with
conditional_distribution, tutorial 7 merges a likelihood with a posterior to predict new counts, and tutorial 3 chains three factors.