chi2.py 1.1 KB

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