mixle.stats.bayes.dirichlet module¶
Create, estimate, and sample from a Dirichlet distribution with concentration parameters alpha.
Defines the DirichletDistribution, DirichletSampler, DirichletAccumulatorFactory, DirichletAccumulator, DirichletEstimator, and the DirichletDataEncoder classes for use with mixle.
Data type: Union[List[float], np.ndarray[float]]
- The log-density of a Dirichlet with dim = K, is given by
log(p_mat(x)) = -log(Const) + sum_{k=0}^{K-1} (alpha_k -1)*log(x_k), for sum_k x_k = 1.0,
- else -inf. In above,
log(Const) = sum_{k=0}^{K-1} log(Gamma(alpha_k)) - log(Gamma(sum_{k=0}^{K-1} alpha_k)).
- dirichlet_param_solve(alpha, mean_log_p, delta, max_iter=_MAX_DIRICHLET_ITERATIONS)[source]
Iteratively solve for alpha of a Dirichlet distribution.
- Parameters:
- Returns:
Tuple[np.ndarray, int] containing the estimates of alpha and numer of iterations in solver.
- Return type:
- mpe(x0, f, eps, max_iter=1000)[source]
Minimal polynomial extrapolation for accelerating the fixed-point iteration x_{n+1} = f(x_n).
- Parameters:
- Returns:
Tuple[np.ndarray, int] containing the extrapolated fixed point and the iteration count.
- Return type:
- alpha_seq_lambda(mean_log_p)[source]
Returns the fixed-point map for the Dirichlet alpha given sufficient statistic mean_log_p.
- find_alpha(current_alpha, mlp, thresh)[source]
Solve for the Dirichlet alpha with MPE-accelerated fixed-point iteration.
- Parameters:
current_alpha (np.ndarray) – Initial estimate of the Dirichlet parameters.
mlp (np.ndarray) – Mean of the log of the observed proportions (sufficient statistic).
thresh (float) – Convergence tolerance.
- Returns:
Tuple[np.ndarray, int] containing the estimate of alpha and the iteration count.
- Return type:
- class DirichletDistribution(alpha, name=None, keys=None)[source]
Bases:
SequenceEncodableProbabilityDistributionDirichlet distribution over probability vectors, with concentration parameters alpha.
- classmethod compute_capabilities()[source]
- classmethod compute_declaration()[source]
- get_parameters()[source]
Return the concentration vector alpha.
Lets a DirichletDistribution serve as a conjugate prior (on a Categorical/Mixture weight simplex) under the unified Bayesian estimation protocol.
- Return type:
- cross_entropy(dist)[source]
Cross entropy -E_self[log dist(x)] for a Dirichlet argument.
Accepts another
DirichletDistribution(full concentration vector) or aSymmetricDirichletDistribution(scalar concentration broadcast to this distribution’s dimension). Both arise as the conjugate prior/posterior over the same simplex during variational Bayes (e.g. the ELBO global term in DPM).- Parameters:
dist (SequenceEncodableProbabilityDistribution)
- Return type:
- density(x)[source]
Evaluate the density of a dirichlet observation.
See log_density() for details.
- log_density(x)[source]
Evaluate the log-density of a dirichlet observation.
The log-density of a Dirichlet with dim = K, is given by
log(p_mat(x)) = -log(Const) + sum_{k=0}^{K-1} (alpha_k -1)*log(x_k), for sum_k x_k = 1.0,
else -inf. In above
log(Const) = sum_{k=0}^{K-1} log(Gamma(alpha_k)) - log(Gamma(sum_{k=0}^{K-1} alpha_k)).
- seq_log_density(x)[source]
Vectorized evaluation of the log-density at a sequence-encoded input x.
- Parameters:
x (Tuple[np.ndarray, np.ndarray, np.ndarray]) – Encoded data from DirichletDataEncoder.seq_encode(), a tuple of (log of observations, observations, squared observations).
- Returns:
Numpy array containing the log-density of each encoded observation.
- Return type:
- static backend_log_density_from_params(log_x, alpha, log_const, engine)[source]
Engine-neutral Dirichlet log-density from encoded log observations.
- backend_seq_log_density(x, engine)[source]
Engine-neutral vectorized log-density for encoded Dirichlet observations.
- classmethod backend_stacked_params(dists, engine)[source]
Return stacked parameters for equal-dimensional Dirichlet mixtures.
- classmethod backend_stacked_log_density(x, params, engine)[source]
Return an
(n, k)matrix of Dirichlet component log densities.
- classmethod backend_stacked_sufficient_statistics(x, weights, params, engine)[source]
Return component-stacked legacy Dirichlet sufficient statistics.
- to_fisher(**kwargs)[source]
Return the Dirichlet’s log-coordinate Fisher view (generic fallback for degenerate alpha).
- sampler(seed=None)[source]
Create a DirichletSampler for sampling from this distribution.
- Parameters:
seed (Optional[int]) – Seed to set for sampling with RandomState.
- Returns:
DirichletSampler object.
- Return type:
DirichletSampler
- estimator(pseudo_count=None)[source]
Create a DirichletEstimator for estimating this distribution.
If pseudo_count is passed, the current normalized alpha is used to regularize the estimate.
- Parameters:
pseudo_count (Optional[float]) – Used to inflate sufficient statistics in estimation.
- Returns:
DirichletEstimator object.
- Return type:
DirichletEstimator
- dist_to_encoder()[source]
Create DirichletDataEncoder object for encoding sequences of iid Dirichlet observations.
- Return type:
DirichletDataEncoder
- class DirichletSampler(dist, seed=None)[source]
Bases:
DistributionSamplerDirichletSampler object for sampling from a DirichletDistribution.
- Parameters:
dist (DirichletDistribution)
seed (int | None)
- sample(size=None)[source]
Draw iid samples from the Dirichlet distribution.
Entries with non-positive alpha are fixed at zero and the remaining entries are sampled from the Dirichlet restricted to the valid alpha values.
- class DirichletAccumulator(dim=None, keys=None)[source]
Bases:
SequenceEncodableStatisticAccumulatorDirichletAccumulator object for aggregating sufficient statistics from iid observations.
- update(x, weight, estimate)[source]
Update sufficient statistics with a single weighted observation.
Zero-valued entries of x are excluded from the sum of logs.
- initialize(x, weight, estimate)[source]
Initialize the accumulator with a weighted observation. Calls update().
- get_seq_lambda()[source]
Returns a list containing the seq_update member function.
- seq_update(x, weights, estimate)[source]
Vectorized update of sufficient statistics with an encoded sequence of observations.
- Parameters:
x (Tuple[np.ndarray, np.ndarray, np.ndarray]) – Encoded data from DirichletDataEncoder.seq_encode().
weights (np.ndarray) – Numpy array of observation weights.
estimate (Optional[DirichletDistribution]) – Kept for consistency (not used).
- Returns:
None.
- Return type:
None
- seq_update_engine(x, weights, estimate, engine)[source]
Engine-resident accumulation of Dirichlet moment statistics (numpy or torch).
The weighted vector moments (sum of logs, sum, sum of squares) are reduced via a weight-vector / observation-matrix product on the active engine. Matches seq_update.
- seq_initialize(x, weights, rng)[source]
Vectorized initialization of the accumulator. Calls seq_update().
- Parameters:
x (Tuple[np.ndarray, np.ndarray, np.ndarray]) – Encoded data from DirichletDataEncoder.seq_encode().
weights (np.ndarray) – Numpy array of observation weights.
rng (Optional[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[int, np.ndarray, np.ndarray, np.ndarray]) – Tuple of (counts, sum of logs, sum of observations, sum of squared observations).
- Returns:
DirichletAccumulator object.
- Return type:
DirichletAccumulator
- value()[source]
Returns the sufficient statistics (counts, sum of logs, sum, sum of squares) of the accumulator.
- from_value(x)[source]
Set the sufficient statistics of the accumulator to x.
- Parameters:
x (Tuple[int, np.ndarray, np.ndarray, np.ndarray]) – Tuple of (counts, sum of logs, sum of observations, sum of squared observations).
- Returns:
None.
- 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 accumulators.
- 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 accumulators.
- Returns:
None.
- Return type:
None
- acc_to_encoder()[source]
Create DirichletDataEncoder object for encoding sequences of iid Dirichlet observations.
- Return type:
DirichletDataEncoder
- class DirichletAccumulatorFactory(dim=None, keys=None)[source]
Bases:
StatisticAccumulatorFactoryDirichletAccumulatorFactory object for creating DirichletAccumulator objects.
- make()[source]
Returns a new DirichletAccumulator with the factory’s dim and keys.
- Return type:
DirichletAccumulator
- class DirichletEstimator(dim=None, pseudo_count=None, suff_stat=None, delta=1.0e-8, keys=None, use_mpe=False, name=None)[source]
Bases:
ParameterEstimatorDirichletEstimator object for estimating a Dirichlet distribution from aggregated sufficient statistics.
- Parameters:
- accumulator_factory()[source]
Create DirichletAccumulator object from attributes variables.
- Return type:
DirichletAccumulatorFactory
- estimate(nobs, suff_stat)[source]
Estimate a Dirichlet distribution from aggregated sufficient statistics.
- Suff_stat is a Tuple of size 4 containing:
suff_stat[0] (float): Sum of observation weights. suff_stat[1] (np.ndarray): Weighted sum of the log of observation vectors. suff_stat[2] (np.ndarray): Weighted sum of observation vectors. suff_stat[3] (np.ndarray): Weighted sum of squared observation vectors.
The concentration parameters are solved from the mean-log-probability sufficient statistic with a fixed-point solver (dirichlet_param_solve, or find_alpha when use_mpe is set).
- class DirichletDataEncoder[source]
Bases:
DataSequenceEncoderDirichletDataEncoder object for encoding sequences of iid Dirichlet observations.