Caffe2 - Python API
A deep learning, cross platform ML framework
studentT.py
1 import math
2 from numbers import Number
3 
4 import torch
5 from torch._six import inf, nan
6 from torch.distributions import Chi2, constraints
7 from torch.distributions.distribution import Distribution
8 from torch.distributions.utils import _standard_normal, broadcast_all
9 
10 
12  r"""
13  Creates a Student's t-distribution parameterized by degree of
14  freedom :attr:`df`, mean :attr:`loc` and scale :attr:`scale`.
15 
16  Example::
17 
18  >>> m = StudentT(torch.tensor([2.0]))
19  >>> m.sample() # Student's t-distributed with degrees of freedom=2
20  tensor([ 0.1046])
21 
22  Args:
23  df (float or Tensor): degrees of freedom
24  loc (float or Tensor): mean of the distribution
25  scale (float or Tensor): scale of the distribution
26  """
27  arg_constraints = {'df': constraints.positive, 'loc': constraints.real, 'scale': constraints.positive}
28  support = constraints.real
29  has_rsample = True
30 
31  @property
32  def mean(self):
33  m = self.loc.clone()
34  m[self.df <= 1] = nan
35  return m
36 
37  @property
38  def variance(self):
39  m = self.df.clone()
40  m[self.df > 2] = self.scale[self.df > 2].pow(2) * self.df[self.df > 2] / (self.df[self.df > 2] - 2)
41  m[(self.df <= 2) & (self.df > 1)] = inf
42  m[self.df <= 1] = nan
43  return m
44 
45  def __init__(self, df, loc=0., scale=1., validate_args=None):
46  self.df, self.loc, self.scale = broadcast_all(df, loc, scale)
47  self._chi2 = Chi2(self.df)
48  batch_shape = self.df.size()
49  super(StudentT, self).__init__(batch_shape, validate_args=validate_args)
50 
51  def expand(self, batch_shape, _instance=None):
52  new = self._get_checked_instance(StudentT, _instance)
53  batch_shape = torch.Size(batch_shape)
54  new.df = self.df.expand(batch_shape)
55  new.loc = self.loc.expand(batch_shape)
56  new.scale = self.scale.expand(batch_shape)
57  new._chi2 = self._chi2.expand(batch_shape)
58  super(StudentT, new).__init__(batch_shape, validate_args=False)
59  new._validate_args = self._validate_args
60  return new
61 
62  def rsample(self, sample_shape=torch.Size()):
63  # NOTE: This does not agree with scipy implementation as much as other distributions.
64  # (see https://github.com/fritzo/notebooks/blob/master/debug-student-t.ipynb). Using DoubleTensor
65  # parameters seems to help.
66 
67  # X ~ Normal(0, 1)
68  # Z ~ Chi2(df)
69  # Y = X / sqrt(Z / df) ~ StudentT(df)
70  shape = self._extended_shape(sample_shape)
71  X = _standard_normal(shape, dtype=self.df.dtype, device=self.df.device)
72  Z = self._chi2.rsample(sample_shape)
73  Y = X * torch.rsqrt(Z / self.df)
74  return self.loc + self.scale * Y
75 
76  def log_prob(self, value):
77  if self._validate_args:
78  self._validate_sample(value)
79  y = (value - self.loc) / self.scale
80  Z = (self.scale.log() +
81  0.5 * self.df.log() +
82  0.5 * math.log(math.pi) +
83  torch.lgamma(0.5 * self.df) -
84  torch.lgamma(0.5 * (self.df + 1.)))
85  return -0.5 * (self.df + 1.) * torch.log1p(y**2. / self.df) - Z
86 
87  def entropy(self):
88  lbeta = torch.lgamma(0.5 * self.df) + math.lgamma(0.5) - torch.lgamma(0.5 * (self.df + 1))
89  return (self.scale.log() +
90  0.5 * (self.df + 1) *
91  (torch.digamma(0.5 * (self.df + 1)) - torch.digamma(0.5 * self.df)) +
92  0.5 * self.df.log() + lbeta)
def _get_checked_instance(self, cls, _instance=None)
def _extended_shape(self, sample_shape=torch.Size())