inverse_gamma.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. # mypy: allow-untyped-defs
  2. import torch
  3. from torch import Tensor
  4. from torch.distributions import constraints
  5. from torch.distributions.gamma import Gamma
  6. from torch.distributions.transformed_distribution import TransformedDistribution
  7. from torch.distributions.transforms import PowerTransform
  8. __all__ = ["InverseGamma"]
  9. class InverseGamma(TransformedDistribution):
  10. r"""
  11. Creates an inverse gamma distribution parameterized by :attr:`concentration` and :attr:`rate`
  12. where::
  13. X ~ Gamma(concentration, rate)
  14. Y = 1 / X ~ InverseGamma(concentration, rate)
  15. Example::
  16. >>> # xdoctest: +IGNORE_WANT("non-deterinistic")
  17. >>> m = InverseGamma(torch.tensor([2.0]), torch.tensor([3.0]))
  18. >>> m.sample()
  19. tensor([ 1.2953])
  20. Args:
  21. concentration (float or Tensor): shape parameter of the distribution
  22. (often referred to as alpha)
  23. rate (float or Tensor): rate = 1 / scale of the distribution
  24. (often referred to as beta)
  25. """
  26. arg_constraints = {
  27. "concentration": constraints.positive,
  28. "rate": constraints.positive,
  29. }
  30. # pyrefly: ignore [bad-override]
  31. support = constraints.positive
  32. has_rsample = True
  33. # pyrefly: ignore [bad-override]
  34. base_dist: Gamma
  35. def __init__(
  36. self,
  37. concentration: Tensor | float,
  38. rate: Tensor | float,
  39. validate_args: bool | None = None,
  40. ) -> None:
  41. base_dist = Gamma(concentration, rate, validate_args=validate_args)
  42. neg_one = -base_dist.rate.new_ones(())
  43. super().__init__(
  44. base_dist, PowerTransform(neg_one), validate_args=validate_args
  45. )
  46. def expand(self, batch_shape, _instance=None):
  47. new = self._get_checked_instance(InverseGamma, _instance)
  48. return super().expand(batch_shape, _instance=new)
  49. @property
  50. def concentration(self) -> Tensor:
  51. return self.base_dist.concentration
  52. @property
  53. def rate(self) -> Tensor:
  54. return self.base_dist.rate
  55. @property
  56. def mean(self) -> Tensor:
  57. result = self.rate / (self.concentration - 1)
  58. return torch.where(self.concentration > 1, result, torch.inf)
  59. @property
  60. def mode(self) -> Tensor:
  61. return self.rate / (self.concentration + 1)
  62. @property
  63. def variance(self) -> Tensor:
  64. result = self.rate.square() / (
  65. (self.concentration - 1).square() * (self.concentration - 2)
  66. )
  67. return torch.where(self.concentration > 2, result, torch.inf)
  68. def entropy(self):
  69. return (
  70. self.concentration
  71. + self.rate.log()
  72. + self.concentration.lgamma()
  73. - (1 + self.concentration) * self.concentration.digamma()
  74. )