Caffe2 - Python API
A deep learning, cross platform ML framework
laplace.py
1 from numbers import Number
2 import torch
3 from torch.distributions import constraints
4 from torch.distributions.distribution import Distribution
5 from torch.distributions.utils import broadcast_all
6 
7 
9  r"""
10  Creates a Laplace distribution parameterized by :attr:`loc` and :attr:'scale'.
11 
12  Example::
13 
14  >>> m = Laplace(torch.tensor([0.0]), torch.tensor([1.0]))
15  >>> m.sample() # Laplace distributed with loc=0, scale=1
16  tensor([ 0.1046])
17 
18  Args:
19  loc (float or Tensor): mean of the distribution
20  scale (float or Tensor): scale of the distribution
21  """
22  arg_constraints = {'loc': constraints.real, 'scale': constraints.positive}
23  support = constraints.real
24  has_rsample = True
25 
26  @property
27  def mean(self):
28  return self.loc
29 
30  @property
31  def variance(self):
32  return 2 * self.scale.pow(2)
33 
34  @property
35  def stddev(self):
36  return (2 ** 0.5) * self.scale
37 
38  def __init__(self, loc, scale, validate_args=None):
39  self.loc, self.scale = broadcast_all(loc, scale)
40  if isinstance(loc, Number) and isinstance(scale, Number):
41  batch_shape = torch.Size()
42  else:
43  batch_shape = self.loc.size()
44  super(Laplace, self).__init__(batch_shape, validate_args=validate_args)
45 
46  def expand(self, batch_shape, _instance=None):
47  new = self._get_checked_instance(Laplace, _instance)
48  batch_shape = torch.Size(batch_shape)
49  new.loc = self.loc.expand(batch_shape)
50  new.scale = self.scale.expand(batch_shape)
51  super(Laplace, new).__init__(batch_shape, validate_args=False)
52  new._validate_args = self._validate_args
53  return new
54 
55  def rsample(self, sample_shape=torch.Size()):
56  shape = self._extended_shape(sample_shape)
57  finfo = torch.finfo(self.loc.dtype)
58  if torch._C._get_tracing_state():
59  # [JIT WORKAROUND] lack of support for .uniform_()
60  u = torch.rand(shape, dtype=self.loc.dtype, device=self.loc.device) * 2 - 1
61  return self.loc - self.scale * u.sign() * torch.log1p(-u.abs().clamp(min=finfo.tiny))
62  u = self.loc.new(shape).uniform_(finfo.eps - 1, 1)
63  # TODO: If we ever implement tensor.nextafter, below is what we want ideally.
64  # u = self.loc.new(shape).uniform_(self.loc.nextafter(-.5, 0), .5)
65  return self.loc - self.scale * u.sign() * torch.log1p(-u.abs())
66 
67  def log_prob(self, value):
68  if self._validate_args:
69  self._validate_sample(value)
70  return -torch.log(2 * self.scale) - torch.abs(value - self.loc) / self.scale
71 
72  def cdf(self, value):
73  if self._validate_args:
74  self._validate_sample(value)
75  return 0.5 - 0.5 * (value - self.loc).sign() * torch.expm1(-(value - self.loc).abs() / self.scale)
76 
77  def icdf(self, value):
78  if self._validate_args:
79  self._validate_sample(value)
80  term = value - 0.5
81  return self.loc - self.scale * (term).sign() * torch.log1p(-2 * term.abs())
82 
83  def entropy(self):
84  return 1 + torch.log(2 * self.scale)
def _get_checked_instance(self, cls, _instance=None)
def _extended_shape(self, sample_shape=torch.Size())