Skip to content

AI-generated. An AI assistant drafted this page, and no maintainer has reviewed it yet. Please report errors on the issue tracker.

Random functions

A random function is a distribution over functions, and a random measure is a distribution over distributions. The operations random_log_prob and random_unnormalized_log_prob, which return a random measure's log-density as a random function, are on Operations, and the bootstrap random measure BootstrapDistribution is with the resampling families on Distributions and families.

Random functions

RandomFunction(output_name, event_spec=None, *, label=None)

Bases: Distribution

A distribution over functions, whose value at a point is a distribution.

One draw is a callable, declared by a FunctionSpec. Calling the random function at x returns the law of f(x) for f drawn from it; at stacked points that law is the finite-dimensional law there. A family claims SupportsMean when it has a mean function, SupportsVariance when it has a pointwise variance function, and SupportsSampling when it draws whole functions, each returning a callable. A law over functions has no density in general, so the base claims none.

Parameters:

Name Type Description Default
output_name str

The name of the random function's one output, which names its draws, each a whole term.

required
event_spec OutputSpec or TermSpec

An event spec naming output_name, or the type of one draw, a FunctionSpec. The type defaults to a callable whose input and output are unspecified, which also fills an event spec whose type is unspecified.

None
label str

The random function's label, its class name by default.

None

Raises:

Type Description
TypeError

If output_name is not a string, label is not a non-empty string, or event_spec declares a type that is not a FunctionSpec.

ValueError

If output_name is not a valid output name, or event_spec names another output.

Source code in probpipe/families/_random_functions.py
def __init__(
    self,
    output_name: str,
    event_spec: OutputSpec | TermSpec | None = None,
    *,
    label: str | None = None,
) -> None:
    owner = _class_label(self)
    declaration = _event_of_kind(output_name, event_spec, FunctionSpec, FunctionSpec(), owner)
    super().__init__(
        declaration,
        label=_constructor_label(self, label, owner),
    )

__call__(x) abstractmethod

The law of the drawn function's value at x.

Source code in probpipe/families/_random_functions.py
@abstractmethod
def __call__(self, x: Any) -> Distribution:
    """The law of the drawn function's value at *x*."""

GaussianRandomFunction(output_name, *, label=None, output_spec=None, event_spec=None)

Bases: RandomFunction, SupportsMean, SupportsVariance, ABC

A random function whose finite-dimensional laws are Gaussian.

A concrete member implements predict_mean and predict_variance, and predict_covariance when it evaluates jointly. Each takes stacked inputs X, whose leading axis indexes n input points, and the mean and variance have the shape (n, *output_shape) of the drawn function's value there. The class is not restricted to Gaussian processes: any model with Gaussian predictions is a member.

Calling the random function at X returns the finite-dimensional law there: a MultivariateNormal over the flattened values when the member evaluates jointly and there is more than one value, and otherwise a Normal whose coordinates are the values, which are independent when the member does not evaluate jointly. The law's label is the random function's, and its one output is the drawn function's output.

The function-valued event is a whole term under output_name, and the drawn function's output takes the same name by default; output_spec names another, and event_spec declares the event's type. A type that event_spec declares is a FunctionSpec whose output spec names the drawn function's output; an event spec whose type is unspecified, or a FunctionSpec whose output spec is unspecified, is completed with the drawn function's output spec. The mean is the mean function and the variance the pointwise variance function, each a callable on stacked inputs.

Shifts f + b, scalings alpha * f by a scalar, output-side linear maps A @ f, and sums f + g of independent members are again members, evaluated in closed form. A shift, a scaling, and a linear map of f keep f's label, and a sum is labeled by its expression, as f + g.

Parameters:

Name Type Description Default
output_name str

The name of the random function's one output, which names its draws.

required
label str

The random function's label, its class name by default.

None
output_spec OutputSpec

The drawn function's output spec, which names its one output.

None
event_spec OutputSpec

The event spec of the function-valued draw, naming output_name.

None

Raises:

Type Description
TypeError

If output_name is not a string, label is not a non-empty string, output_spec is not an OutputSpec naming one output, or event_spec is not an OutputSpec or declares a type that is not a FunctionSpec.

