pytorch
99 строк · 3.2 Кб
1from numbers import Number2
3import torch4from torch import nan5from torch.distributions import constraints6from torch.distributions.distribution import Distribution7from torch.distributions.utils import broadcast_all8
9__all__ = ["Uniform"]10
11
12class Uniform(Distribution):13r"""14Generates uniformly distributed random samples from the half-open interval
15``[low, high)``.
16
17Example::
18
19>>> m = Uniform(torch.tensor([0.0]), torch.tensor([5.0]))
20>>> m.sample() # uniformly distributed in the range [0.0, 5.0)
21>>> # xdoctest: +SKIP
22tensor([ 2.3418])
23
24Args:
25low (float or Tensor): lower range (inclusive).
26high (float or Tensor): upper range (exclusive).
27"""
28# TODO allow (loc,scale) parameterization to allow independent constraints.29arg_constraints = {30"low": constraints.dependent(is_discrete=False, event_dim=0),31"high": constraints.dependent(is_discrete=False, event_dim=0),32}33has_rsample = True34
35@property36def mean(self):37return (self.high + self.low) / 238
39@property40def mode(self):41return nan * self.high42
43@property44def stddev(self):45return (self.high - self.low) / 12**0.546
47@property48def variance(self):49return (self.high - self.low).pow(2) / 1250
51def __init__(self, low, high, validate_args=None):52self.low, self.high = broadcast_all(low, high)53
54if isinstance(low, Number) and isinstance(high, Number):55batch_shape = torch.Size()56else:57batch_shape = self.low.size()58super().__init__(batch_shape, validate_args=validate_args)59
60if self._validate_args and not torch.lt(self.low, self.high).all():61raise ValueError("Uniform is not defined when low>= high")62
63def expand(self, batch_shape, _instance=None):64new = self._get_checked_instance(Uniform, _instance)65batch_shape = torch.Size(batch_shape)66new.low = self.low.expand(batch_shape)67new.high = self.high.expand(batch_shape)68super(Uniform, new).__init__(batch_shape, validate_args=False)69new._validate_args = self._validate_args70return new71
72@constraints.dependent_property(is_discrete=False, event_dim=0)73def support(self):74return constraints.interval(self.low, self.high)75
76def rsample(self, sample_shape=torch.Size()):77shape = self._extended_shape(sample_shape)78rand = torch.rand(shape, dtype=self.low.dtype, device=self.low.device)79return self.low + rand * (self.high - self.low)80
81def log_prob(self, value):82if self._validate_args:83self._validate_sample(value)84lb = self.low.le(value).type_as(self.low)85ub = self.high.gt(value).type_as(self.low)86return torch.log(lb.mul(ub)) - torch.log(self.high - self.low)87
88def cdf(self, value):89if self._validate_args:90self._validate_sample(value)91result = (value - self.low) / (self.high - self.low)92return result.clamp(min=0, max=1)93
94def icdf(self, value):95result = value * (self.high - self.low) + self.low96return result97
98def entropy(self):99return torch.log(self.high - self.low)100