源代码 for torch.distributions.uniform
# mypy: 允许未类型化定义
导入
火炬
from 火炬
导入
纳尼,
张量
from torch.distributions 导入
约束
from torch.distributions.distribution 导入
分布
from torch.distributions.utils 导入
广播全部
from torch.types 导入
数,
_大小
全部 = [
统一]
[文档]
类
均匀分布(
分发):
r""
生成半开区间的均匀分布随机样本
[低, 高)
示例::
>>> m = Uniform(torch.tensor([0.0]), torch.tensor([5.0]))
>>> m.sample() # 均匀分布在 [0.0, 5.0) 范围内
>>> # xdoctest: +SKIP
tensor([ 2.3418])
参数:
low (float 或 Tensor): 下限范围(包含)。
高(浮点数或张量):上界(不包括)。
""
# TODO 允许(loc,scale)参数化以允许独立约束。
约束参数 = {
低:
约束.
依赖的(
是否离散=
错误,
事件维度=0),
高:
约束.
依赖的(
是否离散=
错误,
事件维度=0),
}
has_rsample = 真实
@property
def 均值(self)
翻译
张量:
返回 (self.
高 + self.
低) / 2
@property
def 模式(self)
翻译
张量:
返回
纳尼 * self.
高
@property
def 标准差(self)
翻译
张量:
返回 (self.
高 - self.
低) / 12**0.5
@property
def 方差(self)
翻译
张量:
返回 (self.
高 - self.
低).pow(2) / 12
def __init__(self, 低,
高,
验证参数=
无):
self.低, self.
高 =
广播全部(
低,
高)
如果 isinstance(
低,
数)
和 isinstance(
高,
数):
批量形状 =
火炬.
尺寸()
else:
批量形状 = self.
低.
尺寸()
超级().__init__(
批量形状,
验证参数=
验证参数)
如果 self.
验证参数
和
不是
火炬.lt(self.
低, self.
高).
所有():
提升 ValueError(
"当 low>= high 时,均匀未定义")
[文档] def expand(self, batch_shape, _instance=None):
new = self._get_checked_instance(Uniform, _instance)
batch_shape = torch.Size(batch_shape)
new.low = self.low.expand(batch_shape)
new.high = self.high.expand(batch_shape)
super(Uniform, new).__init__(batch_shape, validate_args=False)
new._validate_args = self._validate_args
return new
@constraints.依赖属性(
是否离散=
错误,
事件维度=0)
def 支持(self):
返回
约束.
区间(self.
低, self.
高)
[文档] def rsample(self, sample_shape: _size = torch.Size()) -> Tensor:
shape = self._extended_shape(sample_shape)
rand = torch.rand(shape, dtype=self.low.dtype, device=self.low.device)
return self.low + rand * (self.high - self.low)
[文档] def log_prob(self, value):
if self._validate_args:
self._validate_sample(value)
lb = self.low.le(value).type_as(self.low)
ub = self.high.gt(value).type_as(self.low)
return torch.log(lb.mul(ub)) - torch.log(self.high - self.low)
[文档] def cdf(self, value):
if self._validate_args:
self._validate_sample(value)
result = (值 - self.low) / (self.high - self.low)
return result.clamp(min=0, max=1)
[文档] def icdf(self, value):
result = value * (self.high - self.low) + self.low
返回结果
[文档] def 熵(self):
return torch.log(self.high - self.low)