ValueError

If event_spec names an output other than output_name, or the FunctionSpec it declares names an output other than the drawn function's.

Source code in probpipe/families/_gaussian.py
def __init__(
    self,
    output_name: str,
    *,
    label: str | None = None,
    output_spec: OutputSpec | None = None,
    event_spec: OutputSpec | None = None,
) -> None:
    _check_output(output_name, _class_label(self))
    output, event = _declarations(output_name, output_spec, event_spec)
    self._output_spec = output
    super().__init__(output_name, event, label=label)

predict_mean(X) abstractmethod

The mean of the drawn function's value at the stacked inputs X.

Source code in probpipe/families/_gaussian.py
@abstractmethod
def predict_mean(self, X: Array) -> Array:
    """The mean of the drawn function's value at the stacked inputs *X*."""

predict_variance(X) abstractmethod

The marginal variance of each value at the stacked inputs X.

Source code in probpipe/families/_gaussian.py
@abstractmethod
def predict_variance(self, X: Array) -> Array:
    """The marginal variance of each value at the stacked inputs *X*."""

predict_covariance(X)

The joint covariance of the flattened values at the stacked inputs X.

The values are flattened in row-major order of (n, *output_shape), so the point index varies slowest.

Parameters:

Name Type Description Default
X Array

The n input points, stacked along the leading axis.

required

Returns:

Type Description
LinOp

A square operator whose size is n times the size of one output value.

Raises:

Type Description
NotImplementedError

If the member does not evaluate jointly.

Source code in probpipe/families/_gaussian.py
def predict_covariance(self, X: Array) -> LinOp:
    """The joint covariance of the flattened values at the stacked inputs *X*.

    The values are flattened in row-major order of ``(n, *output_shape)``,
    so the point index varies slowest.

    Parameters
    ----------
    X : Array
        The ``n`` input points, stacked along the leading axis.

    Returns
    -------
    LinOp
        A square operator whose size is ``n`` times the size of one output value.

    Raises
    ------
    NotImplementedError
        If the member does not evaluate jointly.
    """
    raise NotImplementedError(f"{type(self).__name__} does not evaluate jointly")

__call__(X)

The finite-dimensional law of the drawn function's value at the stacked inputs X.

Parameters:

Name Type Description Default
X Array

The input points, stacked along the leading axis.

required

Returns:

Type Description
Normal or MultivariateNormal

A MultivariateNormal over the flattened values when the member evaluates jointly and there is more than one value, and a Normal otherwise.

Raises:

Type Description
ValueError

If X is a scalar, which stacks no points.

Source code in probpipe/families/_gaussian.py
def __call__(self, X: Array) -> Normal | MultivariateNormal:
    """The finite-dimensional law of the drawn function's value at the stacked inputs *X*.

    Parameters
    ----------
    X : Array
        The input points, stacked along the leading axis.

    Returns
    -------
    Normal or MultivariateNormal
        A ``MultivariateNormal`` over the flattened values when the member evaluates
        jointly and there is more than one value, and a ``Normal`` otherwise.

    Raises
    ------
    ValueError
        If *X* is a scalar, which stacks no points.
    """
    X = _stacked(X)
    mean = jnp.asarray(self.predict_mean(X))
    output = _root_output_name(self._output_spec)
    if mean.size > 1 and self._joint:
        cov = self.predict_covariance(X)
        return MultivariateNormal(output, jnp.reshape(mean, (-1,)), cov=cov, label=self.label)
    scale = jnp.sqrt(jnp.asarray(self.predict_variance(X)))
    return Normal(output, mean, scale, label=self.label)

__rmatmul__(other)

A @ f, the output-side linear map by the matrix other.

Source code in probpipe/families/_gaussian.py
def __rmatmul__(self, other: ArrayLike) -> GaussianRandomFunction:
    """``A @ f``, the output-side linear map by the matrix *other*."""
    return _LinearMapGRF(self, jnp.asarray(other))

probpipe.families.GaussianProcess(output_name, mean_fn, cov_kernel, *, label=None, output_spec=None, event_spec=None)

Bases: GaussianRandomFunction

The Gaussian random function specified by a mean function and a covariance kernel.

