half_normal.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # mypy: allow-untyped-defs
  2. import math
  3. import torch
  4. from torch import inf
  5. from torch.distributions import constraints
  6. from torch.distributions.normal import Normal
  7. from torch.distributions.transformed_distribution import TransformedDistribution
  8. from torch.distributions.transforms import AbsTransform
  9. __all__ = ["HalfNormal"]
  10. class HalfNormal(TransformedDistribution):
  11. r"""
  12. Creates a half-normal distribution parameterized by `scale` where::
  13. X ~ Normal(0, scale)
  14. Y = |X| ~ HalfNormal(scale)
  15. Example::
  16. >>> # xdoctest: +IGNORE_WANT("non-deterministic")
  17. >>> m = HalfNormal(torch.tensor([1.0]))
  18. >>> m.sample() # half-normal distributed with scale=1
  19. tensor([ 0.1046])
  20. Args:
  21. scale (float or Tensor): scale of the full Normal distribution
  22. """
  23. arg_constraints = {"scale": constraints.positive}
  24. support = constraints.nonnegative
  25. has_rsample = True
  26. def __init__(self, scale, validate_args=None):
  27. base_dist = Normal(0, scale, validate_args=False)
  28. super().__init__(base_dist, AbsTransform(), validate_args=validate_args)
  29. def expand(self, batch_shape, _instance=None):
  30. new = self._get_checked_instance(HalfNormal, _instance)
  31. return super().expand(batch_shape, _instance=new)
  32. @property
  33. def scale(self):
  34. return self.base_dist.scale
  35. @property
  36. def mean(self):
  37. return self.scale * math.sqrt(2 / math.pi)
  38. @property
  39. def mode(self):
  40. return torch.zeros_like(self.scale)
  41. @property
  42. def variance(self):
  43. return self.scale.pow(2) * (1 - 2 / math.pi)
  44. def log_prob(self, value):
  45. if self._validate_args:
  46. self._validate_sample(value)
  47. log_prob = self.base_dist.log_prob(value) + math.log(2)
  48. log_prob = torch.where(value >= 0, log_prob, -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)