torch.distributions.normal 的源代码
import math
from numbers import Number, Real
import torch
from torch.distributions import constraints
from torch.distributions.exp_family import ExponentialFamily
from torch.distributions.utils import _standard_normal, broadcast_all
__all__ = ["Normal"]
[docs]class Normal(ExponentialFamily):
r"""
创建一个正态(也称为高斯)分布,由
:attr:`loc` 和 :attr:`scale` 参数化。
示例::
>>> # xdoctest: +IGNORE_WANT("non-deterministic")
>>> m = Normal(torch.tensor([0.0]), torch.tensor([1.0]))
>>> m.sample() # 正态分布,loc=0,scale=1
tensor([ 0.1046])
参数:
loc (float 或 Tensor): 分布的均值(通常称为 mu)
scale (float 或 Tensor): 分布的标准差
(通常称为 sigma)
"""
arg_constraints = {"loc": constraints.real, "scale": constraints.positive}
support = constraints.real
has_rsample = True
_mean_carrier_measure = 0
@property
def mean(self):
return self.loc
@property
def mode(self):
return self.loc
@property
def stddev(self):
return self.scale
@property
def variance(self):
return self.stddev.pow(2)
def __init__(self, loc, scale, validate_args=None):
self.loc, self.scale = broadcast_all(loc, scale)
if isinstance(loc, Number) and isinstance(scale, Number):
batch_shape = torch.Size()
else:
batch_shape = self.loc.size()
super().__init__(batch_shape, validate_args=validate_args)
[docs] def expand(self, batch_shape, _instance=None):
new = self._get_checked_instance(Normal, _instance)
batch_shape = torch.Size(batch_shape)
new.loc = self.loc.expand(batch_shape)
new.scale = self.scale.expand(batch_shape)
super(Normal, new).__init__(batch_shape, validate_args=False)
new._validate_args = self._validate_args
return new
[docs] def sample(self, sample_shape=torch.Size()):
shape = self._extended_shape(sample_shape)
with torch.no_grad():
return torch.normal(self.loc.expand(shape), self.scale.expand(shape))
[docs] def rsample(self, sample_shape=torch.Size()):
shape = self._extended_shape(sample_shape)
eps = _standard_normal(shape, dtype=self.loc.dtype, device=self.loc.device)
return self.loc + eps * self.scale
[docs] def log_prob(self, value):
if self._validate_args:
self._validate_sample(value)
# 计算方差
var = self.scale**2
log_scale = (
math.log(self.scale) if</