geometric.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. from numbers import Number
  2. import torch
  3. from torch.distributions import constraints
  4. from torch.distributions.distribution import Distribution
  5. from torch.distributions.utils import broadcast_all, probs_to_logits, logits_to_probs, lazy_property
  6. from torch.nn.functional import binary_cross_entropy_with_logits
  7. __all__ = ['Geometric']
  8. class Geometric(Distribution):
  9. r"""
  10. Creates a Geometric distribution parameterized by :attr:`probs`,
  11. where :attr:`probs` is the probability of success of Bernoulli trials.
  12. It represents the probability that in :math:`k + 1` Bernoulli trials, the
  13. first :math:`k` trials failed, before seeing a success.
  14. Samples are non-negative integers [0, :math:`\inf`).
  15. Example::
  16. >>> # xdoctest: +IGNORE_WANT("non-deterinistic")
  17. >>> m = Geometric(torch.tensor([0.3]))
  18. >>> m.sample() # underlying Bernoulli has 30% chance 1; 70% chance 0
  19. tensor([ 2.])
  20. Args:
  21. probs (Number, Tensor): the probability of sampling `1`. Must be in range (0, 1]
  22. logits (Number, Tensor): the log-odds of sampling `1`.
  23. """
  24. arg_constraints = {'probs': constraints.unit_interval,
  25. 'logits': constraints.real}
  26. support = constraints.nonnegative_integer
  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. self.probs, = broadcast_all(probs)
  32. else:
  33. self.logits, = broadcast_all(logits)
  34. probs_or_logits = probs if probs is not None else logits
  35. if isinstance(probs_or_logits, Number):
  36. batch_shape = torch.Size()
  37. else:
  38. batch_shape = probs_or_logits.size()
  39. super().__init__(batch_shape, validate_args=validate_args)
  40. if self._validate_args and probs is not None:
  41. # Add an extra check beyond unit_interval
  42. value = self.probs
  43. valid = value > 0
  44. if not valid.all():
  45. invalid_value = value.data[~valid]
  46. raise ValueError(
  47. "Expected parameter probs "
  48. f"({type(value).__name__} of shape {tuple(value.shape)}) "
  49. f"of distribution {repr(self)} "
  50. f"to be positive but found invalid values:\n{invalid_value}"
  51. )
  52. def expand(self, batch_shape, _instance=None):
  53. new = self._get_checked_instance(Geometric, _instance)
  54. batch_shape = torch.Size(batch_shape)
  55. if 'probs' in self.__dict__:
  56. new.probs = self.probs.expand(batch_shape)
  57. if 'logits' in self.__dict__:
  58. new.logits = self.logits.expand(batch_shape)
  59. super(Geometric, new).__init__(batch_shape, validate_args=False)
  60. new._validate_args = self._validate_args
  61. return new
  62. @property
  63. def mean(self):
  64. return 1. / self.probs - 1.
  65. @property
  66. def mode(self):
  67. return torch.zeros_like(self.probs)
  68. @property
  69. def variance(self):
  70. return (1. / self.probs - 1.) / self.probs
  71. @lazy_property
  72. def logits(self):
  73. return probs_to_logits(self.probs, is_binary=True)
  74. @lazy_property
  75. def probs(self):
  76. return logits_to_probs(self.logits, is_binary=True)
  77. def sample(self, sample_shape=torch.Size()):
  78. shape = self._extended_shape(sample_shape)
  79. tiny = torch.finfo(self.probs.dtype).tiny
  80. with torch.no_grad():
  81. if torch._C._get_tracing_state():
  82. # [JIT WORKAROUND] lack of support for .uniform_()
  83. u = torch.rand(shape, dtype=self.probs.dtype, device=self.probs.device)
  84. u = u.clamp(min=tiny)
  85. else:
  86. u = self.probs.new(shape).uniform_(tiny, 1)
  87. return (u.log() / (-self.probs).log1p()).floor()
  88. def log_prob(self, value):
  89. if self._validate_args:
  90. self._validate_sample(value)
  91. value, probs = broadcast_all(value, self.probs)
  92. probs = probs.clone(memory_format=torch.contiguous_format)
  93. probs[(probs == 1) & (value == 0)] = 0
  94. return value * (-probs).log1p() + self.probs.log()
  95. def entropy(self):
  96. return binary_cross_entropy_with_logits(self.logits, self.probs, reduction='none') / self.probs