Caffe2 - Python API
A deep learning, cross platform ML framework
exponential.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
7 
8 
10  r"""
11  Creates a Exponential distribution parameterized by :attr:`rate`.
12 
13  Example::
14 
15  >>> m = Exponential(torch.tensor([1.0]))
16  >>> m.sample() # Exponential distributed with rate=1
17  tensor([ 0.1046])
18 
19  Args:
20  rate (float or Tensor): rate = 1 / scale of the distribution
21  """
22  arg_constraints = {'rate': constraints.positive}
23  support = constraints.positive
24  has_rsample = True
25  _mean_carrier_measure = 0
26 
27  @property
28  def mean(self):
29  return self.rate.reciprocal()
30 
31  @property
32  def stddev(self):
33  return self.rate.reciprocal()
34 
35  @property
36  def variance(self):
37  return self.rate.pow(-2)
38 
39  def __init__(self, rate, validate_args=None):
40  self.rate, = broadcast_all(rate)
41  batch_shape = torch.Size() if isinstance(rate, Number) else self.rate.size()
42  super(Exponential, self).__init__(batch_shape, validate_args=validate_args)
43 
44  def expand(self, batch_shape, _instance=None):
45  new = self._get_checked_instance(Exponential, _instance)
46  batch_shape = torch.Size(batch_shape)
47  new.rate = self.rate.expand(batch_shape)
48  super(Exponential, new).__init__(batch_shape, validate_args=False)
49  new._validate_args = self._validate_args
50  return new
51 
52  def rsample(self, sample_shape=torch.Size()):
53  shape = self._extended_shape(sample_shape)
54  if torch._C._get_tracing_state():
55  # [JIT WORKAROUND] lack of support for ._exponential()
56  u = torch.rand(shape, dtype=self.rate.dtype, device=self.rate.device)
57  return -(-u).log1p() / self.rate
58  return self.rate.new(shape).exponential_() / self.rate
59 
60  def log_prob(self, value):
61  if self._validate_args:
62  self._validate_sample(value)
63  return self.rate.log() - self.rate * value
64 
65  def cdf(self, value):
66  if self._validate_args:
67  self._validate_sample(value)
68  return 1 - torch.exp(-self.rate * value)
69 
70  def icdf(self, value):
71  if self._validate_args:
72  self._validate_sample(value)
73  return -torch.log(1 - value) / self.rate
74 
75  def entropy(self):
76  return 1.0 - torch.log(self.rate)
77 
78  @property
79  def _natural_params(self):
80  return (-self.rate, )
81 
82  def _log_normalizer(self, x):
83  return -torch.log(-x)
def _get_checked_instance(self, cls, _instance=None)
def _extended_shape(self, sample_shape=torch.Size())