10 Creates a categorical distribution parameterized by either :attr:`probs` or 11 :attr:`logits` (but not both). 14 It is equivalent to the distribution that :func:`torch.multinomial` 17 Samples are integers from :math:`\{0, \ldots, K-1\}` where `K` is ``probs.size(-1)``. 19 If :attr:`probs` is 1D with length-`K`, each element is the relative 20 probability of sampling the class at that index. 22 If :attr:`probs` is 2D, it is treated as a batch of relative probability 25 .. note:: :attr:`probs` must be non-negative, finite and have a non-zero sum, 26 and it will be normalized to sum to 1. 28 See also: :func:`torch.multinomial` 32 >>> m = Categorical(torch.tensor([ 0.25, 0.25, 0.25, 0.25 ])) 33 >>> m.sample() # equal probability of 0, 1, 2, 3 37 probs (Tensor): event probabilities 38 logits (Tensor): event log probabilities 40 arg_constraints = {
'probs': constraints.simplex,
41 'logits': constraints.real}
42 has_enumerate_support =
True 44 def __init__(self, probs=None, logits=None, validate_args=None):
45 if (probs
is None) == (logits
is None):
46 raise ValueError(
"Either `probs` or `logits` must be specified, but not both.")
49 raise ValueError(
"`probs` parameter must be at least one-dimensional.")
50 self.
probs = probs / probs.sum(-1, keepdim=
True)
53 raise ValueError(
"`logits` parameter must be at least one-dimensional.")
54 self.
logits = logits - logits.logsumexp(dim=-1, keepdim=
True)
57 batch_shape = self._param.size()[:-1]
if self._param.ndimension() > 1
else torch.Size()
58 super(Categorical, self).__init__(batch_shape, validate_args=validate_args)
60 def expand(self, batch_shape, _instance=None):
62 batch_shape = torch.Size(batch_shape)
63 param_shape = batch_shape + torch.Size((self.
_num_events,))
64 if 'probs' in self.__dict__:
65 new.probs = self.probs.expand(param_shape)
66 new._param = new.probs
68 new.logits = self.logits.expand(param_shape)
69 new._param = new.logits
71 super(Categorical, new).__init__(batch_shape, validate_args=
False)
75 def _new(self, *args, **kwargs):
76 return self._param.new(*args, **kwargs)
78 @constraints.dependent_property
80 return constraints.integer_interval(0, self.
_num_events - 1)
84 return probs_to_logits(self.
probs)
88 return logits_to_probs(self.
logits)
91 def param_shape(self):
92 return self._param.size()
102 def sample(self, sample_shape=torch.Size()):
104 param_shape = sample_shape + torch.Size((self.
_num_events,))
105 probs = self.probs.expand(param_shape)
106 if self.probs.dim() == 1
or self.probs.size(0) == 1:
109 probs_2d = probs.contiguous().view(-1, self.
_num_events)
110 sample_2d = torch.multinomial(probs_2d, 1,
True)
111 return sample_2d.contiguous().view(sample_shape)
113 def log_prob(self, value):
116 value = value.long().unsqueeze(-1)
117 value, log_pmf = torch.broadcast_tensors(value, self.
logits)
118 value = value[..., :1]
119 return log_pmf.gather(-1, value).squeeze(-1)
123 return -p_log_p.sum(-1)
125 def enumerate_support(self, expand=True):
127 values = torch.arange(num_events, dtype=torch.long, device=self._param.device)
128 values = values.view((-1,) + (1,) * len(self.
_batch_shape))
def _get_checked_instance(self, cls, _instance=None)
def _extended_shape(self, sample_shape=torch.Size())
def _validate_sample(self, value)