|
| 1 | +import numpy as np |
| 2 | +import theano.tensor as tt |
| 3 | + |
| 4 | +from ..math import logsumexp |
| 5 | +from .dist_math import bound |
| 6 | +from .distribution import Discrete, Distribution, draw_values, generate_samples |
| 7 | +from .continuous import get_tau_sd, Normal |
| 8 | + |
| 9 | + |
| 10 | +def all_discrete(comp_dists): |
| 11 | + """ |
| 12 | + Determine if all distributions in comp_dists are discrete |
| 13 | + """ |
| 14 | + if isinstance(comp_dists, Distribution): |
| 15 | + return isinstance(comp_dists, Discrete) |
| 16 | + else: |
| 17 | + return all(isinstance(comp_dist, Discrete) for comp_dist in comp_dists) |
| 18 | + |
| 19 | + |
| 20 | +class Mixture(Distribution): |
| 21 | + R""" |
| 22 | + Mixture log-likelihood |
| 23 | +
|
| 24 | + Often used to model subpopulation heterogeneity |
| 25 | +
|
| 26 | + .. math:: f(x \mid w, \theta) = \sum_{i = 1}^n w_i f_i(x \mid \theta_i) |
| 27 | +
|
| 28 | + ======== ============================================ |
| 29 | + Support :math:`\cap_{i = 1}^n \textrm{support}(f_i)` |
| 30 | + Mean :math:`\sum_{i = 1}^n w_i \mu_i` |
| 31 | + ======== ============================================ |
| 32 | +
|
| 33 | + Parameters |
| 34 | + ---------- |
| 35 | + w : array of floats |
| 36 | + w >= 0 and w <= 1 |
| 37 | + the mixutre weights |
| 38 | + comp_dists : multidimensional PyMC3 distribution or iterable of one-dimensional PyMC3 distributions |
| 39 | + the component distributions :math:`f_1, \ldots, f_n` |
| 40 | + """ |
| 41 | + def __init__(self, w, comp_dists, *args, **kwargs): |
| 42 | + shape = kwargs.pop('shape', ()) |
| 43 | + |
| 44 | + self.w = w |
| 45 | + self.comp_dists = comp_dists |
| 46 | + |
| 47 | + defaults = kwargs.pop('defaults', []) |
| 48 | + |
| 49 | + if all_discrete(comp_dists): |
| 50 | + dtype = kwargs.pop('dtype', 'int64') |
| 51 | + else: |
| 52 | + dtype = kwargs.pop('dtype', 'float64') |
| 53 | + |
| 54 | + try: |
| 55 | + self.mean = (w * self._comp_means()).sum(axis=-1) |
| 56 | + |
| 57 | + if 'mean' not in defaults: |
| 58 | + defaults.append('mean') |
| 59 | + except AttributeError: |
| 60 | + pass |
| 61 | + |
| 62 | + try: |
| 63 | + comp_modes = self._comp_modes() |
| 64 | + comp_mode_logps = self.logp(comp_modes) |
| 65 | + self.mode = comp_modes[tt.argmax(w * comp_mode_logps, axis=-1)] |
| 66 | + |
| 67 | + if 'mode' not in defaults: |
| 68 | + defaults.append('mode') |
| 69 | + except AttributeError: |
| 70 | + pass |
| 71 | + |
| 72 | + super(Mixture, self).__init__(shape, dtype, defaults=defaults, |
| 73 | + *args, **kwargs) |
| 74 | + |
| 75 | + def _comp_logp(self, value): |
| 76 | + comp_dists = self.comp_dists |
| 77 | + |
| 78 | + try: |
| 79 | + value_ = value if value.ndim > 1 else tt.shape_padright(value) |
| 80 | + |
| 81 | + return comp_dists.logp(value_) |
| 82 | + except AttributeError: |
| 83 | + return tt.stack([comp_dist.logp(value) for comp_dist in comp_dists], |
| 84 | + axis=1) |
| 85 | + |
| 86 | + def _comp_means(self): |
| 87 | + try: |
| 88 | + return self.comp_dists.mean |
| 89 | + except AttributeError: |
| 90 | + return tt.stack([comp_dist.mean for comp_dist in self.comp_dists], |
| 91 | + axis=1) |
| 92 | + |
| 93 | + def _comp_modes(self): |
| 94 | + try: |
| 95 | + return self.comp_dists.mode |
| 96 | + except AttributeError: |
| 97 | + return tt.stack([comp_dist.mode for comp_dist in self.comp_dists], |
| 98 | + axis=1) |
| 99 | + |
| 100 | + def _comp_samples(self, point=None, size=None, repeat=None): |
| 101 | + try: |
| 102 | + samples = self.comp_dists.random(point=point, size=size, repeat=repeat) |
| 103 | + except AttributeError: |
| 104 | + samples = np.column_stack([comp_dist.random(point=point, size=size, repeat=repeat) |
| 105 | + for comp_dist in self.comp_dists]) |
| 106 | + |
| 107 | + return np.squeeze(samples) |
| 108 | + |
| 109 | + def logp(self, value): |
| 110 | + w = self.w |
| 111 | + |
| 112 | + return bound(logsumexp(tt.log(w) + self._comp_logp(value), axis=-1).sum(), |
| 113 | + w >= 0, w <= 1, tt.allclose(w.sum(axis=-1), 1)) |
| 114 | + |
| 115 | + def random(self, point=None, size=None, repeat=None): |
| 116 | + def random_choice(*args, **kwargs): |
| 117 | + w = kwargs.pop('w') |
| 118 | + w /= w.sum(axis=-1, keepdims=True) |
| 119 | + k = w.shape[-1] |
| 120 | + |
| 121 | + if w.ndim > 1: |
| 122 | + return np.row_stack([np.random.choice(k, p=w_) for w_ in w]) |
| 123 | + else: |
| 124 | + return np.random.choice(k, p=w, *args, **kwargs) |
| 125 | + |
| 126 | + w = draw_values([self.w], point=point) |
| 127 | + |
| 128 | + w_samples = generate_samples(random_choice, |
| 129 | + w=w, |
| 130 | + broadcast_shape=w.shape[:-1] or (1,), |
| 131 | + dist_shape=self.shape, |
| 132 | + size=size).squeeze() |
| 133 | + comp_samples = self._comp_samples(point=point, size=size, repeat=repeat) |
| 134 | + |
| 135 | + if comp_samples.ndim > 1: |
| 136 | + return np.squeeze(comp_samples[np.arange(w_samples.size), w_samples]) |
| 137 | + else: |
| 138 | + return np.squeeze(comp_samples[w_samples]) |
| 139 | + |
| 140 | + |
| 141 | +class NormalMixture(Mixture): |
| 142 | + R""" |
| 143 | + Normal mixture log-likelihood |
| 144 | +
|
| 145 | + .. math:: f(x \mid w, \mu, \sigma^2) = \sum_{i = 1}^n w_i N(x \mid \mu_i, \sigma^2_i |
| 146 | +
|
| 147 | + ======== ======================================= |
| 148 | + Support :math:`x \in \mathbb{R}` |
| 149 | + Mean :math:`\sum_{i = 1}^n w_i \mu_i` |
| 150 | + Variance :math:`\sum_{i = 1}^n w_i^2 \sigma^2_i` |
| 151 | + ======== ======================================= |
| 152 | +
|
| 153 | + Parameters |
| 154 | + w : array of floats |
| 155 | + w >= 0 and w <= 1 |
| 156 | + the mixutre weights |
| 157 | + mu : array of floats |
| 158 | + the component means |
| 159 | + sd : array of floats |
| 160 | + the component standard deviations |
| 161 | + tau : array of floats |
| 162 | + the component precisions |
| 163 | + """ |
| 164 | + def __init__(self, w, mu, *args, **kwargs): |
| 165 | + _, sd = get_tau_sd(tau=kwargs.pop('tau', None), |
| 166 | + sd=kwargs.pop('sd', None)) |
| 167 | + |
| 168 | + super(NormalMixture, self).__init__(w, Normal.dist(mu, sd=sd), |
| 169 | + *args, **kwargs) |
0 commit comments