half_cauchy.py 2.3 KB

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