pytorch
119 строк · 3.8 Кб
1# mypy: allow-untyped-defs
2import math3
4import torch5from torch import inf, nan6from torch.distributions import Chi2, constraints7from torch.distributions.distribution import Distribution8from torch.distributions.utils import _standard_normal, broadcast_all9from torch.types import _size10
11
12__all__ = ["StudentT"]13
14
15class StudentT(Distribution):16r"""17Creates a Student's t-distribution parameterized by degree of
18freedom :attr:`df`, mean :attr:`loc` and scale :attr:`scale`.
19
20Example::
21
22>>> # xdoctest: +IGNORE_WANT("non-deterministic")
23>>> m = StudentT(torch.tensor([2.0]))
24>>> m.sample() # Student's t-distributed with degrees of freedom=2
25tensor([ 0.1046])
26
27Args:
28df (float or Tensor): degrees of freedom
29loc (float or Tensor): mean of the distribution
30scale (float or Tensor): scale of the distribution
31"""
32arg_constraints = {33"df": constraints.positive,34"loc": constraints.real,35"scale": constraints.positive,36}37support = constraints.real38has_rsample = True39
40@property41def mean(self):42m = self.loc.clone(memory_format=torch.contiguous_format)43m[self.df <= 1] = nan44return m45
46@property47def mode(self):48return self.loc49
50@property51def variance(self):52m = self.df.clone(memory_format=torch.contiguous_format)53m[self.df > 2] = (54self.scale[self.df > 2].pow(2)55* self.df[self.df > 2]56/ (self.df[self.df > 2] - 2)57)58m[(self.df <= 2) & (self.df > 1)] = inf59m[self.df <= 1] = nan60return m61
62def __init__(self, df, loc=0.0, scale=1.0, validate_args=None):63self.df, self.loc, self.scale = broadcast_all(df, loc, scale)64self._chi2 = Chi2(self.df)65batch_shape = self.df.size()66super().__init__(batch_shape, validate_args=validate_args)67
68def expand(self, batch_shape, _instance=None):69new = self._get_checked_instance(StudentT, _instance)70batch_shape = torch.Size(batch_shape)71new.df = self.df.expand(batch_shape)72new.loc = self.loc.expand(batch_shape)73new.scale = self.scale.expand(batch_shape)74new._chi2 = self._chi2.expand(batch_shape)75super(StudentT, new).__init__(batch_shape, validate_args=False)76new._validate_args = self._validate_args77return new78
79def rsample(self, sample_shape: _size = torch.Size()) -> torch.Tensor:80# NOTE: This does not agree with scipy implementation as much as other distributions.81# (see https://github.com/fritzo/notebooks/blob/master/debug-student-t.ipynb). Using DoubleTensor82# parameters seems to help.83
84# X ~ Normal(0, 1)85# Z ~ Chi2(df)86# Y = X / sqrt(Z / df) ~ StudentT(df)87shape = self._extended_shape(sample_shape)88X = _standard_normal(shape, dtype=self.df.dtype, device=self.df.device)89Z = self._chi2.rsample(sample_shape)90Y = X * torch.rsqrt(Z / self.df)91return self.loc + self.scale * Y92
93def log_prob(self, value):94if self._validate_args:95self._validate_sample(value)96y = (value - self.loc) / self.scale97Z = (98self.scale.log()99+ 0.5 * self.df.log()100+ 0.5 * math.log(math.pi)101+ torch.lgamma(0.5 * self.df)102- torch.lgamma(0.5 * (self.df + 1.0))103)104return -0.5 * (self.df + 1.0) * torch.log1p(y**2.0 / self.df) - Z105
106def entropy(self):107lbeta = (108torch.lgamma(0.5 * self.df)109+ math.lgamma(0.5)110- torch.lgamma(0.5 * (self.df + 1))111)112return (113self.scale.log()114+ 0.5115* (self.df + 1)116* (torch.digamma(0.5 * (self.df + 1)) - torch.digamma(0.5 * self.df))117+ 0.5 * self.df.log()118+ lbeta119)120