AI-generated. An AI assistant drafted this page, and no maintainer has reviewed it yet. Please report errors on the issue tracker.
Terms¶
ProbPipe describes a probabilistic analysis with a few kinds of object and the operations that connect them. This chapter first shows how those pieces fit together, and then the properties every object shares, which every later chapter relies on.
# 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 jax
import jax.numpy as jnp
import numpy as np
from probpipe import (
ApplicabilityError,
DistributionBatch,
Gamma,
Normal,
NumericArray,
NumericArrayBatch,
NumericArraySpec,
NumericRecordBatch,
Record,
condition_on,
conditional_distribution,
function,
log_prob,
mean,
positive,
sample,
workflow_run,
)
How ProbPipe is organized¶
ProbPipe has three kinds of object, and each object is a term:
| Kind | What it represents | Examples |
|---|---|---|
| value | data, or a number computed from data | NumericArray, Record, Opaque |
| distribution | a probability distribution over values, or a conditional distribution that gives one for each value of its inputs | Normal, EmpiricalDistribution, glm_likelihood(...) |
| function | a computation from values to values | a Python function decorated with @function |
An operation takes terms and returns a term, so the result of one step is the input of the next:
| Operation | What it returns |
|---|---|
sample(d) |
draws from the distribution d, as a batch of values |
log_prob(d, x) |
the log density of d at the value x |
mean(d), quantile(d, q), expectation(d, f) |
a summary of d, as a value |
lik & prior |
the joint distribution of a model |
condition_on(model, data) |
the posterior distribution of the model's other outputs |
marginal(d, "y") |
the distribution of the output y alone |
f(d) for a function f, or pushforward(d, f) |
the distribution of f's output when its input is drawn from d |
A value comes from data, and a distribution from a parametric family, a sampler or a density, or a set of draws.
Operations make every other term, such as a posterior from condition_on or a forecast from a function called on the posterior.
Each operation has several routes, which are ways to compute its result.
It takes an exact route when the distribution supports a closed form, such as the mean of a Normal, and otherwise an approximate one, such as an average over draws or an inference method for a posterior.
check reports which route applies, as How a result was computed shows.
Here a distribution, a value, and a function enter, and three operations return terms:
prior = Normal("mu", 0.0, 1.0)
counts = NumericArray(jnp.array([3.0, 5.0, 2.0]), label="counts")
@function
def doubled(x: jax.Array) -> jax.Array:
return 2.0 * x
with workflow_run(seed=0):
draws = sample(prior, sample_shape=4)
forecast = doubled(prior)
for name, term in [
("prior", prior),
("counts", counts),
("doubled", doubled),
("sample(prior, sample_shape=4)", draws),
("mean(prior)", mean(prior)),
("doubled(prior)", forecast),
]:
print(f"kind of {name}: {type(term).__name__}")
kind of prior: Normal kind of counts: NumericArray kind of doubled: Function kind of sample(prior, sample_shape=4): NumericArrayBatch kind of mean(prior): NumericArray kind of doubled(prior): EmpiricalDistribution
Every result is again a term: draws from a distribution form a batch of values, its mean is a value, and a function called on a distribution gives the distribution of the function's output, here an EmpiricalDistribution of its values at 256 draws.
The rest of this chapter covers what every term shares. An operation reads a term's spec to check and combine its inputs, labels its result so a reader can follow a computation, and records the terms it used in the result's provenance. A term cannot change after it is made, so that record stays accurate, and every kind of term has a batch form, so an operation applies to many inputs at once.
What every term carries¶
We build one term of each of four kinds.
A value constructor takes its data first and its label as the keyword label=.
A family takes first the name of its output, the part of a draw that the family fills, and @function takes the label from the name of the Python function:
weights = NumericArray(jnp.array([0.2, 0.5, 0.3]), label="weights")
site = Record({"count": jnp.array([3, 5, 2]), "area": 1.5}, label="site")
theta = Normal("theta", 0.0, 1.0)
@function
def rescale(x: jax.Array) -> jax.Array:
# Divide by the total, so the entries sum to one.
return x / jnp.sum(x)
for term in [weights, site, theta, rescale]:
print(f"kind: {type(term).__name__}, label: {term.label!r}")
kind: NumericArray, label: 'weights' kind: NumericRecord, label: 'site' kind: Normal, label: 'Normal' kind: Function, label: 'rescale'
We gave theta no label, so its label is the name of its family, as the next section explains.
Record returned a NumericRecord, which is the record class whose fields are all numeric arrays, as Values and records explains.
.raw is the stored data in the form that other libraries accept, such as the JAX array of weights or the TensorFlow Probability distribution that theta stores:
print("stored data of weights:", weights.raw)
print("stored data of site:", site.raw)
print("stored data of theta:", theta.raw)
print("name of the Python function that rescale stores:", rescale.raw.__name__)
stored data of weights: [0.2 0.5 0.3]
stored data of site: {'count': Array([3, 5, 2], dtype=int32), 'area': Array(1.5, dtype=float32, weak_type=True)}
stored data of theta: tfp.distributions.Normal("Normal", batch_shape=[], event_shape=[], dtype=float32)
name of the Python function that rescale stores: rescale
Labels and notation¶
The label names a term in printed output and in the record of how each result was computed. No operation reads a label, so two terms can share one. A constructor derives a label when its data or structure supplies a description:
- a parametric family: the family's name, such as
Normal; - a record: its field names;
- a function or a callable kernel: the Python callable's name, with
𝒻for a lambda function andℙfor a lambda kernel; - a product or mixture: the descriptions of its operands.
Raw arrays and opaque values require label= because their contents do not identify what they represent.
A callable without a name also requires a label.
label= sets another label at construction, and with_label returns a copy under a new label:
prior = Normal("theta", 0.0, 1.0, label="prior")
renamed = theta.with_label("prior")
print("label set at construction:", prior.label)
print("label of the copy:", renamed.label)
print("label of the original:", theta.label)
label set at construction: prior label of the copy: prior label of the original: Normal
A distribution, a conditional distribution, and a function display as their notation, which is the label followed by the signature. The signature states what the term is over:
- a distribution: its outputs;
- a conditional distribution: its outputs, then
|and its inputs; - a function: its parameters.
print and str() show the notation, and repr() shows the class, the label, and the parameters:
def y_given_theta(theta: jax.Array) -> Normal:
return Normal("y", theta, 1.0)
likelihood = conditional_distribution(
y_given_theta, label="likelihood", given_spec={"theta": NumericArraySpec(())}
)
print("notation of prior:", prior)
print("repr of prior:", repr(prior))
print("notation of likelihood:", likelihood)
print("notation of rescale:", rescale)
notation of prior: prior(theta)
repr of prior: Normal('theta', loc=0.0, scale=1.0, label='prior')
notation of likelihood: likelihood(y | theta)
notation of rescale: rescale(x)
prior is over theta, likelihood is over y given theta, and rescale takes the parameter x.
& joins the labels of its operands with ·, so a product displays factor by factor, and with_label names the product:
model = (likelihood & prior).with_label("model")
print("notation of the product:", (likelihood & prior))
print("notation of the model:", model)
notation of the product: likelihood(y | theta)·prior(theta) notation of the model: model(y, theta)
An operation labels its result from the terms that the result was computed from, and it labels a value computed from a distribution in probability notation:
- a draw: its outputs,
~, and the label of the distribution, astheta ~ prior; - a log density:
logand the notation of the distribution, aslog prior(theta); - a mean, a variance, or a quantile:
𝔼,𝕍, orℚand a draw in brackets, as𝔼[theta ~ prior]; - the result of a function: the function's label, and the distribution that a function returns for a distribution displays as the function applied to a draw, as
doubled(theta ~ prior).
with workflow_run(seed=0):
draw = sample(prior)
doubled_prior = doubled(prior)
print("label of a draw of prior:", draw.label)
print("label of the log density of prior:", log_prob(prior, 0.5).label)
print("label of the mean of prior:", mean(prior).label)
print("label of rescale(weights):", rescale(weights).label)
print("notation of doubled(prior):", doubled_prior)
label of a draw of prior: theta ~ prior label of the log density of prior: log prior(theta) label of the mean of prior: 𝔼[theta ~ prior] label of rescale(weights): rescale(weights) notation of doubled(prior): doubled(theta ~ prior)
A distribution computed from another distribution keeps its label.
A conditioned distribution also records the paths at which it is conditioned, after ; in its signature.
Conditioning the model on a value of theta gives the likelihood at that value:
likelihood_at_half = condition_on(model, {"theta": 0.5})
print("the model conditioned on theta = 0.5:", likelihood_at_half)
the model conditioned on theta = 0.5: likelihood(y; theta)
The result is the factor likelihood at theta = 0.5, so it keeps that factor's label, and ; theta records the conditioned path.
The posterior of model given data y displays as model(theta; y) in the same way, as Conditioning and inference methods shows.
A derived label nests the labels it is built from, as 𝔼[theta ~ prior] nests the draw theta ~ prior.
probpipe.config.notation.max_depth, which is 8 by default, sets the number of nested levels that a label or a notation shows.
A deeper part shows as its label or as …, with a warning, so the label of a long chain of operations, such as a loop that adds to a value, stays short.
Immutability¶
A term cannot be changed after construction, so assigning to one of its attributes raises AttributeError:
try:
weights.label = "w"
except AttributeError as error:
print("assigning a label raised:", error)
assigning a label raised: NumericArray is immutable
A change therefore returns a new term and leaves the original as it was, as with_label did above.
Values and records shows the changes to a record's fields, which return new records in the same way.
A term stores the NumPy array it is given and marks the array read-only, so writing into it afterwards raises ValueError:
counts = np.array([3, 5, 2])
count_term = NumericArray(counts, label="counts")
try:
counts[0] = 4
except ValueError as error:
print("writing into the stored array raised:", error)
writing into the stored array raised: assignment destination is read-only
To change the values, build a new array and a new term from it.
To keep the original array writable, pass a copy, as in NumericArray(counts.copy(), label="counts").
A term's annotations are the one part that can be written after construction.
They form a mapping in which diagnostics record their results, as add_mcmc_diagnostics records R-hat and effective sample sizes in Checking results.
Specs¶
A term's spec declares its kind and its structure, and .spec returns it.
Each kind has its own spec class:
NumericArraySpec: the shape, the dtype, and the support of an array;RecordSpec: the spec of each field of a record, andNumericRecordSpecwhen every field is an array;OpaqueSpec: the Python type of a non-numeric value;DistributionSpec: the event spec of one draw of a distribution, whichevent_specreturns;FunctionSpec: the input spec and the output spec of a function;BatchSpec: the spec of each element of a batch and the size of each level.
print("spec of weights:", weights.spec)
print("spec of site:", site.spec)
print("event spec of one draw of theta:", theta.event_spec)
print("spec of rescale:", rescale.spec)
spec of weights: NumericArraySpec(shape=(3,), dtype=float32) spec of site: NumericRecordSpec(count=(3,), area=()) event spec of one draw of theta: OutputSpec(theta=NumericArraySpec(shape=(), dtype=float32, support=real)) spec of rescale: FunctionSpec()
A draw of theta is a scalar under the output theta, and its support real is the set of values a draw can take.
rescale declares neither its inputs nor its output, so its spec is empty, and a call accepts the arguments that its Python body accepts.
Construction checks the value against a spec passed as spec=.
Here the spec declares three positive weights, and the array holds two:
three_positive_weights = NumericArraySpec((3,), support=positive)
try:
NumericArray(jnp.array([0.4, 0.6]), spec=three_positive_weights, label="weights")
except ValueError as error:
print("construction raised:", error)
construction raised: NumericArray 'weights': value of shape (2,) and dtype float32 does not match spec NumericArraySpec(shape=(3,), support=positive)
Construction checks the shape and the dtype.
The support is checked by the operations that depend on it, such as convert in Converting and updating distributions, which refuses a family whose support differs from the distribution's.
A spec can name a dimension in place of a fixed size. Each value binds the name to its own size, and a name used twice takes one size, so this spec declares a square matrix of any size:
square = NumericArraySpec(("n", "n"))
print("named dimensions:", square.free_dims)
print("a 2 x 2 array matches:", square.is_valid(jnp.eye(2)))
print("a 3 x 3 array matches:", square.is_valid(jnp.eye(3)))
print("a 2 x 3 array matches:", square.is_valid(jnp.ones((2, 3))))
print("the spec with n bound to 4:", square.with_dim_sizes(n=4))
named dimensions: frozenset({'n'})
a 2 x 2 array matches: True
a 3 x 3 array matches: True
a 2 x 3 array matches: False
the spec with n bound to 4: NumericArraySpec(shape=(4, 4))
A function can declare its inputs and its output.
@function takes input_spec, which maps each parameter to its spec, and output_spec, which declares the result.
A call then checks its arguments against the input spec and raises ApplicabilityError for an argument that does not match:
@function(input_spec={"counts": NumericArraySpec(("n",))}, output_spec=NumericArraySpec(()))
def total(counts: jax.Array) -> jax.Array:
return jnp.sum(counts)
print("spec of total:", total.spec)
print("total of three counts:", total(jnp.array([3, 5, 2])).raw)
try:
total(jnp.ones((2, 3)))
except ApplicabilityError as error:
print("a matrix of counts raised:", error)
spec of total: FunctionSpec(
input_spec=InputSpec(counts=NumericArraySpec(shape=('n',))),
output_spec=OutputSpec(total=NumericArraySpec(shape=())),
)
total of three counts: 10
a matrix of counts raised: Function 'total' input/counts has rank 2, expected rank 1 from shape ('n',)
The output spec names the output total, and a distribution's event_spec names the outputs of a draw in the same way.
A function's result and a distribution's draw therefore share one kind of spec, the output spec, which Joint models and conditional distributions uses to compose a model from its parts.
Batches¶
Every kind of term has a batch form, which holds several terms of that kind along named axes called levels.
NumericArrayBatch(values, level_names, label=...) builds a batch of arrays, and the leading axes of values are the levels.
Here the heights of three people at each of two sites form a batch on the levels site and person:
heights = NumericArrayBatch(
jnp.array([[1.71, 1.64, 1.80], [1.55, 1.62, 1.70]]),
("site", "person"),
label="heights",
)
print("batch:", repr(heights))
print("spec of the batch:", heights.spec)
batch: NumericArrayBatch(
'heights',
levels={'site': 2, 'person': 3},
element=NumericArraySpec(shape=(), dtype=float32),
)
[[1.71 1.64 1.8 ]
[1.55 1.62 1.7 ]]
spec of the batch: BatchSpec(NumericArraySpec(shape=(), dtype=float32), site=2, person=3)
Each element is one height, so the elements' spec declares a scalar, and the levels hold the six repetitions. A batch of six heights is therefore a different term from one array of six heights: a function called on the batch evaluates at each height, as Functions on values and distributions shows.
Indexing by position selects along the levels in order, and at_levels selects by level name.
A selection that keeps a level returns a smaller batch, and a selection that fixes every level returns an element, labeled by its position:
print("the first site:", repr(heights[0]))
print("the second person at the first site:", repr(heights[0, 1]))
print("the second person at every site:", repr(heights.at_levels(person=1)))
print("shape of the stored array:", heights.raw.shape)
the first site: NumericArrayBatch(
'heights[site=0]',
levels={'person': 3},
element=NumericArraySpec(shape=(), dtype=float32),
)
[1.71 1.64 1.8 ]
the second person at the first site: NumericArray('heights[site=0, person=1]', shape=(), dtype=float32)
1.64
the second person at every site: NumericArrayBatch(
'heights[person=1]',
levels={'site': 2},
element=NumericArraySpec(shape=(), dtype=float32),
)
[1.64 1.62]
shape of the stored array: (2, 3)
.raw is the stored array, whose leading axes are the levels.
A batch of records stores one column per field. Indexing by position returns one record, and indexing by a field name returns that field's column as a batch:
sites = NumericRecordBatch(
{"count": jnp.array([[3, 5, 2], [4, 1, 2]]), "area": jnp.array([1.5, 2.0])},
"site",
label="sites",
)
print("batch of records:", repr(sites))
print("the second site:", repr(sites[1]))
print("fields of the second site:", sites[1].raw)
print("the area column:", repr(sites["area"]))
batch of records: NumericRecordBatch('sites', levels={'site': 2})
count [[3 5 2]
[4 1 2]]
area [1.5 2. ]
the second site: NumericRecord('sites[site=1]')
count [4 1 2]
area 2.
fields of the second site: {'count': Array([4, 1, 2], dtype=int32), 'area': Array(2., dtype=float32)}
the area column: NumericArrayBatch('area', levels={'site': 2}, element=NumericArraySpec(shape=()))
[1.5 2. ]
Most batches come from operations.
sample returns its draws as a batch on the level sample, and the draws of a joint distribution form a batch of records.
workflow_run(seed=...) makes the draws reproducible, as How a result was computed explains:
mu_and_sigma = (Normal("mu", 0.0, 1.0) & Gamma("sigma", 2.0, 1.0))
with workflow_run(seed=0):
draws_of_theta = sample(theta, sample_shape=5)
draws_of_product = sample(mu_and_sigma, sample_shape=4)
print("draws of theta:", repr(draws_of_theta))
print("draws of the product:", repr(draws_of_product))
draws of theta: NumericArrayBatch(
'theta ~ Normal',
levels={'sample': 5},
element=NumericArraySpec(shape=(), dtype=float32, support=real),
)
[-0.9115058 -0.31258115 -0.25014585 -0.56317055 0.02356279]
draws of the product: NumericRecordBatch('(mu, sigma) ~ Normal·Gamma', levels={'sample': 4})
mu [ 0.937207 0.8559094 -1.1693879 0.55234885]
sigma [3.7010229 2.337635 5.793371 2.8639772]
A batch of draws carries the label of one draw, as theta ~ Normal.
Distributions and functions have batch forms as well.
A DistributionBatch holds distributions whose draws share one event spec, and an operation on it returns a batch of results, one per distribution:
growth = DistributionBatch(
[Normal("growth", 0.0, 1.0), Normal("growth", 1.0, 2.0)], "region", label="growth"
)
print("the second distribution:", repr(growth[1]))
print("mean of each distribution:", mean(growth).raw)
the second distribution: Normal('growth', loc=1.0, scale=2.0, label='growth[region=1]')
mean of each distribution: [0. 1.]
Functions on values and distributions calls a function on a batch of inputs and a distribution together, which returns a batch of distributions.
Provenance¶
A term computed by an operation records in its provenance the operation and the terms that the operation used. A term that we construct directly has no provenance:
print("provenance of rescale(weights):", rescale(weights).provenance)
print("provenance of the mean of prior:", mean(prior).provenance)
print("provenance of weights:", weights.provenance)
provenance of rescale(weights): Provenance('workflow.rescale', parents=[rescale, weights])
provenance of the mean of prior: Provenance('workflow.mean', parents=[mean, prior])
provenance of weights: None
How a result was computed follows the provenance of a posterior back to the data it was conditioned on.
See also¶
- Labels and provenance: the API reference for
TrackedTermandProvenance. - Input and output specs: the spec classes and the supports, such as
positive. - Values and records: the API reference for the values and their batches, such as
NumericArrayBatchandRecordBatch. - Values and records: records, their fields, and the values a field can hold.
- Distributions: the event spec of a draw, and the operations on a distribution.
- Functions on values and distributions: functions called on values, distributions, and batches.