pareto.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. from typing import Optional
  2. from torch import Tensor
  3. from torch.distributions import constraints
  4. from torch.distributions.exponential import Exponential
  5. from torch.distributions.transformed_distribution import TransformedDistribution
  6. from torch.distributions.transforms import AffineTransform, ExpTransform
  7. from torch.distributions.utils import broadcast_all
  8. from torch.types import _size
  9. __all__ = ["Pareto"]
  10. class Pareto(TransformedDistribution):
  11. r"""
  12. Samples from a Pareto Type 1 distribution.
  13. Example::
  14. >>> # xdoctest: +IGNORE_WANT("non-deterministic")
  15. >>> m = Pareto(torch.tensor([1.0]), torch.tensor([1.0]))
  16. >>> m.sample() # sample from a Pareto distribution with scale=1 and alpha=1
  17. tensor([ 1.5623])
  18. Args:
  19. scale (float or Tensor): Scale parameter of the distribution
  20. alpha (float or Tensor): Shape parameter of the distribution
  21. """
  22. arg_constraints = {"alpha": constraints.positive, "scale": constraints.positive}
  23. def __init__(
  24. self,
  25. scale: Tensor | float,
  26. alpha: Tensor | float,
  27. validate_args: bool | None = None,
  28. ) -> None:
  29. self.scale, self.alpha = broadcast_all(scale, alpha)
  30. base_dist = Exponential(self.alpha, validate_args=validate_args)
  31. transforms = [ExpTransform(), AffineTransform(loc=0, scale=self.scale)]
  32. # pyrefly: ignore [bad-argument-type]
  33. super().__init__(base_dist, transforms, validate_args=validate_args)
  34. def expand(
  35. self, batch_shape: _size, _instance: Optional["Pareto"] = None
  36. ) -> "Pareto":
  37. new = self._get_checked_instance(Pareto, _instance)
  38. new.scale = self.scale.expand(batch_shape)
  39. new.alpha = self.alpha.expand(batch_shape)
  40. return super().expand(batch_shape, _instance=new)
  41. @property
  42. def mean(self) -> Tensor:
  43. # mean is inf for alpha <= 1
  44. a = self.alpha.clamp(min=1)
  45. return a * self.scale / (a - 1)
  46. @property
  47. def mode(self) -> Tensor:
  48. return self.scale
  49. @property
  50. def variance(self) -> Tensor:
  51. # var is inf for alpha <= 2
  52. a = self.alpha.clamp(min=2)
  53. return self.scale.pow(2) * a / ((a - 1).pow(2) * (a - 2))
  54. @constraints.dependent_property(is_discrete=False, event_dim=0)
  55. def support(self) -> constraints.Constraint:
  56. return constraints.greater_than_eq(self.scale)
  57. def entropy(self) -> Tensor:
  58. return (self.scale / self.alpha).log() + (1 + self.alpha.reciprocal())