half_cauchy.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. # mypy: allow-untyped-defs
  2. import math
  3. import torch
  4. from torch import inf, Tensor
  5. from torch.distributions import constraints
  6. from torch.distributions.cauchy import Cauchy
  7. from torch.distributions.transformed_distribution import TransformedDistribution
  8. from torch.distributions.transforms import AbsTransform
  9. __all__ = ["HalfCauchy"]
  10. class HalfCauchy(TransformedDistribution):
  11. r"""
  12. Creates a half-Cauchy distribution parameterized by `scale` where::
  13. X ~ Cauchy(0, scale)
  14. Y = |X| ~ HalfCauchy(scale)
  15. Example::
  16. >>> # xdoctest: +IGNORE_WANT("non-deterministic")
  17. >>> m = HalfCauchy(torch.tensor([1.0]))
  18. >>> m.sample() # half-cauchy distributed with scale=1
  19. tensor([ 2.3214])
  20. Args:
  21. scale (float or Tensor): scale of the full Cauchy distribution
  22. """
  23. arg_constraints = {"scale": constraints.positive}
  24. # pyrefly: ignore [bad-override]
  25. support = constraints.nonnegative
  26. has_rsample = True
  27. # pyrefly: ignore [bad-override]
  28. base_dist: Cauchy
  29. def __init__(
  30. self,
  31. scale: Tensor | float,
  32. validate_args: bool | None = None,
  33. ) -> None:
  34. base_dist = Cauchy(0, scale, validate_args=False)
  35. super().__init__(base_dist, AbsTransform(), validate_args=validate_args)
  36. def expand(self, batch_shape, _instance=None):
  37. new = self._get_checked_instance(HalfCauchy, _instance)
  38. return super().expand(batch_shape, _instance=new)
  39. @property
  40. def scale(self) -> Tensor:
  41. return self.base_dist.scale
  42. @property
  43. def mean(self) -> Tensor:
  44. return torch.full(
  45. self._extended_shape(),
  46. math.inf,
  47. dtype=self.scale.dtype,
  48. device=self.scale.device,
  49. )
  50. @property
  51. def mode(self) -> Tensor:
  52. return torch.zeros_like(self.scale)
  53. @property
  54. def variance(self) -> Tensor:
  55. return self.base_dist.variance
  56. def log_prob(self, value):
  57. if self._validate_args:
  58. self._validate_sample(value)
  59. value = torch.as_tensor(
  60. value, dtype=self.base_dist.scale.dtype, device=self.base_dist.scale.device
  61. )
  62. log_prob = self.base_dist.log_prob(value) + math.log(2)
  63. log_prob = torch.where(value >= 0, log_prob, -inf)
  64. return log_prob
  65. def cdf(self, value):
  66. if self._validate_args:
  67. self._validate_sample(value)
  68. return 2 * self.base_dist.cdf(value) - 1
  69. def icdf(self, prob):
  70. return self.base_dist.icdf((prob + 1) / 2)
  71. def entropy(self):
  72. return self.base_dist.entropy() - math.log(2)