File: gamma.py

package info (click to toggle)
python-bayespy 0.6.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,132 kB
  • sloc: python: 22,402; makefile: 156
file content (430 lines) | stat: -rw-r--r-- 10,773 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
################################################################################
# Copyright (C) 2011-2012,2014 Jaakko Luttinen
#
# This file is licensed under the MIT License.
################################################################################


"""
Module for the gamma distribution node.
"""

import numpy as np
import scipy.special as special

from .node import Node, Moments, ensureparents
from .deterministic import Deterministic
from .stochastic import Stochastic
from .expfamily import ExponentialFamily, ExponentialFamilyDistribution
from .constant import Constant

from bayespy.utils import misc
from bayespy.utils import random


def diagonal(alpha):
    """
    Create a diagonal Wishart node from a Gamma node.
    """
    return _GammaToDiagonalWishart(alpha,
                                   name=alpha.name + " as Wishart")


class GammaPriorMoments(Moments):
    """
    Class for the moments of the shape parameter in gamma distributions.
    """


    dims = ( (), () )


    def compute_fixed_moments(self, a):
        """
        Compute the moments for a fixed value
        """
        a = np.asanyarray(a)
        if np.any(a <= 0):
            raise ValueError("Shape parameter must be positive")
        u0 = a
        u1 = special.gammaln(a)
        return [u0, u1]


    @classmethod
    def from_values(cls, a):
        """
        Return the shape of the moments for a fixed value.
        """
        return cls()


class GammaMoments(Moments):
    """
    Class for the moments of gamma variables.
    """

    dims = ( (), () )


    def compute_fixed_moments(self, x):
        """
        Compute the moments for a fixed value
        """
        x = np.asanyarray(x)
        if np.any(x < 0):
            raise ValueError("Values must be positive")
        u0 = x
        u1 = np.log(x)
        return [u0, u1]


    @classmethod
    def from_values(cls, x):
        """
        Return the shape of the moments for a fixed value.
        """
        return cls()


class GammaDistribution(ExponentialFamilyDistribution):
    """
    Class for the VMP formulas of gamma variables.
    """


    def compute_message_to_parent(self, parent, index, u_self, u_a, u_b):
        r"""
        Compute the message to a parent node.
        """
        x = u_self[0]
        logx = u_self[1]

        if index == 0:
            b = u_b[0]
            logb = u_b[1]
            return [logx + logb,
                    -1]
        elif index == 1:
            a = u_a[0]
            return [-x,
                    a]
        else:
            raise ValueError("Index out of bounds")


    def compute_phi_from_parents(self, *u_parents, mask=True):
        r"""
        Compute the natural parameter vector given parent moments.
        """
        return [-u_parents[1][0],
                1*u_parents[0][0]]


    def compute_moments_and_cgf(self, phi, mask=True):
        r"""
        Compute the moments and :math:`g(\phi)`.

        .. math::

           \overline{\mathbf{u}}  (\boldsymbol{\phi})
           &=
           \begin{bmatrix}
             - \frac{\phi_2} {\phi_1}
             \\
             \psi(\phi_2) - \log(-\phi_1)
           \end{bmatrix}
           \\
           g_{\boldsymbol{\phi}} (\boldsymbol{\phi})
           &=
           TODO
        """
        with np.errstate(invalid='raise', divide='raise'):
            log_b = np.log(-phi[0])
            u0 = phi[1] / (-phi[0])
        u1 = special.digamma(phi[1]) - log_b
        u = [u0, u1]
        g = phi[1] * log_b - special.gammaln(phi[1])
        return (u, g)


    def compute_cgf_from_parents(self, *u_parents):
        r"""
        Compute :math:`\mathrm{E}_{q(p)}[g(p)]`
        """
        a = u_parents[0][0]
        gammaln_a = u_parents[0][1] #special.gammaln(a)
        b = u_parents[1][0]
        log_b = u_parents[1][1]
        g = a * log_b - gammaln_a
        return g


    def compute_fixed_moments_and_f(self, x, mask=True):
        r"""
        Compute the moments and :math:`f(x)` for a fixed value.
        """
        x = np.asanyarray(x)
        if np.any(x < 0):
            raise ValueError("Values must be positive")
        logx = np.log(x)
        u = [x, logx]
        f = -logx
        return (u, f)


    def random(self, *phi, plates=None):
        r"""
        Draw a random sample from the distribution.
        """
        return random.gamma(phi[1], -1/phi[0], size=plates)


    def compute_gradient(self, g, u, phi):
        r"""
        Compute the moments and :math:`g(\phi)`.

        .. math::

           \mathrm{d}\overline{\mathbf{u}} &=
           \begin{bmatrix}
             - \frac{\mathrm{d}\phi_2} {phi_1} + \frac{\phi_2}{\phi_1^2} \mathrm{d}\phi_1
             \\
             \psi^{(1)}(\phi_2) \mathrm{d}\phi_2 - \frac{1}{\phi_1} \mathrm{d}\phi_1
           \end{bmatrix}


        Standard gradient given the gradient with respect to the moments, that
        is, given the Riemannian gradient :math:`\tilde{\nabla}`:

        .. math::

           \nabla =
           \begin{bmatrix}
             \nabla_1 \frac{\phi_2}{\phi_1^2} - \nabla_2 \frac{1}{\phi_1}
             \\
             \nabla_2 \psi^{(1)}(\phi_2) - \nabla_1 \frac {1} {\phi_1}
           \end{bmatrix}
        """
        d0 = g[0] * phi[1] / phi[0]**2 - g[1] / phi[0]
        d1 = g[1] * special.polygamma(1, phi[1]) - g[0] / phi[0]
        return [d0, d1]


