categorical.py 5.9 KB

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