AI-generated. An AI assistant drafted this page, and no maintainer has reviewed it yet. Please report errors on the issue tracker.
Converting and updating distributions¶
A distribution in ProbPipe has a representation, such as the parameters of a Normal or a set of weighted draws, and the representation determines which operations have an exact result.
This chapter covers EmpiricalDistribution, which represents a law by weighted draws, and convert, which changes a law's representation, for example by fitting a family to draws.
It then covers resampling, updating a posterior with iterate as each observation arrives, and the bootstrap.
We need these features to pass an MCMC posterior to code that expects a parametric family, or to update a posterior one observation at a time.
# 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 probpipe import (
BootstrapReplicateDistribution,
Distribution,
EmpiricalDistribution,
Gamma,
Normal,
Poisson,
SupportsLogProb,
Weights,
condition_on,
conditional_distribution,
convert,
converter_registry,
iterate,
log_prob,
marginal,
mean,
pushforward,
quantile,
sample,
variance,
with_conversion,
with_resampling,
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")
Empirical distributions¶
An EmpiricalDistribution is a distribution on finitely many points, its atoms, each with a probability called its weight.
We build one from five draws of a rate and their weights, which the constructor normalizes to sum to one.
output_name= names the output that the atoms fill, and label= names the distribution:
rates = EmpiricalDistribution(
jnp.array([2.1, 2.8, 3.0, 3.4, 4.2]),
weights=jnp.array([1.0, 2.0, 3.0, 2.0, 1.0]),
output_name="rate",
label="rates",
)
print("the distribution:", rates)
print("number of atoms:", rates.num_atoms)
print("atoms:", rates.atoms.raw)
print("weights:", rates.weights)
the distribution: rates(rate) number of atoms: 5 atoms: [2.1 2.8 3. 3.4 4.2] weights: [0.11111112 0.22222224 0.33333337 0.22222224 0.11111112]
Without weights, every atom has the same weight.
Weights given on the log scale, such as importance weights, are passed as Weights(log_weights=...), which the constructor adopts as it is.
The operations on an empirical distribution read its atoms and weights:
mean_rate = mean(rates)
print("mean of rate:", mean_rate.raw)
print("mean of rate is exact:", mean_rate.provenance.metadata["exact"])
with workflow_run(seed=0):
draws = sample(rates, sample_shape=8)
print("eight draws of rate:", draws.raw)
mean of rate: 3.077778 mean of rate is exact: True eight draws of rate: [3.4 2.1 3. 4.2 3. 3.4 2.8 3. ]
mean computes the weighted mean of the atoms, which is the exact mean of this law, and variance and quantile are exact in the same way.
sample draws atoms with probability equal to their weights, so every draw is one of the five atoms and the heaviest atom, 3.0, appears most often.
The posterior that condition_on computes with an MCMC method is an EmpiricalDistribution of the chains' draws, so everything in this chapter applies to it.
Changing the representation with convert¶
convert(law, target) returns a law of the class target with the label and outputs of law, so the result can replace law in later code.
Fitting a Normal to the weighted atoms matches its mean and variance to theirs:
normal_fit = convert(rates, Normal)
print("fitted Normal:", repr(normal_fit))
prov_meta = normal_fit.provenance.metadata
print(f"fit provenance: method={prov_meta['method']}, exact={prov_meta['exact']}")
fitted Normal: Normal('rate', loc=3.077778, scale=0.53702426, label='rates')
fit provenance: method=moment_match, exact=False
The converter moment_match made the fit, and the provenance records that the fit is approximate.
The same converter fits other families from the moments their parameters need, so convert(rates, Gamma) fits a Gamma.
The converter registry tries its converters in a fixed order, and converter_registry.list_methods() names them:
print("converters:", converter_registry.list_methods())
converters: ['tfp', 'scipy', 'empirical', 'moment_match', 'kde']
convert.using selects a converter and passes it options:
method: the name of the converter to run, such as"kde";exact_only: withTrue, only exact converters run, so a fit by moments, which is approximate, raisesResolutionError;method_options: a dictionary of the converter's options, such asnum_samples, which sets the number of draws a converter takes from a law, andcheck_support, which the next section describes.
A converter raises TypeError for an option it does not read, and the message names the options it reads.
Here the converter empirical represents a Gamma prior by 2000 of its draws:
prior = Gamma("rate", concentration=2.0, rate=1.0, label="prior")
with workflow_run(seed=1):
prior_draws = convert.using(method_options={"num_samples": 2000})(
prior, EmpiricalDistribution
)
print("number of atoms of the converted prior:", prior_draws.num_atoms)
print("mean of rate, Gamma prior:", mean(prior).raw)
print("mean of rate, 2000 draws of the prior:", mean(prior_draws).raw)
number of atoms of the converted prior: 2000 mean of rate, Gamma prior: 2.0 mean of rate, 2000 draws of the prior: 1.9644487
A target can also be a capability protocol in place of a class.
An empirical distribution has no density, and convert(rates, SupportsLogProb) returns a law that has one, which the converter kde builds as a kernel density estimate of the atoms:
density = convert(rates, SupportsLogProb)
print("kind of the converted law:", type(density).__name__)
print("log density of rate at 3.0:", log_prob(density, 3.0).raw)
kind of the converted law: KDEDistribution log density of rate at 3.0: -0.3996753
Tutorial 4 uses this conversion to plot the density of a forecast.
The support check¶
A fitted family keeps the support of the law it replaces.
convert refuses a family whose support differs from the support that the law declares, such as a Normal for a Gamma law.
For an empirical law, it refuses a family whose support excludes an atom.
Waiting times rounded to whole minutes include zeros, which lie outside the positive support of a Gamma:
waits = EmpiricalDistribution(
jnp.array([0.0, 1.0, 1.0, 2.0, 3.0, 5.0, 8.0]), output_name="wait", label="waits"
)
try:
convert(waits, Gamma)
except ValueError as error:
print("convert refused:", error)
convert refused: cannot convert EmpiricalDistribution 'waits' to Gamma (support=positive): its atoms lie outside that support. Pass check_support=False to override.
The option check_support=False skips the check and fits the family anyway.
The zeros here are short waits that rounding recorded as zero, so a Gamma remains a reasonable model of the waits before rounding:
gamma_fit = convert.using(method_options={"check_support": False})(waits, Gamma)
print("fitted Gamma:", repr(gamma_fit))
fitted Gamma: Gamma('wait', concentration=1.2195122, rate=0.4268293, label='waits')
Resampling weighted atoms¶
Uneven weights reduce what a set of atoms is worth.
The effective sample size is the number of equally weighted atoms that a set of weighted atoms is worth, and Weights computes it:
def effective_sample_size(law: EmpiricalDistribution) -> float:
"""The number of equally weighted atoms that the weighted atoms of *law* are worth."""
return float(Weights(weights=law.weights).effective_sample_size)
print("number of atoms of rates:", rates.num_atoms)
print("effective sample size of rates:", round(effective_sample_size(rates), 2))
number of atoms of rates: 5 effective sample size of rates: 4.26
Resampling draws a new set of atoms from the weighted ones and gives each the same weight, so a heavy atom appears several times and a light one may disappear.
sample draws atoms by weight, and an EmpiricalDistribution of its draws has equal weights:
with workflow_run(seed=2):
resampled = EmpiricalDistribution(sample(rates, sample_shape=1000), output_name="rate")
print("effective sample size after resampling:", round(effective_sample_size(resampled)))
print("mean of rate before resampling:", mean(rates).raw)
print("mean of rate after resampling:", mean(resampled).raw)
effective sample size after resampling: 1000 mean of rate before resampling: 3.077778 mean of rate after resampling: 3.0774999
Resampling approximates the same law and adds Monte Carlo error, which is why a sequential update resamples only when the weights become uneven.
with_resampling, in the next section, makes that decision after each step.
Updating as observations arrive¶
A posterior updated with one observation is the prior for the next.
We observe counts that are Poisson with an unknown rate, and we start from the 2000 draws of the Gamma prior.
condition_on updates draws by Bayes' rule with an exact method, which multiplies each atom's weight by the likelihood of the count at that atom:
def count_given_rate(rate: jax.Array) -> Poisson:
return Poisson("y", rate)
likelihood = conditional_distribution(
count_given_rate, given_spec=prior.event_spec["rate"]
)
def update(belief: EmpiricalDistribution, count: jax.Array) -> EmpiricalDistribution:
"""The law of the rate given *count*, by Bayes' rule."""
return marginal(condition_on((likelihood & belief), {"y": count}), "rate")
report = condition_on.check((likelihood & prior_draws), {"y": jnp.array(3)})
print("route:", report.route)
print("method:", report.method)
print("exact:", report.exact)
route: inference_methods method: empirical_reweighting exact: True
condition_on returns the law of the unobserved fields as a record, and marginal(..., "rate") returns the law of rate alone.
So update returns a law with the same outputs as the law it receives, which lets its result be the input of the next update.
iterate(step, initial, inputs) applies step to the law and each input in turn, and returns a DistributionBatch of the laws it visits, starting with initial:
counts = jnp.array([3, 5, 2, 4, 6, 3, 4, 5])
beliefs = iterate(update, prior_draws, list(counts))
print("kind of result:", type(beliefs).__name__)
print("number of laws:", beliefs.batch_shape[0])
for t in range(len(counts) + 1):
belief = beliefs[t]
print(
f"number of counts {t}: mean of rate {float(mean(belief)):.3f}, "
f"effective sample size {effective_sample_size(belief):.0f}"
)
kind of result: DistributionBatch number of laws: 9 number of counts 0: mean of rate 1.964, effective sample size 2000 number of counts 1: mean of rate 2.465, effective sample size 1464 number of counts 2: mean of rate 3.321, effective sample size 790 number of counts 3: mean of rate 2.982, effective sample size 843 number of counts 4: mean of rate 3.186, effective sample size 677 number of counts 5: mean of rate 3.660, effective sample size 475 number of counts 6: mean of rate 3.559, effective sample size 467 number of counts 7: mean of rate 3.611, effective sample size 424 number of counts 8: mean of rate 3.765, effective sample size 368
Indexing the batch returns the law after that many counts.
The Gamma prior is conjugate to the Poisson likelihood, so the exact posterior after the eight counts is a Gamma whose concentration is 2 plus the sum of the counts and whose rate is 1 plus their number:
exact = Gamma("rate", concentration=2.0 + float(counts.sum()), rate=1.0 + len(counts))
print("mean of rate, exact posterior:", mean(exact).raw)
print("mean of rate, updated draws:", mean(beliefs[len(counts)]).raw)
mean of rate, exact posterior: 3.7777777 mean of rate, updated draws: 3.7646403
The updated draws agree with the exact posterior, but the effective sample size falls with each count, because the weight concentrates on the atoms that agree with the data.
with_resampling(step, ess_threshold=0.5) resamples the result of step whenever its effective sample size falls below half its number of atoms:
with workflow_run(seed=4):
resampled_beliefs = iterate(
with_resampling(update, ess_threshold=0.5), prior_draws, list(counts)
)
for t in range(len(counts) + 1):
belief = resampled_beliefs[t]
print(
f"number of counts {t}: mean of rate {float(mean(belief)):.3f}, "
f"effective sample size {effective_sample_size(belief):.0f}"
)
number of counts 0: mean of rate 1.964, effective sample size 2000 number of counts 1: mean of rate 2.465, effective sample size 1464 number of counts 2: mean of rate 3.365, effective sample size 2000 number of counts 3: mean of rate 3.013, effective sample size 1795 number of counts 4: mean of rate 3.212, effective sample size 1819 number of counts 5: mean of rate 3.689, effective sample size 1575 number of counts 6: mean of rate 3.585, effective sample size 1542 number of counts 7: mean of rate 3.637, effective sample size 1437 number of counts 8: mean of rate 3.790, effective sample size 1286
The update after the second count resamples, and the effective sample size returns to 2000. The resampled atoms repeat the heavy ones, so the number of distinct atoms falls at each resampling, and a long run adds a step that moves the atoms, such as a few MCMC steps. Tutorial 5 runs a particle filter of this kind on a population model.
with_conversion(step, target) converts the result of step to target after each step.
Here each step draws 2000 fresh atoms from the current law, updates them, and fits a Gamma to the updated atoms, so every law in the batch is a Gamma:
draw_atoms = convert.using(method_options={"num_samples": 2000})
def update_from_draws(belief: Distribution, count: jax.Array) -> EmpiricalDistribution:
"""The law of the rate given *count*, computed from 2000 draws of *belief*."""
return update(draw_atoms(belief, EmpiricalDistribution), count)
with workflow_run(seed=3):
fitted_beliefs = iterate(with_conversion(update_from_draws, Gamma), prior, list(counts))
final = fitted_beliefs[len(counts)]
print("kind of the law after eight counts:", type(final).__name__)
print("concentration and rate, fitted Gamma:", float(final.concentration), float(final.rate))
print("concentration and rate, exact posterior:", float(exact.concentration), float(exact.rate))
kind of the law after eight counts: Gamma concentration and rate, fitted Gamma: 34.804542541503906 9.270853042602539 concentration and rate, exact posterior: 34.0 9.0
Each step draws new atoms, so no atom repeats, and the fitted Gamma after eight counts is close to the exact posterior.
The same wrapper converts the draws of an MCMC step into a parametric law that the next step can use as its prior.
Bootstrap distributions¶
The bootstrap estimates the sampling distribution of a statistic by recomputing it on datasets drawn with replacement from the data.
A BootstrapReplicateDistribution is the law of one such dataset, and its draws have as many values as the empirical law it resamples has atoms.
pushforward(replicate, statistic) returns the bootstrap distribution of a statistic, which is the distribution of the statistic over the replicate datasets:
data = EmpiricalDistribution(counts.astype(jnp.float32), output_name="count")
replicate = BootstrapReplicateDistribution("replicate", data)
def sample_mean(dataset: jax.Array) -> jax.Array:
return jnp.mean(dataset)
with workflow_run(seed=4):
bootstrap_mean = pushforward.using(max_evaluations=2000)(replicate, sample_mean)
print("bootstrap standard error of the mean count:", jnp.sqrt(variance(bootstrap_mean).raw))
print(
"bootstrap 90% interval of the mean count:",
quantile(bootstrap_mean, jnp.array([0.05, 0.95])).raw,
)
bootstrap standard error of the mean count: 0.43674207 bootstrap 90% interval of the mean count: [3.25 4.75]
pushforward.using(max_evaluations=2000) sets the number of replicates.
The source of a replicate can be any law that samples, so a fitted family as the source, with replicate_size given, gives the parametric bootstrap.
BootstrapDistribution takes the same arguments, and a draw from it is the EmpiricalDistribution of one replicate.
See also¶
- Distributions and families:
EmpiricalDistribution,BootstrapReplicateDistribution, andBootstrapDistribution. - Conversion:
convertand the converter registry. - Inference methods:
iterate,with_conversion, andwith_resampling. - Values:
Weights. - Operations:
sample,mean,marginal, andcondition_on. - Distributions, Functions on values and distributions, Conditioning and inference methods, and How a result was computed.
- Tutorial 2 computes an MCMC posterior, tutorial 4 converts a forecast to a kernel density estimate, and tutorial 5 runs a particle filter with
iterateandwith_resampling.