half_cauchy.py 2.3 KB

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