mixle.stats.multivariate.diagonal_gaussian module¶
Create, estimate, and sample from a diagonal Gaussian distribution (independent-multivariate Gaussian).
Defines the DiagonalGaussianDistribution, DiagonalGaussianSampler, DiagonalGaussianAccumulatorFactory, DiagonalGaussianAccumulator, DiagonalGaussianEstimator, and the DiagonalGaussianDataEncoder classes for use with mixle.
The log-density of an ‘n’ dimensional diagonal-gaussian observation x = (x_1,x_2,…,x_n) with mean mu=(m_1,m_2,..,m_n), and diagonal covariance matrix given by covar = diag(s2_1, s2_2,…,s2_n).
log(p_mat(x)) = -0.5*sum_{i=1}^{n} (x_i-m_i)^2 / s2_i - 0.5*log(s2_i) - (n/2)*log(2*pi).
Data type: x (List[float], np.ndarray).
Reference: Mardia, Kent & Bibby, Multivariate Analysis (Academic Press, 1979).
- class DiagonalGaussianDistribution(mu, covar=MISSING, name=None, keys=None, covariance=MISSING, prior=None)[source]
Bases:
SequenceEncodableProbabilityDistributionMultivariate Gaussian distribution with independent components (diagonal covariance matrix).
- Parameters:
- classmethod compute_capabilities()[source]
- classmethod compute_declaration()[source]
- static exp_family_sufficient_statistics(x, engine)[source]
Return vector sufficient statistics for generated diagonal-Gaussian scoring.
- static exp_family_natural_parameters(params, engine)[source]
Return vector natural parameters for generated diagonal-Gaussian scoring.
- static exp_family_log_partition(params, engine)[source]
Return the diagonal-Gaussian log partition for generated scoring.
- static backend_legacy_sufficient_statistics(x, params, engine)[source]
Return row-wise legacy accumulator statistics for generated resident reductions.
- set_prior(prior)[source]
Attach a parameter prior and precompute conjugate-prior expectations.
With a MultivariateNormalGamma(mu0, lam, a, b) prior over (mu, tau=1/covar) this caches the expected natural parameters [ea, eb, e1, e2] with e1 = E[mu*tau] and e2 = -0.5*E[tau] per component (ea, eb scalars summed over components), so that
expected_log_density(x) = x.e1 + (x*x).e2 - ea + eb. Any other prior (includingNone) leaves the distribution a plain point model.- Parameters:
prior (SequenceEncodableProbabilityDistribution | None)
- Return type:
None
- expected_log_density(x)[source]
Variational expectation E_q[log p(x | mu, tau)] under the prior.
Falls back to the plug-in
log_density(x)when no conjugate prior is attached.- Return type:
- seq_expected_log_density(x)[source]
Vectorized
expected_log_densityover sequence-encoded observations.
- density(x)[source]
Evaluate the density at observation x.
See log_density() for details.
- Parameters:
x (Union[Sequence[float], np.ndarray]) – Length-dim observation vector.
- Returns:
Density at x.
- log_density(x)[source]
Evaluate the log-density at observation x.
The log-density is given by
log(p(x)) = -0.5*sum_{i=1}^{n} (x_i-m_i)^2 / s2_i - 0.5*log(s2_i) - (n/2)*log(2*pi).
- Parameters:
x (Union[Sequence[float], np.ndarray]) – Length-dim observation vector.
- Returns:
Log-density at x.
- condition(observed)[source]
Return the conditional over the unobserved dimensions given
observed.A diagonal Gaussian has independent coordinates, so conditioning on some of them leaves the rest unchanged: the result is just
DiagonalGaussian(mu[unobserved], covar[unobserved])(the observed values do not shift the unobserved mean or variance). Provided so diagonal-covariance Gaussian mixtures supportMixtureDistribution.conditional()– there the responsibilities still update from how well each component explains the observed coordinates, even though the within-component coordinates are independent. Raises if no dimension is left unobserved.
- marginal(keep)[source]
Return the marginal over the dimensions
keep:DiagonalGaussian(mu[keep], covar[keep]).Marginalizing a diagonal Gaussian simply drops the other independent coordinates (order kept).
- density_cumulative(x)[source]
Exact probability-ordered cumulative
G(x) = P(p(Y) >= p(x))– the highest-density-region mass throughx(multivariate analogue of a CDF). For a diagonal Gaussian the squared Mahalanobis distancesum_i (x_i-mu_i)^2/var_iis chi-square(dim), soG = chi2.cdf(maha2, dim). Used bymixle.enumeration.density_rank.density_rank()to return an EXACT cumulative.
- density_quantile(q)[source]
Inverse of
density_cumulative(): a representative point at cumulative-density indexq.qis the highest-density-region mass, whose boundary is the squared-Mahalanobis levelchi2.ppf(q, dim); a representative point on that contour offsets the first coordinate bysqrt(level * var_0)(Mahalanobis distance exactly the level). Sweepingqenumerates the support in descending density.
- seq_log_density(x)[source]
Vectorized evaluation of the log-density at a sequence-encoded input x.
- Parameters:
x (np.ndarray) – Encoded data matrix with shape (sz, dim) from DiagonalGaussianDataEncoder.seq_encode().
- Returns:
Numpy array of length sz containing the log-density of each encoded observation.
- Return type:
- static backend_log_density_from_params(x, mu, covar, engine)[source]
Engine-neutral diagonal Gaussian log-density from explicit parameters.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded data.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked diagonal-Gaussian parameters for a homogeneous mixture kernel.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of diagonal-Gaussian log densities.
- to_fisher(**kwargs)[source]
Return this distribution’s own Fisher view.
- sampler(seed=None)[source]
Create a DiagonalGaussianSampler for sampling from this distribution.
- Parameters:
seed (Optional[int]) – Seed to set for sampling with RandomState.
- Returns:
DiagonalGaussianSampler object.
- Return type:
DiagonalGaussianSampler
- estimator(pseudo_count=None)[source]
Create a DiagonalGaussianEstimator for estimating this distribution.
- Parameters:
pseudo_count (Optional[float]) – Used to inflate sufficient statistics in estimation.
- Returns:
DiagonalGaussianEstimator object.
- Return type:
DiagonalGaussianEstimator
- dist_to_encoder()[source]
Returns a DiagonalGaussianDataEncoder object for encoding sequences of iid observations.
- Return type:
DiagonalGaussianDataEncoder
- class DiagonalGaussianSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDiagonalGaussianSampler object for sampling from a DiagonalGaussianDistribution.
- Parameters:
dist (DiagonalGaussianDistribution)
seed (int | None)
- sample(size=None)[source]
Draw iid samples from the diagonal Gaussian distribution.
- class DiagonalGaussianAccumulator(dim=None, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorDiagonalGaussianAccumulator object for aggregating sufficient statistics from iid observations.
- update(x, weight, estimate)[source]
Update sufficient statistics with a single weighted observation.
- initialize(x, weight, rng)[source]
Initialize the accumulator with a weighted observation. Calls update().
- seq_update(x, weights, estimate)[source]
Vectorized update of sufficient statistics with an encoded sequence of observations.
- Parameters:
x (np.ndarray) – Encoded data matrix with shape (sz, dim).
weights (np.ndarray) – Numpy array of sz observation weights.
estimate (Optional[DiagonalGaussianDistribution]) – Kept for consistency (not used).
- Returns:
None.
- Return type:
None
- seq_initialize(x, weights, rng)[source]
Vectorized initialization of the accumulator. Calls seq_update().
- Parameters:
x (np.ndarray) – Encoded data matrix with shape (sz, dim).
weights (np.ndarray) – Numpy array of sz observation weights.
rng (RandomState) – Kept for consistency with SequenceEncodableStatisticAccumulator.
- Returns:
None.
- Return type:
None
- combine(suff_stat)[source]
Merge the sufficient statistics of suff_stat into this accumulator.
- Parameters:
suff_stat (Tuple[np.ndarray, np.ndarray, float]) – Tuple of (weighted sum of observations, weighted sum of squared observations, sum of weights).
- Returns:
DiagonalGaussianAccumulator object.
- Return type:
DiagonalGaussianAccumulator
- value()[source]
Returns the sufficient statistics (sum, sum of squares, count) of the accumulator.
- from_value(x)[source]
Set the sufficient statistics of the accumulator to x.
- Parameters:
x (Tuple[np.ndarray, np.ndarray, float]) – Tuple of (weighted sum of observations, weighted sum of squared observations, sum of weights).
- Returns:
DiagonalGaussianAccumulator object.
- Return type:
DiagonalGaussianAccumulator
- key_merge(stats_dict)[source]
Combine sufficient statistics with other accumulators sharing a matching key.
- Parameters:
stats_dict (Dict[str, Any]) – Dictionary mapping keys to aggregated statistics.
- Returns:
None.
- Return type:
None
- key_replace(stats_dict)[source]
Replace sufficient statistics with values from stats_dict for a matching key.
- Parameters:
stats_dict (Dict[str, Any]) – Dictionary mapping keys to aggregated statistics.
- Returns:
None.
- Return type:
None
- acc_to_encoder()[source]
Returns a DiagonalGaussianDataEncoder object for encoding sequences of iid observations.
- Return type:
DiagonalGaussianDataEncoder
- class DiagonalGaussianAccumulatorFactory(dim=None, keys=None)[source]
Bases:
StatisticAccumulatorFactoryDiagonalGaussianAccumulatorFactory object for creating DiagonalGaussianAccumulator objects.
- make()[source]
Returns a new DiagonalGaussianAccumulator with the factory’s dim and keys.
- Return type:
DiagonalGaussianAccumulator
- class DiagonalGaussianEstimator(dim=None, pseudo_count=(None, None), suff_stat=(None, None), name=None, keys=None, prior=None, min_covar=None, ridge=None)[source]
Bases:
ParameterEstimatorDiagonalGaussianEstimator object for estimating a diagonal Gaussian distribution from aggregated sufficient statistics.
- Parameters:
- accumulator_factory()[source]
Returns a DiagonalGaussianAccumulatorFactory built from the estimator’s attributes.
- Return type:
DiagonalGaussianAccumulatorFactory
- model_log_density(model)[source]
Log-density of the model parameters under the MultivariateNormalGamma prior (ELBO global term).
The prior is over (mu, tau=1/covar), so the model’s covariance is inverted before scoring.
- Parameters:
model (DiagonalGaussianDistribution)
- Return type:
- estimate(nobs, suff_stat)[source]
Estimate a diagonal Gaussian distribution from aggregated sufficient statistics.
- Suff_stat is a Tuple of size 3 containing:
suff_stat[0] (np.ndarray): Component-wise sum of weighted observation values. suff_stat[1] (np.ndarray): Component-wise sum of weighted squared observation values. suff_stat[2] (float): Sum of weights for each observation.