negative_binomial.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. # mypy: allow-untyped-defs
  2. import torch
  3. import torch.nn.functional as F
  4. from torch.distributions import constraints
  5. from torch.distributions.distribution import Distribution
  6. from torch.distributions.utils import (
  7. broadcast_all,
  8. lazy_property,
  9. logits_to_probs,
  10. probs_to_logits,
  11. )
  12. __all__ = ["NegativeBinomial"]
  13. class NegativeBinomial(Distribution):
  14. r"""
  15. Creates a Negative Binomial distribution, i.e. distribution
  16. of the number of successful independent and identical Bernoulli trials
  17. before :attr:`total_count` failures are achieved. The probability
  18. of success of each Bernoulli trial is :attr:`probs`.
  19. Args:
  20. total_count (float or Tensor): non-negative number of negative Bernoulli
  21. trials to stop, although the distribution is still valid for real
  22. valued count
  23. probs (Tensor): Event probabilities of success in the half open interval [0, 1)
  24. logits (Tensor): Event log-odds for probabilities of success
  25. """
  26. arg_constraints = {
  27. "total_count": constraints.greater_than_eq(0),
  28. "probs": constraints.half_open_interval(0.0, 1.0),
  29. "logits": constraints.real,
  30. }
  31. support = constraints.nonnegative_integer
  32. def __init__(self, total_count, probs=None, logits=None, validate_args=None):
  33. if (probs is None) == (logits is None):
  34. raise ValueError(
  35. "Either `probs` or `logits` must be specified, but not both."
  36. )
  37. if probs is not None:
  38. (
  39. self.total_count,
  40. self.probs,
  41. ) = broadcast_all(total_count, probs)
  42. self.total_count = self.total_count.type_as(self.probs)
  43. else:
  44. (
  45. self.total_count,
  46. self.logits,
  47. ) = broadcast_all(total_count, logits)
  48. self.total_count = self.total_count.type_as(self.logits)
  49. self._param = self.probs if probs is not None else self.logits
  50. batch_shape = self._param.size()
  51. super().__init__(batch_shape, validate_args=validate_args)
  52. def expand(self, batch_shape, _instance=None):
  53. new = self._get_checked_instance(NegativeBinomial, _instance)
  54. batch_shape = torch.Size(batch_shape)
  55. new.total_count = self.total_count.expand(batch_shape)
  56. if "probs" in self.__dict__:
  57. new.probs = self.probs.expand(batch_shape)
  58. new._param = new.probs
  59. if "logits" in self.__dict__:
  60. new.logits = self.logits.expand(batch_shape)
  61. new._param = new.logits
  62. super(NegativeBinomial, new).__init__(batch_shape, validate_args=False)
  63. new._validate_args = self._validate_args
  64. return new
  65. def _new(self, *args, **kwargs):
  66. return self._param.new(*args, **kwargs)
  67. @property
  68. def mean(self):
  69. return self.total_count * torch.exp(self.logits)
  70. @property
  71. def mode(self):
  72. return ((self.total_count - 1) * self.logits.exp()).floor().clamp(min=0.0)
  73. @property
  74. def variance(self):
  75. return self.mean / torch.sigmoid(-self.logits)
  76. @lazy_property
  77. def logits(self):
  78. return probs_to_logits(self.probs, is_binary=True)
  79. @lazy_property
  80. def probs(self):
  81. return logits_to_probs(self.logits, is_binary=True)
  82. @property
  83. def param_shape(self):
  84. return self._param.size()
  85. @lazy_property
  86. def _gamma(self):
  87. # Note we avoid validating because self.total_count can be zero.
  88. return torch.distributions.Gamma(
  89. concentration=self.total_count,
  90. rate=torch.exp(-self.logits),
  91. validate_args=False,
  92. )
  93. def sample(self, sample_shape=torch.Size()):
  94. with torch.no_grad():
  95. rate = self._gamma.sample(sample_shape=sample_shape)
  96. return torch.poisson(rate)
  97. def log_prob(self, value):
  98. if self._validate_args:
  99. self._validate_sample(value)
  100. log_unnormalized_prob = self.total_count * F.logsigmoid(
  101. -self.logits
  102. ) + value * F.logsigmoid(self.logits)
  103. log_normalization = (
  104. -torch.lgamma(self.total_count + value)
  105. + torch.lgamma(1.0 + value)
  106. + torch.lgamma(self.total_count)
  107. )
  108. # The case self.total_count == 0 and value == 0 has probability 1 but
  109. # lgamma(0) is infinite. Handle this case separately using a function
  110. # that does not modify tensors in place to allow Jit compilation.
  111. log_normalization = log_normalization.masked_fill(
  112. self.total_count + value == 0.0, 0.0
  113. )
  114. return log_unnormalized_prob - log_normalization