gamma.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. # mypy: allow-untyped-defs
  2. import torch
  3. from torch import Tensor
  4. from torch.distributions import constraints
  5. from torch.distributions.exp_family import ExponentialFamily
  6. from torch.distributions.utils import broadcast_all
  7. from torch.types import _Number, _size
  8. __all__ = ["Gamma"]
  9. def _standard_gamma(concentration):
  10. return torch._standard_gamma(concentration)
  11. class Gamma(ExponentialFamily):
  12. r"""
  13. Creates a Gamma distribution parameterized by shape :attr:`concentration` and :attr:`rate`.
  14. Example::
  15. >>> # xdoctest: +IGNORE_WANT("non-deterministic")
  16. >>> m = Gamma(torch.tensor([1.0]), torch.tensor([1.0]))
  17. >>> m.sample() # Gamma distributed with concentration=1 and rate=1
  18. tensor([ 0.1046])
  19. Args:
  20. concentration (float or Tensor): shape parameter of the distribution
  21. (often referred to as alpha)
  22. rate (float or Tensor): rate parameter of the distribution
  23. (often referred to as beta), rate = 1 / scale
  24. """
  25. # pyrefly: ignore [bad-override]
  26. arg_constraints = {
  27. "concentration": constraints.positive,
  28. "rate": constraints.positive,
  29. }
  30. support = constraints.nonnegative
  31. has_rsample = True
  32. _mean_carrier_measure = 0
  33. @property
  34. def mean(self) -> Tensor:
  35. return self.concentration / self.rate
  36. @property
  37. def mode(self) -> Tensor:
  38. return ((self.concentration - 1) / self.rate).clamp(min=0)
  39. @property
  40. def variance(self) -> Tensor:
  41. return self.concentration / self.rate.pow(2)
  42. def __init__(
  43. self,
  44. concentration: Tensor | float,
  45. rate: Tensor | float,
  46. validate_args: bool | None = None,
  47. ) -> None:
  48. self.concentration, self.rate = broadcast_all(concentration, rate)
  49. if isinstance(concentration, _Number) and isinstance(rate, _Number):
  50. batch_shape = torch.Size()
  51. else:
  52. batch_shape = self.concentration.size()
  53. super().__init__(batch_shape, validate_args=validate_args)
  54. def expand(self, batch_shape, _instance=None):
  55. new = self._get_checked_instance(Gamma, _instance)
  56. batch_shape = torch.Size(batch_shape)
  57. new.concentration = self.concentration.expand(batch_shape)
  58. new.rate = self.rate.expand(batch_shape)
  59. super(Gamma, new).__init__(batch_shape, validate_args=False)
  60. new._validate_args = self._validate_args
  61. return new
  62. def rsample(self, sample_shape: _size = torch.Size()) -> Tensor:
  63. shape = self._extended_shape(sample_shape)
  64. value = _standard_gamma(self.concentration.expand(shape)) / self.rate.expand(
  65. shape
  66. )
  67. value.detach().clamp_(
  68. min=torch.finfo(value.dtype).tiny
  69. ) # do not record in autograd graph
  70. return value
  71. def log_prob(self, value):
  72. value = torch.as_tensor(value, dtype=self.rate.dtype, device=self.rate.device)
  73. if self._validate_args:
  74. self._validate_sample(value)
  75. return (
  76. torch.xlogy(self.concentration, self.rate)
  77. + torch.xlogy(self.concentration - 1, value)
  78. - self.rate * value
  79. - torch.lgamma(self.concentration)
  80. )
  81. def entropy(self):
  82. return (
  83. self.concentration
  84. - torch.log(self.rate)
  85. + torch.lgamma(self.concentration)
  86. + (1.0 - self.concentration) * torch.digamma(self.concentration)
  87. )
  88. @property
  89. def _natural_params(self) -> tuple[Tensor, Tensor]:
  90. return (self.concentration - 1, -self.rate)
  91. # pyrefly: ignore [bad-override]
  92. def _log_normalizer(self, x, y):
  93. return torch.lgamma(x + 1) + (x + 1) * torch.log(-y.reciprocal())
  94. def cdf(self, value):
  95. if self._validate_args:
  96. self._validate_sample(value)
  97. return torch.special.gammainc(self.concentration, self.rate * value)