|
| 1 | +from collections.abc import Sequence |
| 2 | + |
| 3 | +import numpy as np |
| 4 | + |
| 5 | +import keras |
| 6 | +from keras import ops |
| 7 | + |
| 8 | +from bayesflow.types import Shape, Tensor |
| 9 | +from bayesflow.utils.decorators import allow_batch_size |
| 10 | +from bayesflow.utils.serialization import serializable, serialize |
| 11 | +from bayesflow.distributions import Distribution |
| 12 | + |
| 13 | + |
| 14 | +@serializable |
| 15 | +class Mixture(Distribution): |
| 16 | + """Utility class for a backend-agnostic mixture distributions.""" |
| 17 | + |
| 18 | + def __init__( |
| 19 | + self, |
| 20 | + distributions: Sequence[Distribution], |
| 21 | + mixture_logits: Sequence[float] = None, |
| 22 | + trainable_mixture: bool = False, |
| 23 | + **kwargs, |
| 24 | + ): |
| 25 | + """ |
| 26 | + Initializes a mixture of distributions as a latent distro. |
| 27 | +
|
| 28 | + Parameters |
| 29 | + ---------- |
| 30 | + distributions : Sequence[Distribution] |
| 31 | + A sequence of `Distribution` instances to form the mixture components. |
| 32 | + mixture_logits : Sequence[float], optional |
| 33 | + Initial unnormalized log‑weights for each component. If `None`, all |
| 34 | + components are assigned equal weight. Default is `None`. |
| 35 | + trainable_mixture : bool, optional |
| 36 | + Whether the mixture weights (`mixture_logits`) should be trainable. |
| 37 | + Default is `False`. |
| 38 | + **kwargs |
| 39 | + Additional keyword arguments passed to the base `Distribution` class. |
| 40 | +
|
| 41 | + Attributes |
| 42 | + ---------- |
| 43 | + distributions : Sequence[Distribution] |
| 44 | + The list of component distributions. |
| 45 | + mixture_logits : Tensor |
| 46 | + Trainable or fixed logits representing the mixture weights. |
| 47 | + dim : int or None |
| 48 | + Dimensionality of the output samples; set when first sampling. |
| 49 | + """ |
| 50 | + |
| 51 | + super().__init__(**kwargs) |
| 52 | + |
| 53 | + self.dim = None |
| 54 | + self.distributions = distributions |
| 55 | + |
| 56 | + if mixture_logits is None: |
| 57 | + mixture_logits = keras.ops.ones(shape=len(distributions)) |
| 58 | + |
| 59 | + self.mixture_logits = mixture_logits |
| 60 | + self._mixture_logits = self.add_weight( |
| 61 | + shape=(len(distributions),), |
| 62 | + initializer=keras.initializers.Constant(value=mixture_logits), |
| 63 | + dtype="float32", |
| 64 | + trainable=trainable_mixture, |
| 65 | + ) |
| 66 | + |
| 67 | + self.trainable_mixture = trainable_mixture |
| 68 | + |
| 69 | + @allow_batch_size |
| 70 | + def sample(self, batch_shape: Shape) -> Tensor: |
| 71 | + """ |
| 72 | + Draws samples from the mixture distribution by sampling a categorical index |
| 73 | + for each entry in `batch_shape` according to the softmax of `mixture_logits`, |
| 74 | + then draws from the corresponding component distribution. |
| 75 | +
|
| 76 | + Parameters |
| 77 | + ---------- |
| 78 | + batch_shape : Shape |
| 79 | + The desired sample batch shape (tuple of ints), not including the |
| 80 | + event dimension. |
| 81 | +
|
| 82 | + Returns |
| 83 | + ------- |
| 84 | + samples: Tensor |
| 85 | + A tensor of shape `batch_shape + (dim,)` containing samples drawn |
| 86 | + from the mixture. |
| 87 | + """ |
| 88 | + # Will use numpy until keras adds support for N-D categorical sampling |
| 89 | + pvals = keras.ops.convert_to_numpy(keras.ops.softmax(self._mixture_logits)) |
| 90 | + cat_samples = np.random.multinomial(n=1, pvals=pvals, size=batch_shape) |
| 91 | + cat_samples = cat_samples.argmax(axis=-1) |
| 92 | + |
| 93 | + # Prepare array to fill and dtype to infer |
| 94 | + samples = np.zeros(batch_shape + (self.dim,)) |
| 95 | + dtype = None |
| 96 | + |
| 97 | + # Fill in array with vectorized sampling per component |
| 98 | + for i in range(len(self.distributions)): |
| 99 | + dist_mask = cat_samples == i |
| 100 | + dist_indices = np.where(dist_mask) |
| 101 | + num_dist_samples = np.sum(dist_mask) |
| 102 | + dist_samples = keras.ops.convert_to_numpy(self.distributions[i].sample(num_dist_samples)) |
| 103 | + |
| 104 | + samples[dist_indices] = dist_samples |
| 105 | + |
| 106 | + dtype = dtype or keras.ops.dtype(dist_samples) |
| 107 | + |
| 108 | + # Convert to keras for compatibility |
| 109 | + samples = keras.ops.convert_to_tensor(samples, dtype=dtype) |
| 110 | + |
| 111 | + return samples |
| 112 | + |
| 113 | + def log_prob(self, samples: Tensor, *, normalize: bool = True) -> Tensor: |
| 114 | + """ |
| 115 | + Compute the log probability of given samples under the mixture. |
| 116 | +
|
| 117 | + For each input sample, computes the weighted log‑sum‑exp of the component |
| 118 | + log‑probabilities plus the mixture log‑weights. |
| 119 | +
|
| 120 | + Parameters |
| 121 | + ---------- |
| 122 | + samples : Tensor |
| 123 | + A tensor of samples with shape `batch_shape + (dim,)`. |
| 124 | + normalize : bool, optional |
| 125 | + If `True`, returns normalized log‑probabilities (i.e., includes the |
| 126 | + log normalization constant). Default is `True`. |
| 127 | +
|
| 128 | + Returns |
| 129 | + ------- |
| 130 | + Tensor |
| 131 | + A tensor of shape `batch_shape`, containing the log probability of |
| 132 | + each sample under the mixture distribution. |
| 133 | + """ |
| 134 | + |
| 135 | + log_prob = [distribution.log_prob(samples, normalize=normalize) for distribution in self.distributions] |
| 136 | + log_prob = ops.stack(log_prob, axis=-1) |
| 137 | + log_prob = ops.logsumexp(log_prob + ops.log_softmax(self._mixture_logits), axis=-1) |
| 138 | + return log_prob |
| 139 | + |
| 140 | + def build(self, input_shape: Shape) -> None: |
| 141 | + for distribution in self.distributions: |
| 142 | + distribution.build(input_shape) |
| 143 | + |
| 144 | + self.dim = input_shape[-1] |
| 145 | + |
| 146 | + def get_config(self): |
| 147 | + base_config = super().get_config() |
| 148 | + |
| 149 | + config = { |
| 150 | + "distributions": self.distributions, |
| 151 | + "mixture_logits": self.mixture_logits, |
| 152 | + "trainable_mixture": self.trainable_mixture, |
| 153 | + } |
| 154 | + |
| 155 | + return base_config | serialize(config) |
0 commit comments