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