binomial.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. # mypy: allow-untyped-defs
  2. from typing import Optional, Union
  3. import torch
  4. from torch import Tensor
  5. from torch.distributions import constraints
  6. from torch.distributions.distribution import Distribution
  7. from torch.distributions.utils import (
  8. broadcast_all,
  9. lazy_property,
  10. logits_to_probs,
  11. probs_to_logits,
  12. )
  13. __all__ = ["Binomial"]
  14. def _clamp_by_zero(x):
  15. # works like clamp(x, min=0) but has grad at 0 is 0.5
  16. return (x.clamp(min=0) + x - x.clamp(max=0)) / 2
  17. class Binomial(Distribution):
  18. r"""
  19. Creates a Binomial distribution parameterized by :attr:`total_count` and
  20. either :attr:`probs` or :attr:`logits` (but not both). :attr:`total_count` must be
  21. broadcastable with :attr:`probs`/:attr:`logits`.
  22. Example::
  23. >>> # xdoctest: +IGNORE_WANT("non-deterministic")
  24. >>> m = Binomial(100, torch.tensor([0 , .2, .8, 1]))
  25. >>> x = m.sample()
  26. tensor([ 0., 22., 71., 100.])
  27. >>> m = Binomial(torch.tensor([[5.], [10.]]), torch.tensor([0.5, 0.8]))
  28. >>> x = m.sample()
  29. tensor([[ 4., 5.],
  30. [ 7., 6.]])
  31. Args:
  32. total_count (int or Tensor): number of Bernoulli trials
  33. probs (Tensor): Event probabilities
  34. logits (Tensor): Event log-odds
  35. """
  36. arg_constraints = {
  37. "total_count": constraints.nonnegative_integer,
  38. "probs": constraints.unit_interval,
  39. "logits": constraints.real,
  40. }
  41. has_enumerate_support = True
  42. def __init__(
  43. self,
  44. total_count: Union[Tensor, int] = 1,
  45. probs: Optional[Tensor] = None,
  46. logits: Optional[Tensor] = None,
  47. validate_args: Optional[bool] = None,
  48. ) -> None:
  49. if (probs is None) == (logits is None):
  50. raise ValueError(
  51. "Either `probs` or `logits` must be specified, but not both."
  52. )
  53. if probs is not None:
  54. (
  55. self.total_count,
  56. self.probs,
  57. ) = broadcast_all(total_count, probs)
  58. self.total_count = self.total_count.type_as(self.probs)
  59. else:
  60. assert logits is not None # helps mypy
  61. (
  62. self.total_count,
  63. self.logits,
  64. ) = broadcast_all(total_count, logits)
  65. self.total_count = self.total_count.type_as(self.logits)
  66. self._param = self.probs if probs is not None else self.logits
  67. batch_shape = self._param.size()
  68. super().__init__(batch_shape, validate_args=validate_args)
  69. def expand(self, batch_shape, _instance=None):
  70. new = self._get_checked_instance(Binomial, _instance)
  71. batch_shape = torch.Size(batch_shape)
  72. new.total_count = self.total_count.expand(batch_shape)
  73. if "probs" in self.__dict__:
  74. new.probs = self.probs.expand(batch_shape)
  75. new._param = new.probs
  76. if "logits" in self.__dict__:
  77. new.logits = self.logits.expand(batch_shape)
  78. new._param = new.logits
  79. super(Binomial, new).__init__(batch_shape, validate_args=False)
  80. new._validate_args = self._validate_args
  81. return new
  82. def _new(self, *args, **kwargs):
  83. return self._param.new(*args, **kwargs)
  84. @constraints.dependent_property(is_discrete=True, event_dim=0)
  85. def support(self):
  86. return constraints.integer_interval(0, self.total_count)
  87. @property
  88. def mean(self) -> Tensor:
  89. return self.total_count * self.probs
  90. @property
  91. def mode(self) -> Tensor:
  92. return ((self.total_count + 1) * self.probs).floor().clamp(max=self.total_count)
  93. @property
  94. def variance(self) -> Tensor:
  95. return self.total_count * self.probs * (1 - self.probs)
  96. @lazy_property
  97. def logits(self) -> Tensor:
  98. return probs_to_logits(self.probs, is_binary=True)
  99. @lazy_property
  100. def probs(self) -> Tensor:
  101. return logits_to_probs(self.logits, is_binary=True)
  102. @property
  103. def param_shape(self) -> torch.Size:
  104. return self._param.size()
  105. def sample(self, sample_shape=torch.Size()):
  106. shape = self._extended_shape(sample_shape)
  107. with torch.no_grad():
  108. return torch.binomial(
  109. self.total_count.expand(shape), self.probs.expand(shape)
  110. )
  111. def log_prob(self, value):
  112. if self._validate_args:
  113. self._validate_sample(value)
  114. log_factorial_n = torch.lgamma(self.total_count + 1)
  115. log_factorial_k = torch.lgamma(value + 1)
  116. log_factorial_nmk = torch.lgamma(self.total_count - value + 1)
  117. # k * log(p) + (n - k) * log(1 - p) = k * (log(p) - log(1 - p)) + n * log(1 - p)
  118. # (case logit < 0) = k * logit - n * log1p(e^logit)
  119. # (case logit > 0) = k * logit - n * (log(p) - log(1 - p)) + n * log(p)
  120. # = k * logit - n * logit - n * log1p(e^-logit)
  121. # (merge two cases) = k * logit - n * max(logit, 0) - n * log1p(e^-|logit|)
  122. normalize_term = (
  123. self.total_count * _clamp_by_zero(self.logits)
  124. + self.total_count * torch.log1p(torch.exp(-torch.abs(self.logits)))
  125. - log_factorial_n
  126. )
  127. return (
  128. value * self.logits - log_factorial_k - log_factorial_nmk - normalize_term
  129. )
  130. def entropy(self):
  131. total_count = int(self.total_count.max())
  132. if not self.total_count.min() == total_count:
  133. raise NotImplementedError(
  134. "Inhomogeneous total count not supported by `entropy`."
  135. )
  136. log_prob = self.log_prob(self.enumerate_support(False))
  137. return -(torch.exp(log_prob) * log_prob).sum(0)
  138. def enumerate_support(self, expand=True):
  139. total_count = int(self.total_count.max())
  140. if not self.total_count.min() == total_count:
  141. raise NotImplementedError(
  142. "Inhomogeneous total count not supported by `enumerate_support`."
  143. )
  144. values = torch.arange(
  145. 1 + total_count, dtype=self._param.dtype, device=self._param.device
  146. )
  147. values = values.view((-1,) + (1,) * len(self._batch_shape))
  148. if expand:
  149. values = values.expand((-1,) + self._batch_shape)
  150. return values