Distributions (optix.distributions)
Gamma, Normal, Dirichlet and Categorical distributions with their sufficient statistics and conjugate updates. See Probability distributions for a guided tour.
Probability distributions for variational Bayes and conjugate updates.
Two layers:
- [
functional][optix.distributions.functional]: pure tensor functions (means, expectations, entropies, log-densities, KL divergences), one canonical signature per family, safe to inline into compiled kernels; - classes (
Gamma,Dirichlet,Categorical,Normal) that accept several parameterisations, store the one they were given, derive the others on demand, and dispatchkl_divergenceandposterior.
Accumulated sufficient statistics
(SuffStats subclasses) are mergeable
containers consumed by posterior and
the fit classmethods.
Gamma
Gamma(shape, rate=None, *, scale=None, mean=None, validate=False, cache=False, dtype=None, device=None)
Bases: Distribution
Gamma distribution over x > 0, elementwise (event shape ()).
p(x) = b^a x^(a − 1) exp(−b x) / Γ(a) with shape a and rate b.
Note
Give shape with exactly one of rate, scale or mean;
the given pair is stored, everything else is derived on access. The
canonical parameters of
[functional][optix.distributions.functional] are (shape, rate).
Exponential family: T(x) = (log x, x), η = (a − 1, −b), A = log Γ(a) − a log b, h(x) = 1.
Create a Gamma distribution from one of its parameterisations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
Tensor or float
|
Shape a > 0. |
required |
rate
|
Tensor or float
|
Rate b > 0. |
None
|
scale
|
Tensor or float
|
Scale 1 / b. |
None
|
mean
|
Tensor or float
|
Mean a / b (the "mean / shape" parameterisation (μ, ν)). |
None
|
validate
|
bool
|
Check the parameter values (synchronises). Default False. |
False
|
cache
|
bool
|
Cache derived parameters (see
|
False
|
dtype
|
dtype | None
|
Default: those of the tensors (see
|
None
|
device
|
dtype | None
|
Default: those of the tensors (see
|
None
|
shape
property
shape
Shape a, (*batch).
rate
property
rate
Rate b, (*batch).
scale
property
scale
Scale 1 / b, (*batch).
mean
property
mean
E[x] = a / b.
variance
property
variance
Var[x] = a / b².
mean_log
property
mean_log
E[log x] = ψ(a) − log b.
In the mean / shape parameterisation it is computed as log μ − (log ν − ψ(ν)), without cancellation.
mean_inv
property
mean_inv
E[1 / x] = b / (a − 1); inf where a ≤ 1.
from_mean_shape
classmethod
from_mean_shape(mean, shape, **kwargs)
Gamma with mean μ and shape ν (rate ν / μ).
entropy
entropy()
H = a − log b + log Γ(a) + (1 − a) ψ(a).
log_prob
log_prob(value)
a log b − log Γ(a) + (a − 1) log x − b x.
natural_params
natural_params()
(a − 1, −b).
log_normalizer
log_normalizer()
A = log Γ(a) − a log b.
expected_stats
expected_stats()
(E[log x], E[x]).
from_natural
classmethod
from_natural(eta_log_x, eta_x)
Gamma with natural parameters (a − 1, −b).
to_torch
to_torch()
torch.distributions.Gamma(shape, rate).
fit
classmethod
fit(data, weight=None, *, dim=REQUIRED, mean=None, init=None, niter=16)
Maximum-likelihood Gamma from samples or accumulated statistics.
With n = ∑ₙ wₙ, x̄ = ∑ₙ wₙ xₙ / n and l̄ = ∑ₙ wₙ log xₙ / n, the
shape ν solves log ν − ψ(ν) = c (see
fit_gamma_shape) with
meanfree: μ = x̄ and c = log x̄ − l̄;meanfixed: μ =mean, ρ = x̄ / μ and c = (ρ − 1 − log ρ) + (log x̄ − l̄).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
(GammaStats, Tensor or array - like)
|
Either accumulated statistics, or positive samples xₙ > 0.
Samples are reduced with
|
required |
weight
|
Tensor
|
Non-negative frequency weights (or a boolean mask) of the
samples, broadcastable to |
None
|
dim
|
int or sequence of int or None
|
Reduced dims of the samples ( |
REQUIRED
|
mean
|
Tensor or float
|
Fixed mean; only the shape is fitted. |
None
|
init
|
Gamma
|
Returned where n = 0; otherwise those entries are NaN. |
None
|
niter
|
int
|
Newton iterations. |
16
|
Returns:
| Type | Description |
|---|---|
Gamma
|
Stored in the mean / shape parameterisation (μ, ν), with the
batch shape of the statistics (broadcast with |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
Normal
Normal(mean, var=None, *, std=None, precision=None, validate=False, cache=False, dtype=None, device=None)
Bases: Distribution
Normal distribution, elementwise (event shape ()).
Note
Give exactly one of var, std or precision. It is stored as
given; the others are derived on access. The canonical parameters of
[functional][optix.distributions.functional] are
(mean, precision).
A "diagonal" multivariate Normal is this class with a trailing batch
dim of size K; reduce it yourself, e.g. kl_divergence(q, p).sum(-1).
Exponential family: T(x) = (x, x²), η = (λμ, −λ/2), A = λμ² / 2 − ½ log λ, log h = −½ log(2π).
Create a Normal distribution from one of its parameterisations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mean
|
Tensor or float
|
Mean μ. |
required |
var
|
Tensor or float
|
Variance σ² (also the unnamed second argument:
|
None
|
std
|
Tensor or float
|
Standard deviation σ. |
None
|
precision
|
Tensor or float
|
Precision λ = 1 / σ². Zero is a flat (improper) direction: entropy and KL are infinite, conjugate updates stay valid. |
None
|
validate
|
bool
|
See |
False
|
cache
|
bool
|
See |
False
|
dtype
|
bool
|
See |
False
|
device
|
bool
|
See |
False
|
mean
property
mean
Mean μ = E[x], (*batch).
precision
property
precision
Precision λ = 1 / σ².
var
property
var
Variance σ².
std
property
std
Standard deviation σ = √σ².
mean_sq
property
mean_sq
E[x²] = μ² + σ².
entropy
entropy()
H = (1 + log(2π) − log λ) / 2.
log_prob
log_prob(value)
(log λ − log(2π) − λ (x − μ)²) / 2.
natural_params
natural_params()
(λμ, −λ/2).
log_normalizer
log_normalizer()
A = λμ² / 2 − ½ log λ.
expected_stats
expected_stats()
(E[x], E[x²]) = (μ, μ² + σ²).
from_natural
classmethod
from_natural(eta_x, eta_x_sq)
Normal with natural parameters (λμ, −λ/2).
to_torch
to_torch()
torch.distributions.Normal(mean, std).
Dirichlet
Dirichlet(concentration, *, validate=False, cache=False, dtype=None, device=None)
Bases: Distribution
Dirichlet distribution over the simplex (event shape (K,)).
p(π) = Γ(α₀) ∏ₖ πₖ^(αₖ − 1) / ∏ₖ Γ(αₖ) with α₀ = ∑ₖ αₖ.
Note
Exponential family: T(π) = log π, η = α − 1, A = ∑ₖ log Γ(αₖ) − log Γ(α₀), h = 1.
Create a Dirichlet distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
concentration
|
(*batch, K) Tensor
|
Concentration α > 0. |
required |
validate
|
bool
|
See |
False
|
cache
|
bool
|
See |
False
|
dtype
|
bool
|
See |
False
|
device
|
bool
|
See |
False
|
concentration
property
concentration
Concentration α, (*batch, K).
mean
property
mean
E[π] = α / α₀, (*batch, K).
variance
property
variance
Var[πₖ] = αₖ (α₀ − αₖ) / (α₀² (α₀ + 1)).
mean_log
property
mean_log
E[log π] = ψ(α) − ψ(α₀), (*batch, K).
entropy
entropy()
∑ₖ log Γ(αₖ) − log Γ(α₀) + (α₀ − K) ψ(α₀) − ∑ₖ (αₖ − 1) ψ(αₖ).
log_prob
log_prob(value)
log Γ(α₀) − ∑ₖ log Γ(αₖ) + ∑ₖ (αₖ − 1) log πₖ.
natural_params
natural_params()
(α − 1,).
log_normalizer
log_normalizer()
A = ∑ₖ log Γ(αₖ) − log Γ(α₀).
expected_stats
expected_stats()
(E[log π],).
from_natural
classmethod
from_natural(eta_log_x)
Dirichlet with natural parameters (α − 1,).
to_torch
to_torch()
torch.distributions.Dirichlet(concentration).
fit
classmethod
fit(data, init, weight=None, *, dim=REQUIRED, niter=16)
Maximum-likelihood Dirichlet from samples or accumulated statistics.
With n = ∑ₙ wₙ and sₖ = ∑ₙ wₙ log xₙₖ, maximises
n (log Γ(α₀) − ∑ₖ log Γ(αₖ)) + ∑ₖ (αₖ − 1) sₖ with
fit_dirichlet, started at
init.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
(DirichletStats, Tensor or array - like)
|
Either accumulated statistics, or points xₙ of the simplex
with shape |
required |
init
|
Dirichlet or (..., K) Tensor
|
Starting point (required: Newton's method only converges locally; pass the current estimate). Returned where n = 0. |
required |
weight
|
Tensor
|
Non-negative frequency weights (or a boolean mask) of the
points, broadcastable to |
None
|
dim
|
int or sequence of int or None
|
Reduced batch dims of the points ( |
REQUIRED
|
niter
|
int
|
Iterations. |
16
|
Returns:
| Type | Description |
|---|---|
Dirichlet
|
Batch shape: that of the statistics, broadcast with |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
Categorical
Categorical(probs=None, *, logits=None, validate=False, cache=False, dtype=None, device=None)
Bases: Distribution
Categorical distribution over K categories (event shape ()).
Note
Give exactly one of probs or logits; it is stored as given
(unnormalised, categories in the last dim) and the normalised forms
are derived on access. Categorical(logits=elog_pi + elog_lik) is
the variational update of responsibilities.
Values. The representation of a value is read from its dtype:
- integer dtype: labels in
[0, K), shape(*batch,); - floating or boolean dtype: one-hot or soft assignments
r, shape(*batch, K);log_prob(r)= ∑ₖ rₖ log pₖ is the expected log-likelihood used by variational Bayes.
Integers always mean labels, including the int64 output of
torch.nn.functional.one_hot: cast it with .float() or
.bool() first.
sample returns int64
labels, or float one-hot vectors with one_hot=True. Expectations
(mean = probs), entropy
and KL do not depend on the representation. There is no
reparameterised sampling (as in torch,
rsample raises).
Exponential family: T(z) = onehot(z), η = log p (up to an additive constant), A = logsumexp(η), E[T] = p.
Create a Categorical distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
probs
|
(*batch, K) Tensor
|
Non-negative weights, normalised by their sum. |
None
|
logits
|
(*batch, K) Tensor
|
Log-weights, normalised by |
None
|
validate
|
bool
|
False
|
|
cache
|
bool
|
False
|
|
dtype
|
bool
|
False
|
|
device
|
bool
|
False
|
num_categories
property
num_categories
Number of categories K.
logits
property
logits
Normalised logits log p, (*batch, K).
probs
property
probs
Normalised probabilities p, (*batch, K).
mean
property
mean
E[onehot(z)] = p, (*batch, K).
variance
property
variance
Var[zₖ] = pₖ (1 − pₖ) for one-hot z, (*batch, K).
params
params()
Normalised logits (log p,), unexpanded.
entropy
entropy()
H = −∑ₖ pₖ log pₖ (0 log 0 = 0, finite gradients).
log_prob
log_prob(value)
Log-probability of labels, or expected log-likelihood.
Note
Without validate=True, labels are not range-checked: an
out-of-range label raises a RuntimeError on the CPU and a
device-side assert on CUDA (which leaves the CUDA context
unusable), so validate labels when their source is not trusted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
Tensor
|
Integer labels |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Broadcast of the value's batch shape and
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the last dim of an assignment is not |
sample
sample(sample_shape=(), *, one_hot=False)
Samples: int64 labels, or float one-hot vectors (one_hot).
Labels have shape (*sample_shape, *batch); one-hot vectors
(*sample_shape, *batch, K) in the distribution's dtype.
natural_params
natural_params()
(η,): the stored log-weights, up to an additive constant.
For logits these are the given logits, for probs their
logarithm (unnormalised), so that log_normalizer is
logsumexp(η).
log_normalizer
log_normalizer()
A = logsumexp(η) (zero when normalised).
expected_stats
expected_stats()
(E[onehot(z)],) = (p,), whatever the view.
from_natural
classmethod
from_natural(eta)
Distribution with logits eta (η), stored as given.
to_torch
to_torch()
torch.distributions.Categorical(logits=logits).
Distribution
Base of all distributions: parameterisations, shapes and dispatch.
Parameterisations. A family declares several parameterisations
(_forms: tuples of parameter names). An object stores exactly the
tensors of the one it was built with
(form) and derives every
other parameter on demand (_derive), e.g. the precision of a
Normal given by its variance. params() returns the canonical
parameterisation (_canonical), which is what the
[functional][optix.distributions.functional] kernels take.
Later families declare their forms the same way, e.g. (sketch):
class MultivariateNormal(Distribution):
_forms = {
("mean", "covariance"): (1, 2),
("mean", "precision"): (1, 2),
("mean", "scale_tril"): (1, 2),
("mean", "precision_tril"): (1, 2),
}
_canonical = ("mean", "precision_tril")
_event_ndim = 1
# _check_events: mean (K,) against matrices (K, K)
# _derive("precision_tril"): cholesky / flip trick, ...
class Wishart(Distribution):
_forms = {("df", "scale"): (0, 2), ("df", "rate"): (0, 2),
("df", "mean"): (0, 2)} # mean = df * scale
and a conjugate update returns the form in which it is additive (a
Wishart posterior in (df, rate)).
Caching. Derived quantities are recomputed on every access unless
caching is switched on (cache=True at construction, or
q.cache = True). An entry is reused only while the stored tensors
keep the version counters they had when it was computed, so an
in-place change of a parameter (s.mul_(2)) invalidates it. The
cache is bypassed while compiling (traced functions have no side
effects and never see it), when a stored tensor requires gradients (a
cached graph would break a second backward pass) and for inference
tensors (which have no version counter). A derived parameter has the
broadcast shape of the stored tensors it is computed from (e.g. the
rate of a Gamma given by a scalar shape and a per-pixel mean is
per-pixel), and is cached with that shape.
Shapes. Parameters are stored with their own shapes (not expanded
to the batch shape), so a scalar prior against per-pixel posteriors
costs nothing; public parameter attributes and method results are
expand views of shape batch_shape + event. Returned tensors
must not be modified in place (clone() first).
dtype and device follow the parameter tensors (promoted between floating dtypes); the configuration is used only when no parameter is a floating-point tensor.
Objects are immutable by convention. Values are not checked unless
validate=True is passed or
validate is called (both
synchronise with the host).
form
property
form
Names of the stored parameters (the parameterisation given).
cache
property
writable
cache
Whether derived quantities are cached (off while compiling).
batch_shape
property
batch_shape
Broadcast batch shape of the parameters.
event_shape
property
event_shape
Shape of one sample.
dtype
property
dtype
Floating dtype of the parameters.
device
property
device
Device of the parameters.
mean
property
mean
E[x].
variance
property
variance
Var[x] (elementwise / marginal).
params
params()
Canonical parameters, unexpanded, for functional kernels.
validate
validate()
Check parameter values (synchronises); return self.
Skipped while compiling.
Raises:
| Type | Description |
|---|---|
ValueError
|
If a stored parameter violates its constraint. |
expand
expand(batch_shape)
Same distribution with a larger batch shape (no copy).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_shape
|
sequence of int
|
Target batch shape, broadcast-compatible with
|
required |
Returns:
| Type | Description |
|---|---|
Distribution
|
A new object sharing the stored tensors. |
__getitem__
__getitem__(index)
Index the batch dims (basic indexing only); event dims kept.
to
to(device=None, dtype=None)
Copy on another device and/or floating dtype (new object).
detach
detach()
Same distribution with detached parameters.
entropy
entropy()
Differential (or discrete) entropy, shape batch_shape.
log_prob
log_prob(value)
Log-density at value of shape (*sample, *batch, *event).
log_normalizer
log_normalizer()
Log-normalizer A(η), shape batch_shape.
from_natural
classmethod
from_natural(*eta)
Distribution with natural parameters eta (η).
to_torch
to_torch()
Equivalent torch.distributions object (no validation).
kl
kl(other)
kl_divergence(self, other).
posterior
posterior(stats, **known)
posterior(self, stats, **known).
GammaStats
GammaStats(n, sum_x, sum_log_x)
Bases: SuffStats
Statistics of a Gamma likelihood: (n, sum_x, sum_log_x).
Build the statistics from their fields.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
Tensor
|
Total weight ∑ₙ wₙ. |
required |
sum_x
|
Tensor
|
∑ₙ wₙ xₙ. |
required |
sum_log_x
|
Tensor
|
∑ₙ wₙ log xₙ. |
required |
from_samples
classmethod
from_samples(x, weight=None, *, dim, dtype=None)
Statistics of observed positive samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
Samples > 0. |
required |
weight
|
Tensor
|
Non-negative frequency weights (or a boolean mask),
broadcastable to |
None
|
dim
|
int or sequence of int or None
|
Reduced dims ( |
required |
dtype
|
dtype
|
dtype of the result (the reduction runs in |
None
|
Returns:
| Type | Description |
|---|---|
GammaStats
|
log x uses |
from_expectations
classmethod
from_expectations(log_x, x, weight=None, *, dim, dtype=None)
Statistics of latent samples given E[log x] and E[x].
The arguments are the fields of Gamma.expected_stats();
weight, dim and dtype as in
from_samples.
NormalStats
NormalStats(n, mean, scatter)
Bases: SuffStats
Statistics of a Normal likelihood, central form (n, mean, scatter).
mean = ∑ₙ wₙ xₙ / n and scatter = ∑ₙ wₙ (xₙ − mean)², the same
state as optix.stats.Moments(order=2). Raw power sums are never
formed, so large offsets do not destroy the scatter in float32.
References
- Pébay P. Formulas for robust, one-pass parallel computation of covariances and arbitrary-order statistical moments. Sandia National Laboratories report SAND2008-6212, 2008. doi:10.2172/1028931
BibTeX
@techreport{pebay2008,
author = {P{'e}bay, P.},
title = {Formulas for robust, one-pass parallel
computation of covariances and arbitrary-order
statistical moments},
institution = {Sandia National Laboratories},
number = {SAND2008-6212},
year = {2008},
doi = {10.2172/1028931}
}
Build the statistics from their fields.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
Tensor
|
Total weight. |
required |
mean
|
Tensor
|
Weighted mean (any value where n = 0, conventionally 0). |
required |
scatter
|
Tensor
|
Weighted sum of squared deviations from |
required |
sum_x
property
sum_x
∑ₙ wₙ xₙ = n · mean (in the fields' dtype).
sum_x_sq
property
sum_x_sq
∑ₙ wₙ xₙ² = scatter + n · mean² (in the fields' dtype).
from_samples
classmethod
from_samples(x, weight=None, *, dim, dtype=None)
Statistics of observed samples (two passes, central form).
See from_samples
of GammaStats.
from_expectations
classmethod
from_expectations(x, x_sq, weight=None, *, dim, dtype=None)
Statistics of latent samples given E[x] and E[x²].
scatter = ∑ₙ wₙ (E[x²] − E[x]²) + ∑ₙ wₙ (E[x] − mean)².
from_moments
classmethod
from_moments(moments)
(count, mean, m2) of an optix.stats.Moments.
mean and m2 are not copied; the count is stored as a
float64 (or int64) count.
Requires order >= 2 and at least one update.
DirichletStats
DirichletStats(n, sum_log_x)
Bases: SuffStats
Statistics of a Dirichlet likelihood: (n, sum_log_x).
Build the statistics from their fields.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
Tensor
|
Total weight ∑ₙ wₙ, shape |
required |
sum_log_x
|
(*batch, K) Tensor
|
∑ₙ wₙ log xₙ. |
required |
from_samples
classmethod
from_samples(x, weight=None, *, dim, dtype=None)
Statistics of observed points x of the simplex (..., K).
weight broadcasts against x.shape[:-1]; dim are batch
dims (the last dim of x is the event); see
GammaStats.from_samples.
from_expectations
classmethod
from_expectations(log_x, weight=None, *, dim, dtype=None)
Statistics of latent probability vectors given E[log x].
log_x is Dirichlet.expected_stats().log_x (or
Dirichlet.mean_log), shape (..., K).
CategoricalStats
CategoricalStats(counts)
Bases: SuffStats
Statistics of a categorical likelihood: counts (*batch, K).
Build the statistics from the counts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
counts
|
(*batch, K) Tensor
|
Weighted counts ∑ₙ wₙ onehot(zₙ) (or ∑ₙ wₙ pₙ for soft
assignments). |
required |
n
property
n
Total weight counts.sum(-1).
from_samples
classmethod
from_samples(x, weight=None, *, dim, dtype=None)
Statistics of one-hot or soft assignments x (..., K).
See from_samples
of GammaStats; for integer labels use
from_labels.
from_expectations
classmethod
from_expectations(x, weight=None, *, dim, dtype=None)
Statistics of latent labels given their probabilities E[x].
x is Categorical.expected_stats().x (the responsibilities).
from_labels
classmethod
from_labels(index, num_classes, weight=None, *, dim, dtype=None)
Statistics of integer labels in [0, num_classes).
Note
The labels are scattered into a (*kept, K) buffer: no one-hot
tensor of the data's size is built. Weights are summed in their
own floating dtype (integer or boolean weights in the
configuration's), then stored in float64.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
Tensor
|
Integer labels; all its dims are batch dims. |
required |
num_classes
|
int
|
Number of categories K. |
required |
weight
|
Tensor | None
|
As in |
None
|
dim
|
Tensor | None
|
As in |
None
|
dtype
|
Tensor | None
|
As in |
None
|
SuffStats
Weighted sufficient statistics of samples from one family.
Holds ∑ₙ wₙ T(xₙ) and the total weight n = ∑ₙ wₙ over a set of samples
(observed values, or expectations of latent ones). This is what models
accumulate over batches and what
posterior and the fit
classmethods consume.
Fields have shape (*batch, *field_event) and are broadcast against
each other. dtype: the statistics of a batch are reduced in the
data's own dtype (no data-sized upcast); dtype= in the
constructors casts only the reduced result, which is how a float64
running state is obtained from float32 data. Counts (n, and
the counts of
CategoricalStats) are small
and exact whatever the data dtype: int64 when unweighted, float64 when
they are sums of weights (a float32 count stops counting past 2²⁴).
Merging an int64 count with a float64 one gives a float64 count, and
dtype,
to and the constructors'
dtype= apply to the other fields only.
Statistics merge with + (out of place),
add_ (in place, also
available as merge) and
sum (over batch dims);
zeros() is the identity of + and n = 0 entries are legal
everywhere. Weights must be non-negative (not checked).
n
property
n
Total weight ∑ₙ wₙ, shape broadcastable to the batch.
batch_shape
property
batch_shape
Broadcast batch shape of the fields.
event_shape
property
event_shape
Event shape of the statistics (that of the family).
dtype
property
dtype
dtype of the fields other than the count (see the class notes).
For CategoricalStats,
whose only field is a count, the dtype of the counts.
device
property
device
Device of the fields.
astuple
astuple()
Fields, in declaration order (unexpanded).
__add__
__add__(other)
Merge, out of place, on broadcast batch shapes.
__radd__
__radd__(other)
0 + s, so that sum([s1, s2, ...]) works.
add_
add_(other)
Merge other into self, in place; return self.
self's fields must have the full batch shape and own their
memory (build it with zeros or
copy). other is
cast to self's dtype and device first, so a float64
accumulator accepts float32 batch statistics. An int64 count that
receives a float64 (weighted) count is replaced by a float64
tensor (the only field that is not updated in place).
scale
scale(factor)
Statistics with the total weight multiplied by factor.
Used for tempering, subsampling corrections and stochastic VB.
sum
sum(dim=None)
Merge along batch dims (None: all); event dims are kept.
Negative dims count from the last batch dim.
to
to(device=None, dtype=None)
Copy on another device and/or floating dtype.
Unlike optix.stats.Reducer.to, this returns a new object. The
count keeps its int64 / float64 dtype.
copy
copy()
Independent copy with full-shape, owned fields (an accumulator).
state_dict
state_dict()
{"class", "args", "state"}, as Reducer.state_dict.
zeros
classmethod
zeros(batch_shape=(), *, event_shape=(), dtype=None, device=None)
Empty accumulator (identity of +) with owned fields.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_shape
|
sequence of int
|
Batch shape. |
()
|
event_shape
|
sequence of int
|
Event shape of the family ( |
()
|
dtype
|
dtype | None
|
Default: the configuration. Pass |
None
|
device
|
dtype | None
|
Default: the configuration. Pass |
None
|
GammaExpectations
NormalExpectations
DirichletExpectations
CategoricalExpectations
kl_divergence
kl_divergence(q, p)
KL(q ‖ p), elementwise over the broadcast batch shape.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
q
|
Distribution
|
Distributions with the same event shape and broadcastable batch
shapes. Broadcasting is right-aligned: a prior with one value per
class |
required |
p
|
Distribution
|
Distributions with the same event shape and broadcastable batch
shapes. Broadcasting is right-aligned: a prior with one value per
class |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Shape |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the pair of types has no registered divergence. |
ValueError
|
If the event shapes differ, the batch shapes do not broadcast or the devices differ. |
posterior
posterior(prior, stats, **known)
Conjugate posterior of prior given likelihood statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
Distribution
|
Conjugate prior. |
required |
stats
|
SuffStats
|
Weighted sufficient statistics of the observations (weights must
be non-negative; this is not checked). Tempering is
|
required |
**known
|
Tensor
|
Fixed parameters of the likelihood, required by some pairs (e.g.
|
{}
|
Returns:
| Type | Description |
|---|---|
Distribution
|
Same type as |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the pair has no registered update. |
ValueError
|
If the event shapes differ or the batch shapes do not broadcast. |
TypeError
|
If a required |