binomial.py 5.9 KB

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