pytorch
116 строк · 3.8 Кб
1import math
2
3import torch
4from torch import inf, nan
5from torch.distributions import Chi2, constraints
6from torch.distributions.distribution import Distribution
7from torch.distributions.utils import _standard_normal, broadcast_all
8
9__all__ = ["StudentT"]
10
11
12class StudentT(Distribution):
13r"""
14Creates a Student's t-distribution parameterized by degree of
15freedom :attr:`df`, mean :attr:`loc` and scale :attr:`scale`.
16
17Example::
18
19>>> # xdoctest: +IGNORE_WANT("non-deterministic")
20>>> m = StudentT(torch.tensor([2.0]))
21>>> m.sample() # Student's t-distributed with degrees of freedom=2
22tensor([ 0.1046])
23
24Args:
25df (float or Tensor): degrees of freedom
26loc (float or Tensor): mean of the distribution
27scale (float or Tensor): scale of the distribution
28"""
29arg_constraints = {
30"df": constraints.positive,
31"loc": constraints.real,
32"scale": constraints.positive,
33}
34support = constraints.real
35has_rsample = True
36
37@property
38def mean(self):
39m = self.loc.clone(memory_format=torch.contiguous_format)
40m[self.df <= 1] = nan
41return m
42
43@property
44def mode(self):
45return self.loc
46
47@property
48def variance(self):
49m = self.df.clone(memory_format=torch.contiguous_format)
50m[self.df > 2] = (
51self.scale[self.df > 2].pow(2)
52* self.df[self.df > 2]
53/ (self.df[self.df > 2] - 2)
54)
55m[(self.df <= 2) & (self.df > 1)] = inf
56m[self.df <= 1] = nan
57return m
58
59def __init__(self, df, loc=0.0, scale=1.0, validate_args=None):
60self.df, self.loc, self.scale = broadcast_all(df, loc, scale)
61self._chi2 = Chi2(self.df)
62batch_shape = self.df.size()
63super().__init__(batch_shape, validate_args=validate_args)
64
65def expand(self, batch_shape, _instance=None):
66new = self._get_checked_instance(StudentT, _instance)
67batch_shape = torch.Size(batch_shape)
68new.df = self.df.expand(batch_shape)
69new.loc = self.loc.expand(batch_shape)
70new.scale = self.scale.expand(batch_shape)
71new._chi2 = self._chi2.expand(batch_shape)
72super(StudentT, new).__init__(batch_shape, validate_args=False)
73new._validate_args = self._validate_args
74return new
75
76def rsample(self, sample_shape=torch.Size()):
77# NOTE: This does not agree with scipy implementation as much as other distributions.
78# (see https://github.com/fritzo/notebooks/blob/master/debug-student-t.ipynb). Using DoubleTensor
79# parameters seems to help.
80
81# X ~ Normal(0, 1)
82# Z ~ Chi2(df)
83# Y = X / sqrt(Z / df) ~ StudentT(df)
84shape = self._extended_shape(sample_shape)
85X = _standard_normal(shape, dtype=self.df.dtype, device=self.df.device)
86Z = self._chi2.rsample(sample_shape)
87Y = X * torch.rsqrt(Z / self.df)
88return self.loc + self.scale * Y
89
90def log_prob(self, value):
91if self._validate_args:
92self._validate_sample(value)
93y = (value - self.loc) / self.scale
94Z = (
95self.scale.log()
96+ 0.5 * self.df.log()
97+ 0.5 * math.log(math.pi)
98+ torch.lgamma(0.5 * self.df)
99- torch.lgamma(0.5 * (self.df + 1.0))
100)
101return -0.5 * (self.df + 1.0) * torch.log1p(y**2.0 / self.df) - Z
102
103def entropy(self):
104lbeta = (
105torch.lgamma(0.5 * self.df)
106+ math.lgamma(0.5)
107- torch.lgamma(0.5 * (self.df + 1))
108)
109return (
110self.scale.log()
111+ 0.5
112* (self.df + 1)
113* (torch.digamma(0.5 * (self.df + 1)) - torch.digamma(0.5 * self.df))
114+ 0.5 * self.df.log()
115+ lbeta
116)
117