pareto.py 2.1 KB

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