half_normal.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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.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. # pyrefly: ignore [bad-override]
  25. support = constraints.nonnegative
  26. has_rsample = True
  27. # pyrefly: ignore [bad-override]
  28. base_dist: Normal
  29. def __init__(
  30. self,
  31. scale: Tensor | float,
  32. validate_args: bool | None = None,
  33. ) -> None:
  34. base_dist = Normal(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(HalfNormal, _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 self.scale * math.sqrt(2 / math.pi)
  45. @property
  46. def mode(self) -> Tensor:
  47. return torch.zeros_like(self.scale)
  48. @property
  49. def variance(self) -> Tensor:
  50. return self.scale.pow(2) * (1 - 2 / math.pi)
  51. def log_prob(self, value):
  52. if self._validate_args:
  53. self._validate_sample(value)
  54. log_prob = self.base_dist.log_prob(value) + math.log(2)
  55. log_prob = torch.where(value >= 0, log_prob, -inf)
  56. return log_prob
  57. def cdf(self, value):
  58. if self._validate_args:
  59. self._validate_sample(value)
  60. return 2 * self.base_dist.cdf(value) - 1
  61. def icdf(self, prob):
  62. return self.base_dist.icdf((prob + 1) / 2)
  63. def entropy(self):
  64. return self.base_dist.entropy() - math.log(2)