categorical.py 5.4 KB

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