geometric.py 4.2 KB

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