bernoulli.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. from numbers import Number
  2. import torch
  3. from torch._six import nan
  4. from torch.distributions import constraints
  5. from torch.distributions.exp_family import ExponentialFamily
  6. from torch.distributions.utils import broadcast_all, probs_to_logits, logits_to_probs, lazy_property
  7. from torch.nn.functional import binary_cross_entropy_with_logits
  8. class Bernoulli(ExponentialFamily):
  9. r"""
  10. Creates a Bernoulli distribution parameterized by :attr:`probs`
  11. or :attr:`logits` (but not both).
  12. Samples are binary (0 or 1). They take the value `1` with probability `p`
  13. and `0` with probability `1 - p`.
  14. Example::
  15. >>> m = Bernoulli(torch.tensor([0.3]))
  16. >>> m.sample() # 30% chance 1; 70% chance 0
  17. tensor([ 0.])
  18. Args:
  19. probs (Number, Tensor): the probability of sampling `1`
  20. logits (Number, Tensor): the log-odds of sampling `1`
  21. """
  22. arg_constraints = {'probs': constraints.unit_interval,
  23. 'logits': constraints.real}
  24. support = constraints.boolean
  25. has_enumerate_support = True
  26. _mean_carrier_measure = 0
  27. def __init__(self, probs=None, logits=None, validate_args=None):
  28. if (probs is None) == (logits is None):
  29. raise ValueError("Either `probs` or `logits` must be specified, but not both.")
  30. if probs is not None:
  31. is_scalar = isinstance(probs, Number)
  32. self.probs, = broadcast_all(probs)
  33. else:
  34. is_scalar = isinstance(logits, Number)
  35. self.logits, = broadcast_all(logits)
  36. self._param = self.probs if probs is not None else self.logits
  37. if is_scalar:
  38. batch_shape = torch.Size()
  39. else:
  40. batch_shape = self._param.size()
  41. super(Bernoulli, self).__init__(batch_shape, validate_args=validate_args)
  42. def expand(self, batch_shape, _instance=None):
  43. new = self._get_checked_instance(Bernoulli, _instance)
  44. batch_shape = torch.Size(batch_shape)
  45. if 'probs' in self.__dict__:
  46. new.probs = self.probs.expand(batch_shape)
  47. new._param = new.probs
  48. if 'logits' in self.__dict__:
  49. new.logits = self.logits.expand(batch_shape)
  50. new._param = new.logits
  51. super(Bernoulli, new).__init__(batch_shape, validate_args=False)
  52. new._validate_args = self._validate_args
  53. return new
  54. def _new(self, *args, **kwargs):
  55. return self._param.new(*args, **kwargs)
  56. @property
  57. def mean(self):
  58. return self.probs
  59. @property
  60. def mode(self):
  61. mode = (self.probs >= 0.5).to(self.probs)
  62. mode[self.probs == 0.5] = nan
  63. return mode
  64. @property
  65. def variance(self):
  66. return self.probs * (1 - self.probs)
  67. @lazy_property
  68. def logits(self):
  69. return probs_to_logits(self.probs, is_binary=True)
  70. @lazy_property
  71. def probs(self):
  72. return logits_to_probs(self.logits, is_binary=True)
  73. @property
  74. def param_shape(self):
  75. return self._param.size()
  76. def sample(self, sample_shape=torch.Size()):
  77. shape = self._extended_shape(sample_shape)
  78. with torch.no_grad():
  79. return torch.bernoulli(self.probs.expand(shape))
  80. def log_prob(self, value):
  81. if self._validate_args:
  82. self._validate_sample(value)
  83. logits, value = broadcast_all(self.logits, value)
  84. return -binary_cross_entropy_with_logits(logits, value, reduction='none')
  85. def entropy(self):
  86. return binary_cross_entropy_with_logits(self.logits, self.probs, reduction='none')
  87. def enumerate_support(self, expand=True):
  88. values = torch.arange(2, dtype=self._param.dtype, device=self._param.device)
  89. values = values.view((-1,) + (1,) * len(self._batch_shape))
  90. if expand:
  91. values = values.expand((-1,) + self._batch_shape)
  92. return values
  93. @property
  94. def _natural_params(self):
  95. return (torch.log(self.probs / (1 - self.probs)), )
  96. def _log_normalizer(self, x):
  97. return torch.log(1 + torch.exp(x))