Shortcuts

torch.distributions.studentT 的源代码

import math

import torch
from torch import inf, nan
from torch.distributions import Chi2, constraints
from torch.distributions.distribution import Distribution
from torch.distributions.utils import _standard_normal, broadcast_all

__all__ = ["StudentT"]


[docs]class StudentT(Distribution): r""" 创建一个由自由度 :attr:`df`、均值 :attr:`loc` 和尺度 :attr:`scale` 参数化的学生 t 分布。 示例:: >>> # xdoctest: +IGNORE_WANT("非确定性") >>> m = StudentT(torch.tensor([2.0])) >>> m.sample() # 自由度为 2 的学生 t 分布 tensor([ 0.1046]) 参数: df (float 或 Tensor): 自由度 loc (float 或 Tensor): 分布的均值 scale (float 或 Tensor): 分布的尺度 """ arg_constraints = { "df": constraints.positive, "loc": constraints.real, "scale": constraints.positive, } support = constraints.real has_rsample = True @property def mean(self): m = self.loc.clone(memory_format=torch.contiguous_format) m[self.df <= 1] = nan return m @property def mode(self): return self.loc @property def variance(self): m = self.df.clone(memory_format=torch.contiguous_format) m[self.df > 2] = ( self.scale[self.df > 2].pow(2) * self.df[self.df > 2] / (self.df[self.df > 2] - 2) ) m[(self.df <= 2) & (self.df > 1)] = inf m[self.df <= 1] = nan return m def __init__(self, df, loc=0.0, scale=1.0, validate_args=None): self.df, self.loc, self.scale = broadcast_all(df, loc, scale) self._chi2 = Chi2(self.df) batch_shape = self.df.size() super().__init__(batch_shape, validate_args=validate_args)
[docs] def expand(self, batch_shape, _instance=None): new = self._get_checked_instance(StudentT, _instance) batch_shape = torch.Size(batch_shape) new.df = self.df.expand(batch_shape) new.loc = self.loc.expand(batch_shape) new.scale = self.scale.expand(batch_shape) new._chi2 = self._chi2.expand(batch_shape) super(StudentT, new).__init__(batch_shape, validate_args=False) new._validate_args = self._validate_args return new
[docs] def rsample(self, sample_shape=torch.Size()): # 注意:这与 scipy 实现不完全一致。 # (参见 https://github.com/fritzo/notebooks/blob/master/debug-student-t.ipynb)。使用 DoubleTensor # 参数似乎
优云智算