exponential.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. from numbers import Number
  2. import torch
  3. from torch.distributions import constraints
  4. from torch.distributions.exp_family import ExponentialFamily
  5. from torch.distributions.utils import broadcast_all
  6. class Exponential(ExponentialFamily):
  7. r"""
  8. Creates a Exponential distribution parameterized by :attr:`rate`.
  9. Example::
  10. >>> m = Exponential(torch.tensor([1.0]))
  11. >>> m.sample() # Exponential distributed with rate=1
  12. tensor([ 0.1046])
  13. Args:
  14. rate (float or Tensor): rate = 1 / scale of the distribution
  15. """
  16. arg_constraints = {'rate': constraints.positive}
  17. support = constraints.nonnegative
  18. has_rsample = True
  19. _mean_carrier_measure = 0
  20. @property
  21. def mean(self):
  22. return self.rate.reciprocal()
  23. @property
  24. def mode(self):
  25. return torch.zeros_like(self.rate)
  26. @property
  27. def stddev(self):
  28. return self.rate.reciprocal()
  29. @property
  30. def variance(self):
  31. return self.rate.pow(-2)
  32. def __init__(self, rate, validate_args=None):
  33. self.rate, = broadcast_all(rate)
  34. batch_shape = torch.Size() if isinstance(rate, Number) else self.rate.size()
  35. super(Exponential, self).__init__(batch_shape, validate_args=validate_args)
  36. def expand(self, batch_shape, _instance=None):
  37. new = self._get_checked_instance(Exponential, _instance)
  38. batch_shape = torch.Size(batch_shape)
  39. new.rate = self.rate.expand(batch_shape)
  40. super(Exponential, new).__init__(batch_shape, validate_args=False)
  41. new._validate_args = self._validate_args
  42. return new
  43. def rsample(self, sample_shape=torch.Size()):
  44. shape = self._extended_shape(sample_shape)
  45. if torch._C._get_tracing_state():
  46. # [JIT WORKAROUND] lack of support for ._exponential()
  47. u = torch.rand(shape, dtype=self.rate.dtype, device=self.rate.device)
  48. return -(-u).log1p() / self.rate
  49. return self.rate.new(shape).exponential_() / self.rate
  50. def log_prob(self, value):
  51. if self._validate_args:
  52. self._validate_sample(value)
  53. return self.rate.log() - self.rate * value
  54. def cdf(self, value):
  55. if self._validate_args:
  56. self._validate_sample(value)
  57. return 1 - torch.exp(-self.rate * value)
  58. def icdf(self, value):
  59. return -torch.log(1 - value) / self.rate
  60. def entropy(self):
  61. return 1.0 - torch.log(self.rate)
  62. @property
  63. def _natural_params(self):
  64. return (-self.rate, )
  65. def _log_normalizer(self, x):
  66. return -torch.log(-x)