-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
poisson.py
87 lines (67 loc) · 2.23 KB
/
poisson.py
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
import chainer
from chainer.backends import cuda
from chainer import distribution
from chainer.functions.math import exponential
from chainer.functions.math import lgamma
from chainer import utils
from chainer.utils import cache
class Poisson(distribution.Distribution):
"""Poisson Distribution.
The probability mass function of the distribution is expressed as
.. math::
P(x; \\lambda) = \\frac{\\lambda ^x e^{-\\lambda}}{x!}
Args:
lam(:class:`~chainer.Variable` or :ref:`ndarray`): Parameter of
distribution. :math:`\\lambda`
"""
def __init__(self, lam):
super(Poisson, self).__init__()
self.__lam = lam
@cache.cached_property
def lam(self):
return chainer.as_variable(self.__lam)
@cache.cached_property
def _log_lam(self):
return exponential.log(self.lam)
@property
def batch_shape(self):
return self.lam.shape
@property
def event_shape(self):
return ()
@property
def _is_gpu(self):
return isinstance(self.lam.data, cuda.ndarray)
def log_prob(self, x):
if isinstance(x, chainer.Variable):
x = x.data
x = x.astype(self.lam.dtype)
xp1 = (x + 1).astype(self.lam.dtype)
x, xp1 = utils.force_array(x), utils.force_array(xp1)
return x * self._log_lam - lgamma.lgamma(xp1) - self.lam
@cache.cached_property
def mean(self):
return self.lam
@property
def params(self):
return {'lam': self.lam}
def sample_n(self, n):
xp = cuda.get_array_module(self.lam)
if xp is cuda.cupy:
eps = xp.random.poisson(
self.lam.data, size=(n,)+self.batch_shape, dtype=xp.float32)
else:
eps = xp.random.poisson(
self.lam.data, size=(n,)+self.batch_shape).astype(xp.float32)
noise = chainer.Variable(eps)
return noise
@property
def support(self):
return 'non negative integer'
@cache.cached_property
def variance(self):
return self.lam
@distribution.register_kl(Poisson, Poisson)
def _kl_poisson_poisson(dist1, dist2):
return dist1.lam * (dist1._log_lam
- dist2._log_lam) - dist1.lam + dist2.lam