pytorch

Форк
0
/
categorical.py 
155 строк · 5.6 Кб
1
import torch
2
from torch import nan
3
from torch.distributions import constraints
4
from torch.distributions.distribution import Distribution
5
from torch.distributions.utils import lazy_property, logits_to_probs, probs_to_logits
6

7
__all__ = ["Categorical"]
8

9

10
class Categorical(Distribution):
11
    r"""
12
    Creates a categorical distribution parameterized by either :attr:`probs` or
13
    :attr:`logits` (but not both).
14

15
    .. note::
16
        It is equivalent to the distribution that :func:`torch.multinomial`
17
        samples from.
18

19
    Samples are integers from :math:`\{0, \ldots, K-1\}` where `K` is ``probs.size(-1)``.
20

21
    If `probs` is 1-dimensional with length-`K`, each element is the relative probability
22
    of sampling the class at that index.
23

24
    If `probs` is N-dimensional, the first N-1 dimensions are treated as a batch of
25
    relative probability vectors.
26

27
    .. note:: The `probs` argument must be non-negative, finite and have a non-zero sum,
28
              and it will be normalized to sum to 1 along the last dimension. :attr:`probs`
29
              will return this normalized value.
30
              The `logits` argument will be interpreted as unnormalized log probabilities
31
              and can therefore be any real number. It will likewise be normalized so that
32
              the resulting probabilities sum to 1 along the last dimension. :attr:`logits`
33
              will return this normalized value.
34

35
    See also: :func:`torch.multinomial`
36

37
    Example::
38

39
        >>> # xdoctest: +IGNORE_WANT("non-deterministic")
40
        >>> m = Categorical(torch.tensor([ 0.25, 0.25, 0.25, 0.25 ]))
41
        >>> m.sample()  # equal probability of 0, 1, 2, 3
42
        tensor(3)
43

44
    Args:
45
        probs (Tensor): event probabilities
46
        logits (Tensor): event log probabilities (unnormalized)
47
    """
48
    arg_constraints = {"probs": constraints.simplex, "logits": constraints.real_vector}
49
    has_enumerate_support = True
50

51
    def __init__(self, probs=None, logits=None, validate_args=None):
52
        if (probs is None) == (logits is None):
53
            raise ValueError(
54
                "Either `probs` or `logits` must be specified, but not both."
55
            )
56
        if probs is not None:
57
            if probs.dim() < 1:
58
                raise ValueError("`probs` parameter must be at least one-dimensional.")
59
            self.probs = probs / probs.sum(-1, keepdim=True)
60
        else:
61
            if logits.dim() < 1:
62
                raise ValueError("`logits` parameter must be at least one-dimensional.")
63
            # Normalize
64
            self.logits = logits - logits.logsumexp(dim=-1, keepdim=True)
65
        self._param = self.probs if probs is not None else self.logits
66
        self._num_events = self._param.size()[-1]
67
        batch_shape = (
68
            self._param.size()[:-1] if self._param.ndimension() > 1 else torch.Size()
69
        )
70
        super().__init__(batch_shape, validate_args=validate_args)
71

72
    def expand(self, batch_shape, _instance=None):
73
        new = self._get_checked_instance(Categorical, _instance)
74
        batch_shape = torch.Size(batch_shape)
75
        param_shape = batch_shape + torch.Size((self._num_events,))
76
        if "probs" in self.__dict__:
77
            new.probs = self.probs.expand(param_shape)
78
            new._param = new.probs
79
        if "logits" in self.__dict__:
80
            new.logits = self.logits.expand(param_shape)
81
            new._param = new.logits
82
        new._num_events = self._num_events
83
        super(Categorical, new).__init__(batch_shape, validate_args=False)
84
        new._validate_args = self._validate_args
85
        return new
86

87
    def _new(self, *args, **kwargs):
88
        return self._param.new(*args, **kwargs)
89

90
    @constraints.dependent_property(is_discrete=True, event_dim=0)
91
    def support(self):
92
        return constraints.integer_interval(0, self._num_events - 1)
93

94
    @lazy_property
95
    def logits(self):
96
        return probs_to_logits(self.probs)
97

98
    @lazy_property
99
    def probs(self):
100
        return logits_to_probs(self.logits)
101

102
    @property
103
    def param_shape(self):
104
        return self._param.size()
105

106
    @property
107
    def mean(self):
108
        return torch.full(
109
            self._extended_shape(),
110
            nan,
111
            dtype=self.probs.dtype,
112
            device=self.probs.device,
113
        )
114

115
    @property
116
    def mode(self):
117
        return self.probs.argmax(axis=-1)
118

119
    @property
120
    def variance(self):
121
        return torch.full(
122
            self._extended_shape(),
123
            nan,
124
            dtype=self.probs.dtype,
125
            device=self.probs.device,
126
        )
127

128
    def sample(self, sample_shape=torch.Size()):
129
        if not isinstance(sample_shape, torch.Size):
130
            sample_shape = torch.Size(sample_shape)
131
        probs_2d = self.probs.reshape(-1, self._num_events)
132
        samples_2d = torch.multinomial(probs_2d, sample_shape.numel(), True).T
133
        return samples_2d.reshape(self._extended_shape(sample_shape))
134

135
    def log_prob(self, value):
136
        if self._validate_args:
137
            self._validate_sample(value)
138
        value = value.long().unsqueeze(-1)
139
        value, log_pmf = torch.broadcast_tensors(value, self.logits)
140
        value = value[..., :1]
141
        return log_pmf.gather(-1, value).squeeze(-1)
142

143
    def entropy(self):
144
        min_real = torch.finfo(self.logits.dtype).min
145
        logits = torch.clamp(self.logits, min=min_real)
146
        p_log_p = logits * self.probs
147
        return -p_log_p.sum(-1)
148

149
    def enumerate_support(self, expand=True):
150
        num_events = self._num_events
151
        values = torch.arange(num_events, dtype=torch.long, device=self._param.device)
152
        values = values.view((-1,) + (1,) * len(self._batch_shape))
153
        if expand:
154
            values = values.expand((-1,) + self._batch_shape)
155
        return values
156

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

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

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

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