AI-generated. An AI assistant drafted this page, and no maintainer has reviewed it yet. Please report errors on the issue tracker.
Distributions¶
This chapter covers single distributions: the parametric families ProbPipe ships, the operations that summarize a distribution or draw from it, and the support and capabilities each distribution declares. It ends with distributions built from a sampling function or a log density, which represent the models that no family covers. Read it before building a model from more than one distribution, which Joint models and conditional distributions covers.
# 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
from jax.scipy.special import gamma as gamma_function
from jax.scipy.stats import norm
from probpipe import (
BijectorTransformedDistribution,
Gamma,
LogNormal,
Normal,
NumericArraySpec,
Poisson,
SupportsLogProb,
SupportsMean,
SupportsQuantile,
SupportsSampling,
SupportsUnnormalizedLogProb,
SupportsVariance,
bijector_for,
distribution,
log_prob,
mean,
positive,
prob,
quantile,
real,
sample,
summarize,
unnormalized_log_prob,
variance,
workflow_run,
)
# TensorFlow Probability warns that JAX runs in 32-bit precision, which these examples use.
warnings.filterwarnings("ignore", message=r"Explicitly requested dtype float64")
Parametric families¶
ProbPipe ships the standard parametric families, such as Normal, Gamma, and Poisson, and the API reference lists them all.
Each family takes as its first argument the name of its output, the part of a draw that the family fills, and then the family's parameters.
The label of the distribution is the family's name, unless label= sets another.
x = Normal("x", 0.0, 1.0)
g = Gamma("g", 2.0, 3.0)
n = Poisson("n", 4.0)
print("normal distribution:", repr(x))
print("gamma distribution:", repr(g))
print("Poisson distribution:", repr(n))
print("notation of g:", g)
normal distribution: Normal('x', loc=0.0, scale=1.0)
gamma distribution: Gamma('g', concentration=2.0, rate=3.0)
Poisson distribution: Poisson('n', rate=4.0)
notation of g: Gamma(g)
The repr of each distribution names its output and then its parameters, and it shows label= only for a label other than the family's name.
Gamma("g", 2.0, 3.0) is labeled Gamma and fills the output g, and its concentration is 2 and its rate 3.
print shows the shorter notation Gamma(g), which is the label followed by the output.
Array parameters give a distribution whose draws are vectors. The coordinates are independent, and each one has the parameters at its position:
v = Normal("v", jnp.zeros(3), jnp.array([1.0, 2.0, 3.0]))
print("vector normal distribution:", repr(v))
print("shape of one draw:", v.event_shape)
print("event spec of one draw:", v.event_spec)
vector normal distribution: Normal('v', loc=[0.0, 0.0, 0.0], scale=[1.0, 2.0, 3.0])
shape of one draw: (3,)
event spec of one draw: OutputSpec(v=NumericArraySpec(shape=(3,), dtype=float32, support=real))
The event spec event_spec describes one draw: the output v holds an array of shape (3,) of 32-bit floats whose entries can be any real number.
Terms explains these specs, and Joint models and conditional distributions explains how outputs combine.
Operations on a distribution¶
The operations are functions that take the distribution as their first argument.
sample draws from a distribution, and sample_shape sets how many draws it returns.
Every operation that draws random numbers runs inside workflow_run(seed=...), which makes its draws reproducible.
with workflow_run(seed=0):
one_draw = sample(x)
five_draws = sample(n, sample_shape=5)
draws_of_v = sample(v, sample_shape=4)
print("one draw of x:", one_draw.raw)
print("five draws of n:", five_draws.raw)
print("four draws of v, one per row:")
print(draws_of_v.raw)
one draw of x: -0.9115058 five draws of n: [2. 2. 4. 2. 2.] four draws of v, one per row: [[-2.9721317 -1.4887556 -3.6221173 ] [ 0.79898363 2.409431 3.2525835 ] [-2.169697 -5.3292513 1.0098191 ] [-0.19793297 1.1412288 1.5215228 ]]
With a sample_shape, the draws lead with one axis per entry of the shape, and an integer is a shape of one axis.
The four draws of v therefore form a 4 × 3 array.
.raw is the array that a result holds.
log_prob evaluates the log density at a value, and prob evaluates the density itself.
For a discrete distribution such as n, the density is the probability mass:
print("log density of x at 0:", log_prob(x, 0.0).raw)
print("P(n = 3):", prob(n, 3).raw)
print("log density of v at (0, 0, 0):", log_prob(v, jnp.zeros(3)).raw)
print("log density of v at each of its four draws:", log_prob(v, draws_of_v).raw)
log density of x at 0: -0.9189385 P(n = 3): 0.19536662 log density of v at (0, 0, 0): -4.5485754 log density of v at each of its four draws: [ -9.971282 -6.1811714 -10.509134 -4.859577 ]
A draw of v is one vector, so its log density is one number, which is the sum of the log densities of the three independent coordinates.
Given the batch of four draws, log_prob returns one log density per draw.
mean, variance, and quantile summarize a distribution.
The mean and the variance of a vector distribution are vectors, and quantile takes one level or an array of levels:
print("mean of g:", mean(g).raw)
print("variance of g:", variance(g).raw)
print("variance of v:", variance(v).raw)
print("5%, 50%, and 95% quantiles of g:", quantile(g, jnp.array([0.05, 0.5, 0.95])).raw)
mean of g: 0.6666667 variance of g: 0.22222222 variance of v: [1. 4. 9.] 5%, 50%, and 95% quantiles of g: [0.11845382 0.55944896 1.5812881 ]
Each of these results is exact, because the gamma and normal families have formulas for their means, variances, and quantiles.
Where a family has no formula, the operation estimates the result from draws.
The Poisson family has no formula for its quantiles, and quantile.check reports how quantile would compute them without running it:
for name, law in [("g", g), ("n", n)]:
report = quantile.check(law, 0.5)
print(f"median of {name}: route={report.route}, exact={report.exact}")
with workflow_run(seed=1):
print("median of n, estimated from draws:", quantile(n, 0.5).raw)
median of g: route=closed_form, exact=True median of n: route=monte_carlo, exact=False median of n, estimated from draws: 4.0
The route closed_form evaluates a formula, and the route monte_carlo estimates the result from draws, so its result is approximate.
How a result was computed explains routes and the record that each result keeps of how it was computed.
A table of summaries¶
summarize computes the standard summaries of a distribution together: the mean, the standard deviation, the median, and the ends of the central 80% interval.
It returns a record with one field per summary, which displays as a table with one row per output and one column per summary.
The line below the table states which columns are exact and which are estimated from draws, as the record of each result's computation states:
with workflow_run(seed=2):
summary = summarize(x & n)
summary
| mean | sd | median | q10 | q90 | |
|---|---|---|---|---|---|
| x | 0. | 1. | 0. | -1.2815516 | 1.2815511 |
| n | 4. | 2. | 4. | 2. | 6. |
mean, sd: exact. median, q10, q90: Monte Carlo, 256 draws.
The normal and Poisson families have formulas for their means and standard deviations, but the Poisson family has none for its quantiles, so quantile estimates those of n from draws.
Each column is the result of its operation, and a summary and an output index the record, as summary["sd/x"] does.
interval=0.9 sets the interval to 90%, which gives the columns q5 and q95, and statistics passed to summarize replace the default columns:
print("standard deviation of x:", float(summary["sd/x"]))
with workflow_run(seed=3):
print("columns at a 90% interval:", list(summarize((x & n), interval=0.9).children))
print("columns of a table of means and variances:", list(summarize((x & g), mean, variance).children))
standard deviation of x: 1.0 columns at a 90% interval: ['mean', 'sd', 'median', 'q5', 'q95'] columns of a table of means and variances: ['mean', 'variance']
A posterior from an MCMC method also gets the columns r_hat, ess_bulk, and ess_tail, which Checking results describes, and its line below the table gives its chains and draws, as MCMC, 4 chains of 1,000 draws.
mcse=True adds the Monte Carlo standard error of each column, which is 0 where the column is exact.
Supports¶
The support of a distribution is the set of values a draw can take.
The event spec records it, and the support attribute returns it:
for name, law in [("x", x), ("g", g), ("n", n)]:
print(f"support of {name}:", law.support)
support of x: real support of g: positive support of n: non_negative_integer
A normal draw is any real number, a gamma draw is a positive number, and a Poisson draw is a non-negative integer.
Each support is a constraint object, such as real or positive, and its check method tests whether values lie in it:
values = jnp.array([-1.0, 0.0, 2.5])
print("values:", values)
print("in the support of g:", g.support.check(values))
print("in the support of n:", n.support.check(values))
values: [-1. 0. 2.5] in the support of g: [False False True] in the support of n: [False True False]
support is the support that every array in a draw shares.
A draw of a joint distribution holds several arrays, and supports returns the support of each one, keyed by its path, as Joint models and conditional distributions shows.
print("support of each array in a draw of v:", v.supports)
support of each array in a draw of v: {'v': real}
Capabilities¶
A capability is a computation that a distribution provides, such as drawing samples or evaluating its log density.
Each capability has a class, such as SupportsSampling or SupportsLogProb, and isinstance checks whether a distribution claims it:
capabilities = [
SupportsSampling,
SupportsLogProb,
SupportsUnnormalizedLogProb,
SupportsMean,
SupportsVariance,
SupportsQuantile,
]
print(f"{'capability':<30}{'g':>6}{'n':>6}")
for capability in capabilities:
claims_for_g, claims_for_n = isinstance(g, capability), isinstance(n, capability)
print(f"{capability.__name__:<30}{claims_for_g!s:>6}{claims_for_n!s:>6}")
capability g n SupportsSampling True True SupportsLogProb True True SupportsUnnormalizedLogProb True True SupportsMean True True SupportsVariance True True SupportsQuantile True False
Both families draw samples and evaluate their densities, and both have formulas for the mean and the variance.
Only the gamma family claims SupportsQuantile, which is why quantile estimated the median of n from draws.
An operation selects its route from the capabilities that its arguments claim, so a capability that a distribution lacks makes the operation fall back to another route or raise an error.
A distribution from a sampler or a density¶
distribution(sample=..., log_prob=..., unnormalized_log_prob=..., event_spec=..., output_name=...) builds a distribution that no family covers.
It takes a sampling function, a log density, or both, together with the event spec of one draw and the name of its output.
A sampling function takes a JAX random key and returns one draw. Here the draw is the largest of ten standard normal draws:
def largest_of_ten(key: jax.Array) -> jax.Array:
return jnp.max(jax.random.normal(key, (10,)))
largest = distribution(
sample=largest_of_ten,
event_spec=NumericArraySpec((), support=real),
output_name="largest",
)
print("distribution:", largest)
print("repr:", repr(largest))
print("event spec of one draw:", largest.event_spec)
for capability in [SupportsSampling, SupportsLogProb, SupportsMean]:
print(f"claims {capability.__name__}:", isinstance(largest, capability))
distribution: ℙ(largest)
repr: Distribution('largest', sample=largest_of_ten)
event spec of one draw: OutputSpec(largest=NumericArraySpec(shape=(), dtype=float32, support=real))
claims SupportsSampling: True
claims SupportsLogProb: False
claims SupportsMean: False
The distribution has the default label ℙ, so it displays as ℙ(largest).
It claims only SupportsSampling.
Construction traced the sampling function in JAX, without drawing, and filled in the dtype of a draw that the event spec left unset.
The summaries take the route monte_carlo, which estimates them from 1,024 draws, and log_prob has no route:
with workflow_run(seed=2):
print("mean of largest, estimated from draws:", mean(largest).raw)
print("90% interval of largest:", quantile(largest, jnp.array([0.05, 0.95])).raw)
print("route of the mean:", mean.check(largest).route)
print("log_prob applies:", log_prob.check(largest, 1.0).feasible)
mean of largest, estimated from draws: 1.5416135 90% interval of largest: [0.614763 2.602572] route of the mean: monte_carlo log_prob applies: False
The exact mean of the largest of ten standard normal draws is 1.54, and the estimate is close to it.
A density alone also defines a distribution.
The argument unnormalized_log_prob takes a log density up to an additive constant, such as a density whose normalizing constant has no formula.
Here the density is proportional to $\exp(-x^4/4)$, and label= names the distribution quartic:
def quartic_log_density(x: jax.Array) -> jax.Array:
return -0.25 * x**4
quartic = distribution(
unnormalized_log_prob=quartic_log_density,
event_spec=NumericArraySpec((), support=real),
output_name="x",
label="quartic",
)
print("distribution:", quartic)
print("claims SupportsUnnormalizedLogProb:", isinstance(quartic, SupportsUnnormalizedLogProb))
print("claims SupportsSampling:", isinstance(quartic, SupportsSampling))
print("unnormalized log density at 1:", unnormalized_log_prob(quartic, 1.0).raw)
print("log_prob applies:", log_prob.check(quartic, 1.0).feasible)
print("mean applies:", mean.check(quartic).feasible)
distribution: quartic(x) claims SupportsUnnormalizedLogProb: True claims SupportsSampling: False unnormalized log density at 1: -0.25 log_prob applies: False mean applies: False
The distribution evaluates its unnormalized log density, and log_prob, which needs the normalized density, does not apply.
mean does not apply either, because the distribution claims neither a mean nor sampling.
sample takes the route normalize, which draws from the density with an inference method, and sample.check names the method it selects:
print("route and method of sample:", sample.check(quartic).selected.method_name)
with workflow_run(seed=3):
quartic_draws = sample(quartic, sample_shape=1000).raw
exact_second_moment = 2 * gamma_function(0.75) / gamma_function(0.25)
print("E[x^2] estimated from 1,000 draws:", jnp.mean(quartic_draws**2))
print("E[x^2] from its formula:", exact_second_moment)
route and method of sample: normalize/blackjax_nuts E[x^2] estimated from 1,000 draws: 0.66963494 E[x^2] from its formula: 0.67597824
The method blackjax_nuts draws with the No-U-Turn Sampler, so the draws are approximate, and their second moment agrees with the formula $2\,\Gamma(3/4)/\Gamma(1/4)$ to within Monte Carlo error.
Converting and updating distributions shows how to keep such draws as a distribution whose mean and quantiles the operations then compute.
Given both a sampler and a normalized log density, the distribution claims both capabilities. The largest of ten standard normal draws has the density $10\,\varphi(x)\,\Phi(x)^9$, where $\varphi$ and $\Phi$ are the standard normal density and distribution function:
def largest_of_ten_log_density(x: jax.Array) -> jax.Array:
return jnp.log(10.0) + norm.logpdf(x) + 9 * norm.logcdf(x)
largest_with_density = distribution(
sample=largest_of_ten,
log_prob=largest_of_ten_log_density,
event_spec=NumericArraySpec((), support=real),
output_name="largest",
)
for capability in [SupportsSampling, SupportsLogProb]:
print(f"claims {capability.__name__}:", isinstance(largest_with_density, capability))
print("log density at 1.5:", log_prob(largest_with_density, 1.5).raw)
claims SupportsSampling: True claims SupportsLogProb: True log density at 1.5: -0.36364466
A transformed distribution¶
BijectorTransformedDistribution(output_name, base, bijector) is the distribution of $f(X)$ for $X$ drawn from base and an invertible map $f$ given as bijector.
bijector_for returns the canonical invertible map from the real numbers onto a support, which for positive is the exponential function.
The exponential of a normal variable is log-normal, so the transformed distribution matches LogNormal:
exp_of_normal = BijectorTransformedDistribution("y", Normal("z", 0.0, 0.5), bijector_for(positive))
log_normal = LogNormal("y", 0.0, 0.5)
print("support of the transformed distribution:", exp_of_normal.support)
print("log density at 2, transformed distribution:", log_prob(exp_of_normal, 2.0).raw)
print("log density at 2, LogNormal:", log_prob(log_normal, 2.0).raw)
with workflow_run(seed=4):
print("mean from 1,024 draws, transformed distribution:", mean(exp_of_normal).raw)
more_draws = mean.using(num_samples=10_000)(exp_of_normal)
print("mean from 10,000 draws, transformed distribution:", more_draws.raw)
print("exact mean, LogNormal:", mean(log_normal).raw)
support of the transformed distribution: positive log density at 2, transformed distribution: -1.8798445 log density at 2, LogNormal: -1.8798445 mean from 1,024 draws, transformed distribution: 1.1144763 mean from 10,000 draws, transformed distribution: 1.1381361 exact mean, LogNormal: 1.1331484
The two log densities agree, because the transformed distribution evaluates the base log density at the preimage and subtracts the log-determinant of the map's Jacobian there.
The exponential is not affine, so the transformed distribution has no formula for its mean, and mean estimates it from 1,024 draws, the default of the control num_samples.
mean.using(num_samples=10_000) estimates it from 10,000 draws, which brings the estimate closer to the exact mean that LogNormal computes from its formula.
See also¶
- Distributions and families: the families,
distribution,BijectorTransformedDistribution, and the capability classes. - Operations:
sample,log_prob,prob,unnormalized_log_prob,mean,variance,quantile, andsummarize. - Input and output specs:
NumericArraySpec, the constraints such aspositive, andbijector_for. - Terms, Values and records, Joint models and conditional distributions, Converting and updating distributions, and How a result was computed.
- Tutorial 1 builds a prior from parametric families, and tutorial 6 fits a model whose likelihood can only be sampled.