pytorch

Форк
0
116 строк · 3.8 Кб
1
import math
2

3
import torch
4
from torch import inf, nan
5
from torch.distributions import Chi2, constraints
6
from torch.distributions.distribution import Distribution
7
from torch.distributions.utils import _standard_normal, broadcast_all
8

9
__all__ = ["StudentT"]
10

11

12
class StudentT(Distribution):
13
    r"""
14
    Creates a Student's t-distribution parameterized by degree of
15
    freedom :attr:`df`, mean :attr:`loc` and scale :attr:`scale`.
16

17
    Example::
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
22
        tensor([ 0.1046])
23

24
    Args:
25
        df (float or Tensor): degrees of freedom
26
        loc (float or Tensor): mean of the distribution
27
        scale (float or Tensor): scale of the distribution
28
    """
29
    arg_constraints = {
30
        "df": constraints.positive,
31
        "loc": constraints.real,
32
        "scale": constraints.positive,
33
    }
34
    support = constraints.real
35
    has_rsample = True
36

37
    @property
38
    def mean(self):
39
        m = self.loc.clone(memory_format=torch.contiguous_format)
40
        m[self.df <= 1] = nan
41
        return m
42

43
    @property
44
    def mode(self):
45
        return self.loc
46

47
    @property
48
    def variance(self):
49
        m = self.df.clone(memory_format=torch.contiguous_format)
50
        m[self.df > 2] = (
51
            self.scale[self.df > 2].pow(2)
52
            * self.df[self.df > 2]
53
            / (self.df[self.df > 2] - 2)
54
        )
55
        m[(self.df <= 2) & (self.df > 1)] = inf
56
        m[self.df <= 1] = nan
57
        return m
58

59
    def __init__(self, df, loc=0.0, scale=1.0, validate_args=None):
60
        self.df, self.loc, self.scale = broadcast_all(df, loc, scale)
61
        self._chi2 = Chi2(self.df)
62
        batch_shape = self.df.size()
63
        super().__init__(batch_shape, validate_args=validate_args)
64

65
    def expand(self, batch_shape, _instance=None):
66
        new = self._get_checked_instance(StudentT, _instance)
67
        batch_shape = torch.Size(batch_shape)
68
        new.df = self.df.expand(batch_shape)
69
        new.loc = self.loc.expand(batch_shape)
70
        new.scale = self.scale.expand(batch_shape)
71
        new._chi2 = self._chi2.expand(batch_shape)
72
        super(StudentT, new).__init__(batch_shape, validate_args=False)
73
        new._validate_args = self._validate_args
74
        return new
75

76
    def 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)
84
        shape = self._extended_shape(sample_shape)
85
        X = _standard_normal(shape, dtype=self.df.dtype, device=self.df.device)
86
        Z = self._chi2.rsample(sample_shape)
87
        Y = X * torch.rsqrt(Z / self.df)
88
        return self.loc + self.scale * Y
89

90
    def log_prob(self, value):
91
        if self._validate_args:
92
            self._validate_sample(value)
93
        y = (value - self.loc) / self.scale
94
        Z = (
95
            self.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
        )
101
        return -0.5 * (self.df + 1.0) * torch.log1p(y**2.0 / self.df) - Z
102

103
    def entropy(self):
104
        lbeta = (
105
            torch.lgamma(0.5 * self.df)
106
            + math.lgamma(0.5)
107
            - torch.lgamma(0.5 * (self.df + 1))
108
        )
109
        return (
110
            self.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

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.