Its finite-dimensional law at stacked inputs X has the mean mean_fn(X) and the covariance cov_kernel(X, X). The kernel takes two stacks of n and m points and returns the covariance between their flattened values, of shape (n, m) for a scalar output. A Gaussian process does not draw whole functions.

Parameters:

Name Type Description Default
output_name str

The name of the random function's one output, which names its draws.

required
mean_fn Callable[[Array], Array]

The mean function, evaluated at stacked input points.

required
cov_kernel Callable[[Array, Array], Array]

The covariance kernel, evaluated at two stacks of input points.

required
label str

The process's label, GaussianProcess by default.

None
output_spec OutputSpec

The drawn function's output spec.

None
event_spec OutputSpec

The event spec of the function-valued draw.

None

Raises:

Type Description
TypeError

If mean_fn or cov_kernel is not callable, or output_spec or event_spec is refused as GaussianRandomFunction refuses it.

ValueError

As GaussianRandomFunction raises.

Source code in probpipe/families/_gaussian.py
def __init__(
    self,
    output_name: str,
    mean_fn: Callable[[Array], Array],
    cov_kernel: Callable[[Array, Array], Array],
    *,
    label: str | None = None,
    output_spec: OutputSpec | None = None,
    event_spec: OutputSpec | None = None,
) -> None:
    if not callable(mean_fn) or not callable(cov_kernel):
        raise TypeError(
            f"mean_fn and cov_kernel of GaussianProcess must be callable, got "
            f"{type(mean_fn).__name__} and {type(cov_kernel).__name__}"
        )
    self._mean_fn = mean_fn
    self._cov_kernel = cov_kernel
    super().__init__(output_name, label=label, output_spec=output_spec, event_spec=event_spec)

predict_mean(X)

The mean function at the stacked input points X.

Source code in probpipe/families/_gaussian.py
def predict_mean(self, X: Array) -> Array:
    """The mean function at the stacked input points *X*."""
    return jnp.asarray(self._mean_fn(_stacked(X)))

predict_variance(X)

The kernel's diagonal at each stacked input point of X, shaped like the mean.

Source code in probpipe/families/_gaussian.py
def predict_variance(self, X: Array) -> Array:
    """The kernel's diagonal at each stacked input point of *X*, shaped like the mean."""
    X = _stacked(X)

    def at(point: Array) -> Array:
        block = jnp.asarray(self._cov_kernel(point[None], point[None]))
        side = math.isqrt(block.size)
        return jnp.diagonal(jnp.reshape(block, (side, side)))

    shape = jax.eval_shape(self.predict_mean, X).shape
    return jnp.reshape(jax.vmap(at)(X), shape)

predict_covariance(X)

The kernel at the stacked input points X, over their flattened values.

Source code in probpipe/families/_gaussian.py
def predict_covariance(self, X: Array) -> LinOp:
    """The kernel at the stacked input points *X*, over their flattened values."""
    X = _stacked(X)
    kernel = jnp.asarray(self._cov_kernel(X, X))
    side = math.isqrt(kernel.size)
    return DenseLinOp(jnp.reshape(kernel, (side, side)))

LinearBasisFunction(output_name, basis, weights, *, label=None, output_spec=None, event_spec=None)

Bases: GaussianRandomFunction, SupportsSampling

The random function f(x) = basis(x)ᵀ w with Gaussian weights w.

For w ~ N(m, Σ), the value at x has the mean basis(x)ᵀ m, and the covariance kernel is basis(x)ᵀ Σ basis(x′), so the member evaluates jointly. The basis maps stacked inputs X of n points to features of shape (n, d_w) for a scalar output, or (n, *output_shape, d_w) for an array output, where d_w is the weights' dimension. A draw is the function of one weight draw.

Parameters:

Name Type Description Default
output_name str

The name of the random function's one output, which names its draws.

required
basis Callable[[Array], Array]

The feature map, evaluated at stacked input points.

required
weights MultivariateNormal

The law of the weight vector.

required
label str

The random function's label, LinearBasisFunction by default.

None
output_spec OutputSpec

The drawn function's output spec.

None
event_spec OutputSpec

The event spec of the function-valued draw.

