pytorch
155 строк · 5.6 Кб
1import torch
2from torch import nan
3from torch.distributions import constraints
4from torch.distributions.distribution import Distribution
5from torch.distributions.utils import lazy_property, logits_to_probs, probs_to_logits
6
7__all__ = ["Categorical"]
8
9
10class Categorical(Distribution):
11r"""
12Creates a categorical distribution parameterized by either :attr:`probs` or
13:attr:`logits` (but not both).
14
15.. note::
16It is equivalent to the distribution that :func:`torch.multinomial`
17samples from.
18
19Samples are integers from :math:`\{0, \ldots, K-1\}` where `K` is ``probs.size(-1)``.
20
21If `probs` is 1-dimensional with length-`K`, each element is the relative probability
22of sampling the class at that index.
23
24If `probs` is N-dimensional, the first N-1 dimensions are treated as a batch of
25relative probability vectors.
26
27.. note:: The `probs` argument must be non-negative, finite and have a non-zero sum,
28and it will be normalized to sum to 1 along the last dimension. :attr:`probs`
29will return this normalized value.
30The `logits` argument will be interpreted as unnormalized log probabilities
31and can therefore be any real number. It will likewise be normalized so that
32the resulting probabilities sum to 1 along the last dimension. :attr:`logits`
33will return this normalized value.
34
35See also: :func:`torch.multinomial`
36
37Example::
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
42tensor(3)
43
44Args:
45probs (Tensor): event probabilities
46logits (Tensor): event log probabilities (unnormalized)
47"""
48arg_constraints = {"probs": constraints.simplex, "logits": constraints.real_vector}
49has_enumerate_support = True
50
51def __init__(self, probs=None, logits=None, validate_args=None):
52if (probs is None) == (logits is None):
53raise ValueError(
54"Either `probs` or `logits` must be specified, but not both."
55)
56if probs is not None:
57if probs.dim() < 1:
58raise ValueError("`probs` parameter must be at least one-dimensional.")
59self.probs = probs / probs.sum(-1, keepdim=True)
60else:
61if logits.dim() < 1:
62raise ValueError("`logits` parameter must be at least one-dimensional.")
63# Normalize
64self.logits = logits - logits.logsumexp(dim=-1, keepdim=True)
65self._param = self.probs if probs is not None else self.logits
66self._num_events = self._param.size()[-1]
67batch_shape = (
68self._param.size()[:-1] if self._param.ndimension() > 1 else torch.Size()
69)
70super().__init__(batch_shape, validate_args=validate_args)
71
72def expand(self, batch_shape, _instance=None):
73new = self._get_checked_instance(Categorical, _instance)
74batch_shape = torch.Size(batch_shape)
75param_shape = batch_shape + torch.Size((self._num_events,))
76if "probs" in self.__dict__:
77new.probs = self.probs.expand(param_shape)
78new._param = new.probs
79if "logits" in self.__dict__:
80new.logits = self.logits.expand(param_shape)
81new._param = new.logits
82new._num_events = self._num_events
83super(Categorical, new).__init__(batch_shape, validate_args=False)
84new._validate_args = self._validate_args
85return new
86
87def _new(self, *args, **kwargs):
88return self._param.new(*args, **kwargs)
89
90@constraints.dependent_property(is_discrete=True, event_dim=0)
91def support(self):
92return constraints.integer_interval(0, self._num_events - 1)
93
94@lazy_property
95def logits(self):
96return probs_to_logits(self.probs)
97
98@lazy_property
99def probs(self):
100return logits_to_probs(self.logits)
101
102@property
103def param_shape(self):
104return self._param.size()
105
106@property
107def mean(self):
108return torch.full(
109self._extended_shape(),
110nan,
111dtype=self.probs.dtype,
112device=self.probs.device,
113)
114
115@property
116def mode(self):
117return self.probs.argmax(axis=-1)
118
119@property
120def variance(self):
121return torch.full(
122self._extended_shape(),
123nan,
124dtype=self.probs.dtype,
125device=self.probs.device,
126)
127
128def sample(self, sample_shape=torch.Size()):
129if not isinstance(sample_shape, torch.Size):
130sample_shape = torch.Size(sample_shape)
131probs_2d = self.probs.reshape(-1, self._num_events)
132samples_2d = torch.multinomial(probs_2d, sample_shape.numel(), True).T
133return samples_2d.reshape(self._extended_shape(sample_shape))
134
135def log_prob(self, value):
136if self._validate_args:
137self._validate_sample(value)
138value = value.long().unsqueeze(-1)
139value, log_pmf = torch.broadcast_tensors(value, self.logits)
140value = value[..., :1]
141return log_pmf.gather(-1, value).squeeze(-1)
142
143def entropy(self):
144min_real = torch.finfo(self.logits.dtype).min
145logits = torch.clamp(self.logits, min=min_real)
146p_log_p = logits * self.probs
147return -p_log_p.sum(-1)
148
149def enumerate_support(self, expand=True):
150num_events = self._num_events
151values = torch.arange(num_events, dtype=torch.long, device=self._param.device)
152values = values.view((-1,) + (1,) * len(self._batch_shape))
153if expand:
154values = values.expand((-1,) + self._batch_shape)
155return values
156