negative_binomial.py 4.2 KB

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