None

Raises:

Type Description
TypeError

If weights is not a MultivariateNormal, basis is not callable, or output_spec or event_spec is refused as GaussianRandomFunction refuses it.

ValueError

As GaussianRandomFunction raises.

Source code in probpipe/families/_gaussian.py
def __init__(
    self,
    output_name: str,
    basis: Callable[[Array], Array],
    weights: MultivariateNormal,
    *,
    label: str | None = None,
    output_spec: OutputSpec | None = None,
    event_spec: OutputSpec | None = None,
) -> None:
    if not isinstance(weights, MultivariateNormal):
        raise TypeError(f"weights must be a MultivariateNormal, got {type(weights).__name__}")
    if not callable(basis):
        raise TypeError(
            f"basis of LinearBasisFunction must be callable, got {type(basis).__name__}"
        )
    self._basis = basis
    self._weights = weights
    self._w_mean = weights.loc
    self._w_cov = weights.cov
    super().__init__(output_name, label=label, output_spec=output_spec, event_spec=event_spec)

predict_mean(X)

basis(X) m at the stacked inputs X.

Source code in probpipe/families/_gaussian.py
def predict_mean(self, X: Array) -> Array:
    """``basis(X) m`` at the stacked inputs *X*."""
    return jnp.einsum("...w,w->...", self._features(X), self._w_mean)

predict_variance(X)

The diagonal of basis(X) Σ basis(X)ᵀ, shaped like the mean.

Source code in probpipe/families/_gaussian.py
def predict_variance(self, X: Array) -> Array:
    """The diagonal of ``basis(X) Σ basis(X)ᵀ``, shaped like the mean."""
    phi = self._features(X)
    return jnp.einsum("...w,wv,...v->...", phi, self._w_cov, phi)

predict_covariance(X)

basis(X) Σ basis(X)ᵀ over the flattened values at the stacked inputs X.

Source code in probpipe/families/_gaussian.py
def predict_covariance(self, X: Array) -> LinOp:
    """``basis(X) Σ basis(X)ᵀ`` over the flattened values at the stacked inputs *X*."""
    phi = self._features(X)
    flat = jnp.reshape(phi, (-1, phi.shape[-1]))
    return DenseLinOp(flat @ self._w_cov @ flat.T)

Random measures

RandomMeasure(output_name, event_spec=None, *, label=None)

Bases: Distribution

A distribution over distributions: one draw is a Distribution.

The event is a DistributionSpec, which declares the event of a drawn law. A family claims SupportsSampling when it draws laws, SupportsMean when it computes the marginalized law D̄(A) = ∫ D(A) dM(D), and SupportsRandomLogProb or SupportsRandomUnnormalizedLogProb only when it computes the law of x ↦ log D(x) for D ~ M, which is a RandomFunction. A random measure claims no variance, since a law-valued draw has no event-typed second moment in general.

Parameters:

Name Type Description Default
output_name str

The name of the random measure's one output, which names its draws, each a whole term.

required
event_spec OutputSpec or TermSpec

An event spec naming output_name, or the type of one draw, a DistributionSpec. The type defaults to a law whose event is opaque under output_name, which also fills an event spec whose type is unspecified.

None
label str

The random measure's label, its class name by default.

None

Raises:

Type Description
TypeError

If output_name is not a string, label is not a non-empty string, or event_spec declares a type that is not a DistributionSpec.

ValueError

If output_name is not a valid output name, or event_spec names another output.

Source code in probpipe/families/_random_functions.py
def __init__(
    self,
    output_name: str,
    event_spec: OutputSpec | TermSpec | None = None,
    *,
    label: str | None = None,
) -> None:
    owner = _class_label(self)
    _check_output(output_name, owner)
    opaque_law = DistributionSpec(OutputSpec(**{output_name: OpaqueSpec()}))
    declaration = _event_of_kind(output_name, event_spec, DistributionSpec, opaque_law, owner)
    super().__init__(
        declaration,
        label=_constructor_label(self, label, owner),
    )

MinibatchedDistribution(prior, likelihood, data, batch_size, *, label=None, with_replacement=False)

Bases: RandomMeasure, SupportsRandomUnnormalizedLogProb

