Shortcuts

torch.distributions.uniform 的源代码

from numbers import Number

import torch
from torch import nan
from torch.distributions import constraints
from torch.distributions.distribution import Distribution
from torch.distributions.utils import broadcast_all

__all__ = ["Uniform"]


[docs]class Uniform(Distribution): r""" 从半开区间 ``[low, high)`` 生成均匀分布的随机样本。 示例:: >>> m = Uniform(torch.tensor([0.0]), torch.tensor([5.0])) >>> m.sample() # 在范围 [0.0, 5.0) 内均匀分布 >>> # xdoctest: +SKIP tensor([ 2.3418]) 参数: low (float 或 Tensor): 下界(包含)。 high (float 或 Tensor): 上界(不包含)。 """ # TODO 允许 (loc,scale) 参数化以允许独立的约束。 arg_constraints = { "low": constraints.dependent(is_discrete=False, event_dim=0), "high": constraints.dependent(is_discrete=False, event_dim=0), } has_rsample = True @property def mean(self): return (self.high + self.low) / 2 @property def mode(self): return nan * self.high @property def stddev(self): return (self.high - self.low) / 12**0.5 @property def variance(self): return (self.high - self.low).pow(2) / 12 def __init__(self, low, high, validate_args=None): self.low, self.high = broadcast_all(low, high) if isinstance(low, Number) and isinstance(high, Number): batch_shape = torch.Size() else: batch_shape = self.low.size() super().__init__(batch_shape, validate_args=validate_args) if self._validate_args and not torch.lt(self.low, self.high).all(): raise ValueError("Uniform 在 low>= high 时未定义")
[docs] 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.dependent_property(is_discrete=False, event_dim=0) def support(self): return constraints.interval(self.low, self.high)
[docs] def rsample(self, sample_shape=torch.Size()): 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<span class
优云智算