studentT.py 3.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import math
  2. import torch
  3. from torch import inf, nan
  4. from torch.distributions import Chi2, constraints
  5. from torch.distributions.distribution import Distribution
  6. from torch.distributions.utils import _standard_normal, broadcast_all
  7. __all__ = ['StudentT']
  8. class StudentT(Distribution):
  9. r"""
  10. Creates a Student's t-distribution parameterized by degree of
  11. freedom :attr:`df`, mean :attr:`loc` and scale :attr:`scale`.
  12. Example::
  13. >>> # xdoctest: +IGNORE_WANT("non-deterinistic")
  14. >>> m = StudentT(torch.tensor([2.0]))
  15. >>> m.sample() # Student's t-distributed with degrees of freedom=2
  16. tensor([ 0.1046])
  17. Args:
  18. df (float or Tensor): degrees of freedom
  19. loc (float or Tensor): mean of the distribution
  20. scale (float or Tensor): scale of the distribution
  21. """
  22. arg_constraints = {'df': constraints.positive, 'loc': constraints.real, 'scale': constraints.positive}
  23. support = constraints.real
  24. has_rsample = True
  25. @property
  26. def mean(self):
  27. m = self.loc.clone(memory_format=torch.contiguous_format)
  28. m[self.df <= 1] = nan
  29. return m
  30. @property
  31. def mode(self):
  32. return self.loc
  33. @property
  34. def variance(self):
  35. m = self.df.clone(memory_format=torch.contiguous_format)
  36. m[self.df > 2] = self.scale[self.df > 2].pow(2) * self.df[self.df > 2] / (self.df[self.df > 2] - 2)
  37. m[(self.df <= 2) & (self.df > 1)] = inf
  38. m[self.df <= 1] = nan
  39. return m
  40. def __init__(self, df, loc=0., scale=1., validate_args=None):
  41. self.df, self.loc, self.scale = broadcast_all(df, loc, scale)
  42. self._chi2 = Chi2(self.df)
  43. batch_shape = self.df.size()
  44. super().__init__(batch_shape, validate_args=validate_args)
  45. def expand(self, batch_shape, _instance=None):
  46. new = self._get_checked_instance(StudentT, _instance)
  47. batch_shape = torch.Size(batch_shape)
  48. new.df = self.df.expand(batch_shape)
  49. new.loc = self.loc.expand(batch_shape)
  50. new.scale = self.scale.expand(batch_shape)
  51. new._chi2 = self._chi2.expand(batch_shape)
  52. super(StudentT, new).__init__(batch_shape, validate_args=False)
  53. new._validate_args = self._validate_args
  54. return new
  55. def rsample(self, sample_shape=torch.Size()):
  56. # NOTE: This does not agree with scipy implementation as much as other distributions.
  57. # (see https://github.com/fritzo/notebooks/blob/master/debug-student-t.ipynb). Using DoubleTensor
  58. # parameters seems to help.
  59. # X ~ Normal(0, 1)
  60. # Z ~ Chi2(df)
  61. # Y = X / sqrt(Z / df) ~ StudentT(df)
  62. shape = self._extended_shape(sample_shape)
  63. X = _standard_normal(shape, dtype=self.df.dtype, device=self.df.device)
  64. Z = self._chi2.rsample(sample_shape)
  65. Y = X * torch.rsqrt(Z / self.df)
  66. return self.loc + self.scale * Y
  67. def log_prob(self, value):
  68. if self._validate_args:
  69. self._validate_sample(value)
  70. y = (value - self.loc) / self.scale
  71. Z = (self.scale.log() +
  72. 0.5 * self.df.log() +
  73. 0.5 * math.log(math.pi) +
  74. torch.lgamma(0.5 * self.df) -
  75. torch.lgamma(0.5 * (self.df + 1.)))
  76. return -0.5 * (self.df + 1.) * torch.log1p(y**2. / self.df) - Z
  77. def entropy(self):
  78. lbeta = torch.lgamma(0.5 * self.df) + math.lgamma(0.5) - torch.lgamma(0.5 * (self.df + 1))
  79. return (self.scale.log() +
  80. 0.5 * (self.df + 1) *
  81. (torch.digamma(0.5 * (self.df + 1)) - torch.digamma(0.5 * self.df)) +
  82. 0.5 * self.df.log() + lbeta)