Caffe2 - Python API
A deep learning, cross platform ML framework
weibull.py
1 import torch
2 from torch.distributions import constraints
3 from torch.distributions.exponential import Exponential
4 from torch.distributions.transformed_distribution import TransformedDistribution
5 from torch.distributions.transforms import AffineTransform, PowerTransform
6 from torch.distributions.utils import broadcast_all
7 from torch.distributions.gumbel import euler_constant
8 
9 
11  r"""
12  Samples from a two-parameter Weibull distribution.
13 
14  Example:
15 
16  >>> m = Weibull(torch.tensor([1.0]), torch.tensor([1.0]))
17  >>> m.sample() # sample from a Weibull distribution with scale=1, concentration=1
18  tensor([ 0.4784])
19 
20  Args:
21  scale (float or Tensor): Scale parameter of distribution (lambda).
22  concentration (float or Tensor): Concentration parameter of distribution (k/shape).
23  """
24  arg_constraints = {'scale': constraints.positive, 'concentration': constraints.positive}
25  support = constraints.positive
26 
27  def __init__(self, scale, concentration, validate_args=None):
28  self.scale, self.concentration = broadcast_all(scale, concentration)
29  self.concentration_reciprocal = self.concentration.reciprocal()
30  base_dist = Exponential(torch.ones_like(self.scale))
31  transforms = [PowerTransform(exponent=self.concentration_reciprocal),
32  AffineTransform(loc=0, scale=self.scale)]
33  super(Weibull, self).__init__(base_dist,
34  transforms,
35  validate_args=validate_args)
36 
37  def expand(self, batch_shape, _instance=None):
38  new = self._get_checked_instance(Weibull, _instance)
39  new.scale = self.scale.expand(batch_shape)
40  new.concentration = self.concentration.expand(batch_shape)
41  new.concentration_reciprocal = new.concentration.reciprocal()
42  base_dist = self.base_dist.expand(batch_shape)
43  transforms = [PowerTransform(exponent=new.concentration_reciprocal),
44  AffineTransform(loc=0, scale=new.scale)]
45  super(Weibull, new).__init__(base_dist,
46  transforms,
47  validate_args=False)
48  new._validate_args = self._validate_args
49  return new
50 
51  @property
52  def mean(self):
53  return self.scale * torch.exp(torch.lgamma(1 + self.concentration_reciprocal))
54 
55  @property
56  def variance(self):
57  return self.scale.pow(2) * (torch.exp(torch.lgamma(1 + 2 * self.concentration_reciprocal)) -
58  torch.exp(2 * torch.lgamma(1 + self.concentration_reciprocal)))
59 
60  def entropy(self):
61  return euler_constant * (1 - self.concentration_reciprocal) + \
62  torch.log(self.scale * self.concentration_reciprocal) + 1
def _get_checked_instance(self, cls, _instance=None)