pareto.py 2.1 KB

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