Random measure realised by uniform minibatching.

A draw from this measure is a fixed-minibatch target — an unnormalized stochastic surrogate of the full-data unnormalized log-posterior, rescaled by N / b so the gradient is an unbiased estimator. Not a posterior in the strict (normalized) sense.

For a model with prior :math:p(\theta) and likelihood :math:p(\mathcal{D} \mid \theta) = \prod_i p(d_i \mid \theta), a draw's unnormalized log-density is

.. math::

\log \tilde{D}_B(\theta) = \log p(\theta)
                              + \frac{N}{b}
                                \sum_{d \in B}
                                  \log p(d \mid \theta).

Parameters:

Name Type Description Default
prior SupportsLogProb

Prior distribution over parameters; provides the log-prior term :math:\log p(\theta).

required
likelihood ConditionalDistribution

The kernel of the observations given the prior's fields, whose observations are conditionally independent along the leading axis of its event and which scores a subset of them through _observation_log_prob(given, value, rows), as the kernel glm_likelihood returns does.

required
data array - like

The observed value of the likelihood's event, with the observations along its leading axis, of length >= batch_size.

required
batch_size int

Minibatch size :math:b. Must be 1 <= b <= len(data).

required
label str

The measure's label. By default the label is minibatch, and the notation shows the construction over the prior and the likelihood, as minibatch(prior(beta), lik(y | beta), batch_size=40). A prior that is not a Distribution has no label to show, so it requires one.

None
with_replacement bool

Sample minibatch indices with replacement. By default each draw selects a uniform size-b subset in random order. Different draws may reuse observations.

False

Raises:

Type Description
TypeError

If prior is not SupportsLogProb, or likelihood is not a kernel that scores a subset of its observations, or label is None for a prior that is not a Distribution.

ValueError

If data has no leading axis, or batch_size is not in [1, len(data)].

Source code in probpipe/inference/_minibatch.py
def __init__(
    self,
    prior: SupportsLogProb,
    likelihood: ConditionalDistribution,
    data: ArrayLike,
    batch_size: int,
    *,
    label: str | None = None,
    with_replacement: bool = False,
):
    if not isinstance(prior, SupportsLogProb):
        raise TypeError(
            f"MinibatchedDistribution: prior must have a log-density (SupportsLogProb), "
            f"got {_described(prior)}"
        )
    if not _reads_observations(likelihood):
        raise TypeError(f"MinibatchedDistribution: {_subset_scoring_reason(likelihood)}")

    n = _data_size(data)
    if batch_size < 1 or batch_size > n:
        raise ValueError(f"batch_size must be in [1, len(data)={n}]; got {batch_size}")

    expression = None
    if label is None:
        if not isinstance(prior, TrackedTerm):
            raise TypeError(
                f"MinibatchedDistribution cannot take its label from a prior of type "
                f"{type_name(prior)}, which has no label; pass label=..."
            )
        expression = Applied(
            "minibatch",
            (prior._embedded_expression(), likelihood._embedded_expression()),
            (("batch_size", constant(int(batch_size))),),
        )

    self._prior = prior
    self._likelihood = likelihood
    self._data = data
    self._n = n
    self._batch_size = int(batch_size)
    self._with_replacement = bool(with_replacement)
    self._rescale_factor = float(self._n / batch_size)
    # A draw is a law over the prior's parameters, declared as the prior
    # declares them.
    self._draw_event_spec = _parameter_declaration(prior, "parameters")

    # A draw is one fixed-minibatch target, the measure's one output.
    super().__init__("target", DistributionSpec(self._draw_event_spec), label=label)
    if expression is not None:
        self._store_expression(expression)

dataset_size property

Total number of observations in the dataset (len(data)).

Named dataset_size rather than num_atoms (the finite-sample-size convention used by EmpiricalDistribution and siblings) because MinibatchedDistribution is not a finite-sample distribution; it doesn't hold a finite collection of realisations.

batch_size property

Minibatch size :math:b.

with_replacement property

Whether minibatch indices are drawn with replacement.

prior property

The prior distribution over parameters.

likelihood property

The kernel of the conditionally independent observations.

data property

The full dataset (not the minibatched view).