chi2.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # mypy: allow-untyped-defs
  2. from torch import Tensor
  3. from torch.distributions import constraints
  4. from torch.distributions.gamma import Gamma
  5. __all__ = ["Chi2"]
  6. class Chi2(Gamma):
  7. r"""
  8. Creates a Chi-squared distribution parameterized by shape parameter :attr:`df`.
  9. This is exactly equivalent to ``Gamma(alpha=0.5*df, beta=0.5)``
  10. Example::
  11. >>> # xdoctest: +IGNORE_WANT("non-deterministic")
  12. >>> m = Chi2(torch.tensor([1.0]))
  13. >>> m.sample() # Chi2 distributed with shape df=1
  14. tensor([ 0.1046])
  15. Args:
  16. df (float or Tensor): shape parameter of the distribution
  17. """
  18. arg_constraints = {"df": constraints.positive}
  19. def __init__(
  20. self,
  21. df: Tensor | float,
  22. validate_args: bool | None = None,
  23. ) -> None:
  24. super().__init__(0.5 * df, 0.5, validate_args=validate_args)
  25. def expand(self, batch_shape, _instance=None):
  26. new = self._get_checked_instance(Chi2, _instance)
  27. return super().expand(batch_shape, new)
  28. @property
  29. def df(self) -> Tensor:
  30. return self.concentration * 2