cauchy.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import math
  2. from torch._six import inf, nan
  3. from numbers import Number
  4. import torch
  5. from torch.distributions import constraints
  6. from torch.distributions.distribution import Distribution
  7. from torch.distributions.utils import broadcast_all
  8. class Cauchy(Distribution):
  9. r"""
  10. Samples from a Cauchy (Lorentz) distribution. The distribution of the ratio of
  11. independent normally distributed random variables with means `0` follows a
  12. Cauchy distribution.
  13. Example::
  14. >>> m = Cauchy(torch.tensor([0.0]), torch.tensor([1.0]))
  15. >>> m.sample() # sample from a Cauchy distribution with loc=0 and scale=1
  16. tensor([ 2.3214])
  17. Args:
  18. loc (float or Tensor): mode or median of the distribution.
  19. scale (float or Tensor): half width at half maximum.
  20. """
  21. arg_constraints = {'loc': constraints.real, 'scale': constraints.positive}
  22. support = constraints.real
  23. has_rsample = True
  24. def __init__(self, loc, scale, validate_args=None):
  25. self.loc, self.scale = broadcast_all(loc, scale)
  26. if isinstance(loc, Number) and isinstance(scale, Number):
  27. batch_shape = torch.Size()
  28. else:
  29. batch_shape = self.loc.size()
  30. super(Cauchy, self).__init__(batch_shape, validate_args=validate_args)
  31. def expand(self, batch_shape, _instance=None):
  32. new = self._get_checked_instance(Cauchy, _instance)
  33. batch_shape = torch.Size(batch_shape)
  34. new.loc = self.loc.expand(batch_shape)
  35. new.scale = self.scale.expand(batch_shape)
  36. super(Cauchy, new).__init__(batch_shape, validate_args=False)
  37. new._validate_args = self._validate_args
  38. return new
  39. @property
  40. def mean(self):
  41. return torch.full(self._extended_shape(), nan, dtype=self.loc.dtype, device=self.loc.device)
  42. @property
  43. def mode(self):
  44. return self.loc
  45. @property
  46. def variance(self):
  47. return torch.full(self._extended_shape(), inf, dtype=self.loc.dtype, device=self.loc.device)
  48. def rsample(self, sample_shape=torch.Size()):
  49. shape = self._extended_shape(sample_shape)
  50. eps = self.loc.new(shape).cauchy_()
  51. return self.loc + eps * self.scale
  52. def log_prob(self, value):
  53. if self._validate_args:
  54. self._validate_sample(value)
  55. return -math.log(math.pi) - self.scale.log() - (1 + ((value - self.loc) / self.scale)**2).log()
  56. def cdf(self, value):
  57. if self._validate_args:
  58. self._validate_sample(value)
  59. return torch.atan((value - self.loc) / self.scale) / math.pi + 0.5
  60. def icdf(self, value):
  61. return torch.tan(math.pi * (value - 0.5)) * self.scale + self.loc
  62. def entropy(self):
  63. return math.log(4 * math.pi) + self.scale.log()