-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
geometric.py
81 lines (62 loc) · 1.97 KB
/
geometric.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
import chainer
from chainer.backends import cuda
from chainer import distribution
from chainer.functions.math import exponential
from chainer.utils import cache
class Geometric(distribution.Distribution):
"""Geometric Distribution.
The probability mass function of the distribution is expressed as
.. math::
Pr(x = k) = p(1-p)^{k-1},
for k = 1, 2, 3, ...,
Args:
p(:class:`~chainer.Variable` or :ref:`ndarray`):
Parameter of distribution.
"""
def __init__(self, p):
super(Geometric, self).__init__()
self.__p = p
@cache.cached_property
def p(self):
return chainer.as_variable(self.__p)
@property
def batch_shape(self):
return self.p.shape
@property
def event_shape(self):
return ()
@property
def _is_gpu(self):
return isinstance(self.p.data, cuda.ndarray)
def log_prob(self, x):
return (x - 1) * exponential.log(1 - self.p) + exponential.log(self.p)
@cache.cached_property
def mean(self):
return 1 / self.p
@property
def params(self):
return {'p': self.p}
def sample_n(self, n):
xp = chainer.backend.get_array_module(self.p)
if xp is cuda.cupy:
eps = xp.random.geometric(
self.p.data,
size=(n,)+self.batch_shape, dtype=self.p.dtype)
else:
eps = xp.random.geometric(
self.p.data,
size=(n,)+self.batch_shape).astype(self.p.dtype)
return chainer.Variable(eps)
@property
def support(self):
return 'positive integer'
@cache.cached_property
def variance(self):
return (1 - self.p) / self.p ** 2
@distribution.register_kl(Geometric, Geometric)
def _kl_geometric_geometric(dist1, dist2):
return (
(1 / dist1.p - 1)
* (exponential.log(1 - dist1.p) - exponential.log(1 - dist2.p))
+ exponential.log(dist1.p)
- exponential.log(dist2.p))