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