binomial.py 5.5 KB

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