negative_binomial.py 4.2 KB

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