class Gamma(ExponentialFamily):
    """
    Node for gamma random variables.

    Parameters
    ----------

    a : scalar or array

        Shape parameter

    b : gamma-like node or scalar or array

        Rate parameter
    """

    dims = ( (), () )
    _distribution = GammaDistribution()
    _moments = GammaMoments()
    _parent_moments = (GammaPriorMoments(),
                       GammaMoments())


    def __init__(self, a, b, **kwargs):
        """
        Create gamma random variable node
        """
        super().__init__(a, b, **kwargs)


    def __str__(self):
        """
        Print the distribution using standard parameterization.
        """
        a = self.phi[1]
        b = -self.phi[0]
        return ("%s ~ Gamma(a, b)\n"
                "  a =\n"
                "%s\n"
                "  b =\n"
                "%s\n"
                % (self.name, a, b))


    def as_wishart(self, ndim=0):
        if ndim != 0:
            raise NotImplementedError()
        return _GammaToScalarWishart(self, name=self.name + " as Wishart")


    def as_diagonal_wishart(self):
        return _GammaToDiagonalWishart(self,
                                       name=self.name + " as Wishart")


    def diag(self):
        return self.as_diagonal_wishart()


class GammaShape(Stochastic):
    """
    ML point estimator for the shape parameter of the gamma distribution
    """

    dims = ( (), () )
    _moments = GammaPriorMoments()
    _parent_moments = ()


    def __init__(self, m0=0, m1=0, **kwargs):
        """
        Create gamma random variable node
        """
        super().__init__(dims=self.dims, initialize=False, **kwargs)
        self.u = self._moments.compute_fixed_moments(1)
        self._m0 = m0
        self._m1 = m1
        return


    def _update_distribution_and_lowerbound(self, m):
        r"""
        Find maximum likelihood estimate for the shape parameter

        Messages from children appear in the lower bound as

        .. math::

           m_0 \cdot x +  m_1 \cdot \log(\Gamma(x))

        Take derivative, put it zero and solve:

        .. math::

           m_0 + m_1 \cdot d\log(\Gamma(x)) &= 0
           \\
           m_0 + m_1 \cdot \psi(x) &= 0
           \\
           x &= \psi^{-1}(-\frac{m_0}{m_1})

        where :math:`\psi^{-1}` is the inverse digamma function.
        """

        # Maximum likelihood estimate
        m0 = self._m0 + m[0]
        m1 = self._m1 + m[1]
        x = misc.invpsi(-m0 / m1)

        # Compute moments
        self.u = self._moments.compute_fixed_moments(x)

        return


    def initialize_from_value(self, x):
        self.u = self._moments.compute_fixed_moments(x)
        return


    def lower_bound_contribution(self):
        return 0


class _GammaToDiagonalWishart(Deterministic):
    """
    Transform a set of gamma scalars into a diagonal Wishart matrix.

    The last plate is used as the diagonal dimension.
    """


    _parent_moments = [GammaMoments()]


    @ensureparents
    def __init__(self, alpha, **kwargs):

        # Check for constant
        if misc.is_numeric(alpha):
            alpha = Constant(Gamma)(alpha)

        if len(alpha.plates) == 0:
            raise Exception("Gamma variable needs to have plates in "
                            "order to be used as a diagonal Wishart.")
        D = alpha.plates[-1]

        # FIXME: Put import here to avoid circular dependency import
        from .wishart import WishartMoments
        self._moments = WishartMoments((D,))
        dims = ( (D,D), () )

        # Construct the node
        super().__init__(alpha,
                         dims=self._moments.dims,
                         **kwargs)


    def _plates_to_parent(self, index):
        D = self.dims[0][0]
        return self.plates + (D,)

    def _plates_from_parent(self, index):
        return self.parents[index].plates[:-1]

    @staticmethod
    def _compute_weights_to_parent(index, weights):
        return weights[..., np.newaxis]

    def get_moments(self):
        u = self.parents[0].get_moments()

        # Form a diagonal matrix from the gamma variables
        return [np.identity(self.dims[0][0]) * u[0][...,np.newaxis],
                np.sum(u[1], axis=(-1))]

    @staticmethod
    def _compute_message_to_parent(index, m_children, *u_parents):

        # Take the diagonal
        m0 = np.einsum('...ii->...i', m_children[0])
        m1 = np.reshape(m_children[1], np.shape(m_children[1]) + (1,))

        return [m0, m1]


class _GammaToScalarWishart(Deterministic):
    """
    Transform gamma scalar moments to ndim=0 scalar Wishart moments
    """

    _parent_moments = [GammaMoments()]


    @ensureparents
    def __init__(self, alpha, **kwargs):

        # Check for constant
        if misc.is_numeric(alpha):
            alpha = Constant(Gamma)(alpha)

        # FIXME: Put import here to avoid circular dependency import
        from .wishart import WishartMoments
        self._moments = WishartMoments(())
        dims = ( (), () )

        # Construct the node
        super().__init__(alpha,
                         dims=self._moments.dims,
                         **kwargs)


    def get_moments(self):
        return self.parents[0].get_moments()

    @staticmethod
    def _compute_message_to_parent(index, m_children, *u_parents):
        return m_children