Caffe2 - Python API
A deep learning, cross platform ML framework
bernoulli.py
1 from numbers import Number
2 
3 import torch
4 from torch.distributions import constraints
5 from torch.distributions.exp_family import ExponentialFamily
6 from torch.distributions.utils import broadcast_all, probs_to_logits, logits_to_probs, lazy_property
7 from torch.nn.functional import binary_cross_entropy_with_logits
8 
9 
11  r"""
12  Creates a Bernoulli distribution parameterized by :attr:`probs`
13  or :attr:`logits` (but not both).
14 
15  Samples are binary (0 or 1). They take the value `1` with probability `p`
16  and `0` with probability `1 - p`.
17 
18  Example::
19 
20  >>> m = Bernoulli(torch.tensor([0.3]))
21  >>> m.sample() # 30% chance 1; 70% chance 0
22  tensor([ 0.])
23 
24  Args:
25  probs (Number, Tensor): the probability of sampling `1`
26  logits (Number, Tensor): the log-odds of sampling `1`
27  """
28  arg_constraints = {'probs': constraints.unit_interval,
29  'logits': constraints.real}
30  support = constraints.boolean
31  has_enumerate_support = True
32  _mean_carrier_measure = 0
33 
34  def __init__(self, probs=None, logits=None, validate_args=None):
35  if (probs is None) == (logits is None):
36  raise ValueError("Either `probs` or `logits` must be specified, but not both.")
37  if probs is not None:
38  is_scalar = isinstance(probs, Number)
39  self.probs, = broadcast_all(probs)
40  else:
41  is_scalar = isinstance(logits, Number)
42  self.logits, = broadcast_all(logits)
43  self._param = self.probs if probs is not None else self.logits
44  if is_scalar:
45  batch_shape = torch.Size()
46  else:
47  batch_shape = self._param.size()
48  super(Bernoulli, self).__init__(batch_shape, validate_args=validate_args)
49 
50  def expand(self, batch_shape, _instance=None):
51  new = self._get_checked_instance(Bernoulli, _instance)
52  batch_shape = torch.Size(batch_shape)
53  if 'probs' in self.__dict__:
54  new.probs = self.probs.expand(batch_shape)
55  new._param = new.probs
56  else:
57  new.logits = self.logits.expand(batch_shape)
58  new._param = new.logits
59  super(Bernoulli, new).__init__(batch_shape, validate_args=False)
60  new._validate_args = self._validate_args
61  return new
62 
63  def _new(self, *args, **kwargs):
64  return self._param.new(*args, **kwargs)
65 
66  @property
67  def mean(self):
68  return self.probs
69 
70  @property
71  def variance(self):
72  return self.probs * (1 - self.probs)
73 
74  @lazy_property
75  def logits(self):
76  return probs_to_logits(self.probs, is_binary=True)
77 
78  @lazy_property
79  def probs(self):
80  return logits_to_probs(self.logits, is_binary=True)
81 
82  @property
83  def param_shape(self):
84  return self._param.size()
85 
86  def sample(self, sample_shape=torch.Size()):
87  shape = self._extended_shape(sample_shape)
88  with torch.no_grad():
89  return torch.bernoulli(self.probs.expand(shape))
90 
91  def log_prob(self, value):
92  if self._validate_args:
93  self._validate_sample(value)
94  logits, value = broadcast_all(self.logits, value)
95  return -binary_cross_entropy_with_logits(logits, value, reduction='none')
96 
97  def entropy(self):
98  return binary_cross_entropy_with_logits(self.logits, self.probs, reduction='none')
99 
100  def enumerate_support(self, expand=True):
101  values = torch.arange(2, dtype=self._param.dtype, device=self._param.device)
102  values = values.view((-1,) + (1,) * len(self._batch_shape))
103  if expand:
104  values = values.expand((-1,) + self._batch_shape)
105  return values
106 
107  @property
108  def _natural_params(self):
109  return (torch.log(self.probs / (1 - self.probs)), )
110 
111  def _log_normalizer(self, x):
112  return torch.log(1 + torch.exp(x))
def _get_checked_instance(self, cls, _instance=None)
def _extended_shape(self, sample_shape=torch.Size())