Caffe2 - Python API
A deep learning, cross platform ML framework
half_normal.py
1 import math
2 
3 import torch
4 from torch._six import inf
5 from torch.distributions import constraints
6 from torch.distributions.transforms import AbsTransform
7 from torch.distributions.normal import Normal
8 from torch.distributions.transformed_distribution import TransformedDistribution
9 
10 
12  r"""
13  Creates a half-normal distribution parameterized by `scale` where::
14 
15  X ~ Normal(0, scale)
16  Y = |X| ~ HalfNormal(scale)
17 
18  Example::
19 
20  >>> m = HalfNormal(torch.tensor([1.0]))
21  >>> m.sample() # half-normal distributed with scale=1
22  tensor([ 0.1046])
23 
24  Args:
25  scale (float or Tensor): scale of the full Normal distribution
26  """
27  arg_constraints = {'scale': constraints.positive}
28  support = constraints.positive
29  has_rsample = True
30 
31  def __init__(self, scale, validate_args=None):
32  base_dist = Normal(0, scale)
33  super(HalfNormal, self).__init__(base_dist, AbsTransform(),
34  validate_args=validate_args)
35 
36  def expand(self, batch_shape, _instance=None):
37  new = self._get_checked_instance(HalfNormal, _instance)
38  return super(HalfNormal, self).expand(batch_shape, _instance=new)
39 
40  @property
41  def scale(self):
42  return self.base_dist.scale
43 
44  @property
45  def mean(self):
46  return self.scale * math.sqrt(2 / math.pi)
47 
48  @property
49  def variance(self):
50  return self.scale.pow(2) * (1 - 2 / math.pi)
51 
52  def log_prob(self, value):
53  log_prob = self.base_dist.log_prob(value) + math.log(2)
54  log_prob[value.expand(log_prob.shape) < 0] = -inf
55  return log_prob
56 
57  def cdf(self, value):
58  return 2 * self.base_dist.cdf(value) - 1
59 
60  def icdf(self, prob):
61  return self.base_dist.icdf((prob + 1) / 2)
62 
63  def entropy(self):
64  return self.base_dist.entropy() - math.log(2)
def _get_checked_instance(self, cls, _instance=None)