binomial.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from collections.abc import Sequence
  15. import paddle
  16. from paddle.distribution import distribution
  17. class Binomial(distribution.Distribution):
  18. r"""
  19. The Binomial distribution with size `total_count` and `probs` parameters.
  20. In probability theory and statistics, the binomial distribution is the most basic discrete probability distribution defined on :math:`[0, n] \cap \mathbb{N}`,
  21. which can be viewed as the number of times a potentially unfair coin is tossed to get heads, and the result
  22. of its random variable can be viewed as the sum of a series of independent Bernoulli experiments.
  23. The probability mass function (pmf) is
  24. .. math::
  25. pmf(x; n, p) = \frac{n!}{x!(n-x)!}p^{x}(1-p)^{n-x}
  26. In the above equation:
  27. * :math:`total\_count = n`: is the size, meaning the total number of Bernoulli experiments.
  28. * :math:`probs = p`: is the probability of the event happening in one Bernoulli experiments.
  29. Args:
  30. total_count(int|Tensor): The size of Binomial distribution which should be greater than 0, meaning the number of independent bernoulli
  31. trials with probability parameter :math:`p`. The data type will be converted to 1-D Tensor with paddle global default dtype if the input
  32. :attr:`probs` is not Tensor, otherwise will be converted to the same as :attr:`probs`.
  33. probs(float|Tensor): The probability of Binomial distribution which should reside in [0, 1], meaning the probability of success
  34. for each individual bernoulli trial. If the input data type is float, it will be converted to a 1-D Tensor with paddle global default dtype.
  35. Examples:
  36. .. code-block:: python
  37. >>> import paddle
  38. >>> from paddle.distribution import Binomial
  39. >>> paddle.set_device('cpu')
  40. >>> paddle.seed(100)
  41. >>> rv = Binomial(100, paddle.to_tensor([0.3, 0.6, 0.9]))
  42. >>> print(rv.sample([2]))
  43. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  44. [[31., 62., 93.],
  45. [29., 54., 91.]])
  46. >>> print(rv.mean)
  47. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  48. [30.00000191, 60.00000381, 90. ])
  49. >>> print(rv.entropy())
  50. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  51. [2.94053698, 3.00781751, 2.51124287])
  52. """
  53. def __init__(self, total_count, probs):
  54. self.dtype = paddle.get_default_dtype()
  55. self.total_count, self.probs = self._to_tensor(total_count, probs)
  56. if not self._check_constraint(self.total_count, self.probs):
  57. raise ValueError(
  58. 'Every element of input parameter `total_count` should be grater than or equal to one, and `probs` should be grater than or equal to zero and less than or equal to one.'
  59. )
  60. if self.total_count.shape == []:
  61. batch_shape = (1,)
  62. else:
  63. batch_shape = self.total_count.shape
  64. super().__init__(batch_shape)
  65. def _to_tensor(self, total_count, probs):
  66. """Convert the input parameters into Tensors if they were not and broadcast them
  67. Returns:
  68. Tuple[Tensor, Tensor]: converted total_count and probs.
  69. """
  70. # convert type
  71. if isinstance(probs, float):
  72. probs = paddle.to_tensor(probs, dtype=self.dtype)
  73. else:
  74. self.dtype = probs.dtype
  75. if isinstance(total_count, int):
  76. total_count = paddle.to_tensor(total_count, dtype=self.dtype)
  77. else:
  78. total_count = paddle.cast(total_count, dtype=self.dtype)
  79. # broadcast tensor
  80. return paddle.broadcast_tensors([total_count, probs])
  81. def _check_constraint(self, total_count, probs):
  82. """Check the constraints for input parameters
  83. Args:
  84. total_count (Tensor)
  85. probs (Tensor)
  86. Returns:
  87. bool: pass or not.
  88. """
  89. total_count_check = (total_count >= 1).all()
  90. probability_check = (probs >= 0).all() * (probs <= 1).all()
  91. return total_count_check and probability_check
  92. @property
  93. def mean(self):
  94. """Mean of binomial distribution.
  95. Returns:
  96. Tensor: mean value.
  97. """
  98. return self.total_count * self.probs
  99. @property
  100. def variance(self):
  101. """Variance of binomial distribution.
  102. Returns:
  103. Tensor: variance value.
  104. """
  105. return self.total_count * self.probs * (1 - self.probs)
  106. def sample(self, shape=()):
  107. """Generate binomial samples of the specified shape. The final shape would be ``shape+batch_shape`` .
  108. Args:
  109. shape (Sequence[int], optional): Prepended shape of the generated samples.
  110. Returns:
  111. Tensor: Sampled data with shape `sample_shape` + `batch_shape`. The returned data type is the same as `probs`.
  112. """
  113. if not isinstance(shape, Sequence):
  114. raise TypeError('sample shape must be Sequence object.')
  115. with paddle.set_grad_enabled(False):
  116. shape = tuple(shape)
  117. batch_shape = tuple(self.batch_shape)
  118. output_shape = tuple(shape + batch_shape)
  119. output_size = paddle.broadcast_to(
  120. self.total_count, shape=output_shape
  121. )
  122. output_prob = paddle.broadcast_to(self.probs, shape=output_shape)
  123. sample = paddle.binomial(
  124. paddle.cast(output_size, dtype="int32"), output_prob
  125. )
  126. return paddle.cast(sample, self.dtype)
  127. def entropy(self):
  128. r"""Shannon entropy in nats.
  129. The entropy is
  130. .. math::
  131. \mathcal{H}(X) = - \sum_{x \in \Omega} p(x) \log{p(x)}
  132. In the above equation:
  133. * :math:`\Omega`: is the support of the distribution.
  134. Returns:
  135. Tensor: Shannon entropy of binomial distribution. The data type is the same as `probs`.
  136. """
  137. values = self._enumerate_support()
  138. log_prob = self.log_prob(values)
  139. return -(paddle.exp(log_prob) * log_prob).sum(0)
  140. def _enumerate_support(self):
  141. """Return the support of binomial distribution [0, 1, ... ,n]
  142. Returns:
  143. Tensor: the support of binomial distribution
  144. """
  145. values = paddle.arange(
  146. 1 + paddle.max(self.total_count), dtype=self.dtype
  147. )
  148. values = values.reshape((-1,) + (1,) * len(self.batch_shape))
  149. return values
  150. def log_prob(self, value):
  151. """Log probability density/mass function.
  152. Args:
  153. value (Tensor): The input tensor.
  154. Returns:
  155. Tensor: log probability. The data type is the same as `probs`.
  156. """
  157. value = paddle.cast(value, dtype=self.dtype)
  158. # combination
  159. log_comb = (
  160. paddle.lgamma(self.total_count + 1.0)
  161. - paddle.lgamma(self.total_count - value + 1.0)
  162. - paddle.lgamma(value + 1.0)
  163. )
  164. eps = paddle.finfo(self.probs.dtype).eps
  165. probs = paddle.clip(self.probs, min=eps, max=1 - eps)
  166. # log_p
  167. return paddle.nan_to_num(
  168. (
  169. log_comb
  170. + value * paddle.log(probs)
  171. + (self.total_count - value) * paddle.log(1 - probs)
  172. ),
  173. neginf=-eps,
  174. )
  175. def prob(self, value):
  176. """Probability density/mass function.
  177. Args:
  178. value (Tensor): The input tensor.
  179. Returns:
  180. Tensor: probability. The data type is the same as `probs`.
  181. """
  182. return paddle.exp(self.log_prob(value))
  183. def kl_divergence(self, other):
  184. r"""The KL-divergence between two binomial distributions with the same :attr:`total_count`.
  185. The probability density function (pdf) is
  186. .. math::
  187. KL\_divergence(n_1, p_1, n_2, p_2) = \sum_x p_1(x) \log{\frac{p_1(x)}{p_2(x)}}
  188. .. math::
  189. p_1(x) = \frac{n_1!}{x!(n_1-x)!}p_1^{x}(1-p_1)^{n_1-x}
  190. .. math::
  191. p_2(x) = \frac{n_2!}{x!(n_2-x)!}p_2^{x}(1-p_2)^{n_2-x}
  192. Args:
  193. other (Binomial): instance of ``Binomial``.
  194. Returns:
  195. Tensor: kl-divergence between two binomial distributions. The data type is the same as `probs`.
  196. """
  197. if not (paddle.equal(self.total_count, other.total_count)).all():
  198. raise ValueError(
  199. "KL divergence of two binomial distributions should share the same `total_count` and `batch_shape`."
  200. )
  201. support = self._enumerate_support()
  202. log_prob_1 = self.log_prob(support)
  203. log_prob_2 = other.log_prob(support)
  204. return (
  205. paddle.multiply(
  206. paddle.exp(log_prob_1),
  207. (paddle.subtract(log_prob_1, log_prob_2)),
  208. )
  209. ).sum(0)