1 from numbers
import Number
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`. 16 >>> m = Binomial(100, torch.tensor([0 , .2, .8, 1])) 18 tensor([ 0., 22., 71., 100.]) 20 >>> m = Binomial(torch.tensor([[5.], [10.]]), torch.tensor([0.5, 0.8])) 26 total_count (int or Tensor): number of Bernoulli trials 27 probs (Tensor): Event probabilities 28 logits (Tensor): Event log-odds 30 arg_constraints = {
'total_count': constraints.nonnegative_integer,
31 'probs': constraints.unit_interval,
32 'logits': constraints.real}
33 has_enumerate_support =
True 35 def __init__(self, total_count=1, probs=None, logits=None, validate_args=None):
36 if (probs
is None) == (logits
is None):
37 raise ValueError(
"Either `probs` or `logits` must be specified, but not both.")
41 is_scalar = isinstance(self.
probs, Number)
45 is_scalar = isinstance(self.
logits, Number)
49 batch_shape = torch.Size()
51 batch_shape = self._param.size()
52 super(Binomial, self).__init__(batch_shape, validate_args=validate_args)
54 def expand(self, batch_shape, _instance=None):
56 batch_shape = torch.Size(batch_shape)
57 new.total_count = self.total_count.expand(batch_shape)
58 if 'probs' in self.__dict__:
59 new.probs = self.probs.expand(batch_shape)
60 new._param = new.probs
62 new.logits = self.logits.expand(batch_shape)
63 new._param = new.logits
64 super(Binomial, new).__init__(batch_shape, validate_args=
False)
68 def _new(self, *args, **kwargs):
69 return self._param.new(*args, **kwargs)
71 @constraints.dependent_property
73 return constraints.integer_interval(0, self.
total_count)
85 return probs_to_logits(self.
probs, is_binary=
True)
89 return logits_to_probs(self.
logits, is_binary=
True)
92 def param_shape(self):
93 return self._param.size()
95 def sample(self, sample_shape=torch.Size()):
97 max_count = max(int(self.total_count.max()), 1)
99 bernoullis = torch.bernoulli(self.probs.unsqueeze(-1).expand(shape))
100 if self.total_count.min() != max_count:
101 arange = torch.arange(max_count, dtype=self._param.dtype, device=self._param.device)
102 mask = arange >= self.total_count.unsqueeze(-1)
103 if torch._C._get_tracing_state():
105 bernoullis[mask.expand(shape)] = 0.
107 bernoullis.masked_fill_(mask, 0.)
108 return bernoullis.sum(dim=-1)
110 def log_prob(self, value):
113 log_factorial_n = torch.lgamma(self.
total_count + 1)
114 log_factorial_k = torch.lgamma(value + 1)
115 log_factorial_nmk = torch.lgamma(self.
total_count - value + 1)
117 return (log_factorial_n - log_factorial_k - log_factorial_nmk +
120 def enumerate_support(self, expand=True):
121 total_count = int(self.total_count.max())
122 if not self.total_count.min() == total_count:
123 raise NotImplementedError(
"Inhomogeneous total count not supported by `enumerate_support`.")
124 values = torch.arange(1 + total_count, dtype=self._param.dtype, device=self._param.device)
125 values = values.view((-1,) + (1,) * len(self.
_batch_shape))
def _get_checked_instance(self, cls, _instance=None)
def _extended_shape(self, sample_shape=torch.Size())
def _validate_sample(self, value)