本文整理汇总了Python中torch.distributions.Distribution方法的典型用法代码示例。如果您正苦于以下问题:Python distributions.Distribution方法的具体用法?Python distributions.Distribution怎么用?Python distributions.Distribution使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类torch.distributions
的用法示例。
在下文中一共展示了distributions.Distribution方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _mcmc_move
# 需要导入模块: from torch import distributions [as 别名]
# 或者: from torch.distributions import Distribution [as 别名]
def _mcmc_move(params: Iterable[Parameter], dist: Distribution, stacked: StackedObject, shape: int):
"""
Performs an MCMC move to rejuvenate parameters.
:param params: The parameters to use for defining the distribution
:param dist: The distribution to use for sampling
:param stacked: The mask to apply for parameters
:param shape: The shape to sample
:return: Samples from a multivariate normal distribution
"""
rvs = dist.sample((shape,))
for p, msk, ps in zip(params, stacked.mask, stacked.prev_shape):
p.t_values = unflattify(rvs[:, msk], ps)
return True
示例2: __init__
# 需要导入模块: from torch import distributions [as 别名]
# 或者: from torch.distributions import Distribution [as 别名]
def __init__(self, hidden, a=1., scale=1.):
"""
Implements a State Space model that's linear in the observation equation but has arbitrary dynamics in the
state process.
:param hidden: The hidden dynamics
:param a: The A-matrix
:param scale: The variance of the observations
"""
# ===== Convoluted way to decide number of dimensions ===== #
dim, is_1d = _get_shape(a)
# ====== Define distributions ===== #
n = dists.Normal(0., 1.) if is_1d else dists.Independent(dists.Normal(torch.zeros(dim), torch.ones(dim)), 1)
if not isinstance(scale, (torch.Tensor, float, dists.Distribution)):
raise ValueError(f'`scale` parameter must be numeric type!')
super().__init__(hidden, a, scale, n)
示例3: _iterate_distribution
# 需要导入模块: from torch import distributions [as 别名]
# 或者: from torch.distributions import Distribution [as 别名]
def _iterate_distribution(d: Distribution) -> Tuple[Distribution, ...]:
"""
Helper method for iterating over distributions.
:param d: The distribution
"""
res = tuple()
if not isinstance(d, TransformedDistribution):
res += tuple(_find_types(d, torch.Tensor).values())
for sd in _find_types(d, Distribution).values():
res += _iterate_distribution(sd)
else:
res += _iterate_distribution(d.base_dist)
for t in d.transforms:
res += tuple(_find_types(t, torch.Tensor).values())
return res
示例4: tensors
# 需要导入模块: from torch import distributions [as 别名]
# 或者: from torch.distributions import Distribution [as 别名]
def tensors(self) -> Tuple[torch.Tensor, ...]:
"""
Finds and returns all instances of type module.
"""
res = tuple()
# ===== Find all tensor types ====== #
res += tuple(self._find_obj_helper(torch.Tensor).values())
# ===== Tensor containers ===== #
for tc in self._find_obj_helper(TensorContainerBase).values():
res += tc.tensors
for t in (t_ for t_ in tc.tensors if isinstance(t_, Parameter) and t_.trainable):
res += _iterate_distribution(t.distr)
# ===== Pytorch distributions ===== #
for d in self._find_obj_helper(Distribution).values():
res += _iterate_distribution(d)
# ===== Modules ===== #
for mod in self.modules().values():
res += mod.tensors()
return res
示例5: _test_marginal
# 需要导入模块: from torch import distributions [as 别名]
# 或者: from torch.distributions import Distribution [as 别名]
def _test_marginal(self, batch_shape):
likelihood = self.create_likelihood()
likelihood.max_plate_nesting += len(batch_shape)
input = self._create_marginal_input(batch_shape)
output = likelihood(input)
self.assertTrue(isinstance(output, Distribution))
self.assertEqual(output.sample().shape[-len(input.sample().shape) :], input.sample().shape)
# Compare against default implementation
with gpytorch.settings.num_likelihood_samples(30000):
default = Likelihood.marginal(likelihood, input)
# print(output.mean, default.mean)
default_mean = default.mean
actual_mean = output.mean
if default_mean.dim() > actual_mean.dim():
default_mean = default_mean.mean(0)
self.assertAllClose(default_mean, actual_mean, rtol=0.25, atol=0.25)
示例6: _validate_module_outputs
# 需要导入模块: from torch import distributions [as 别名]
# 或者: from torch.distributions import Distribution [as 别名]
def _validate_module_outputs(outputs):
if isinstance(outputs, tuple):
if not all(
torch.is_tensor(output) or isinstance(output, Distribution) or isinstance(output, LazyTensor)
for output in outputs
):
raise RuntimeError(
"All outputs must be a Distribution, torch.Tensor, or LazyTensor. "
"Got {}".format([output.__class__.__name__ for output in outputs])
)
if len(outputs) == 1:
outputs = outputs[0]
return outputs
elif torch.is_tensor(outputs) or isinstance(outputs, Distribution) or isinstance(outputs, LazyTensor):
return outputs
else:
raise RuntimeError(
"Output must be a Distribution, torch.Tensor, or LazyTensor. Got {}".format(outputs.__class__.__name__)
)
示例7: _eval_kernel
# 需要导入模块: from torch import distributions [as 别名]
# 或者: from torch.distributions import Distribution [as 别名]
def _eval_kernel(params: Iterable[Parameter], dist: Distribution, n_params: Iterable[Parameter]):
"""
Evaluates the kernel used for performing the MCMC move.
:param params: The current parameters
:param dist: The distribution to use for evaluating the prior
:param n_params: The new parameters to evaluate against
:return: The log difference in priors
"""
p_vals = stacker(params, lambda u: u.t_values)
n_p_vals = stacker(n_params, lambda u: u.t_values)
return dist.log_prob(p_vals.concated) - dist.log_prob(n_p_vals.concated)
示例8: define_pdf
# 需要导入模块: from torch import distributions [as 别名]
# 或者: from torch.distributions import Distribution [as 别名]
def define_pdf(self, values: torch.Tensor, weights: torch.Tensor) -> Distribution:
"""
The method to be overridden by the user for defining the kernel to propagate the parameters. Note that the
parameters are propagated in the transformed space.
:param values: The parameters as a single Tensor
:param weights: The normalized weights of the particles
:return: A distribution
"""
raise NotImplementedError()
示例9: dist
# 需要导入模块: from torch import distributions [as 别名]
# 或者: from torch.distributions import Distribution [as 别名]
def dist(self) -> Distribution:
"""
Returns the distribution.
"""
raise NotImplementedError()
示例10: _get_shape
# 需要导入模块: from torch import distributions [as 别名]
# 或者: from torch.distributions import Distribution [as 别名]
def _get_shape(a):
is_1d = False
if isinstance(a, dists.Distribution):
dim = a.event_shape
is_1d = len(a.event_shape) == 1
elif isinstance(a, float) or a.dim() < 2:
dim = torch.Size([])
is_1d = (torch.tensor(a) if isinstance(a, float) else a).dim() <= 1
else:
dim = a.shape[:1]
return dim, is_1d
示例11: __new__
# 需要导入模块: from torch import distributions [as 别名]
# 或者: from torch.distributions import Distribution [as 别名]
def __new__(cls, parameter: Union[torch.Tensor, Distribution] = None, requires_grad=False):
if isinstance(parameter, Parameter):
raise ValueError('The input cannot be of instance `{}`!'.format(parameter.__class__.__name__))
elif isinstance(parameter, torch.Tensor):
_data = parameter
elif not isinstance(parameter, Distribution):
_data = torch.tensor(parameter) if not isinstance(parameter, np.ndarray) else torch.from_numpy(parameter)
else:
# This is just a place holder
_data = torch.empty(parameter.event_shape)
return torch.Tensor._make_subclass(cls, _data, requires_grad)
示例12: __init__
# 需要导入模块: from torch import distributions [as 别名]
# 或者: from torch.distributions import Distribution [as 别名]
def __init__(self, parameter: Union[torch.Tensor, Distribution] = None, requires_grad=False):
"""
The parameter class.
"""
self._prior = parameter if isinstance(parameter, Distribution) else None
示例13: transformed_dist
# 需要导入模块: from torch import distributions [as 别名]
# 或者: from torch.distributions import Distribution [as 别名]
def transformed_dist(self):
"""
Returns the unconstrained distribution.
"""
if not self.trainable:
raise ValueError('Is not of `Distribution` instance!')
return TransformedDistribution(self._prior, [self.bijection.inv])
示例14: bijection
# 需要导入模块: from torch import distributions [as 别名]
# 或者: from torch.distributions import Distribution [as 别名]
def bijection(self) -> Transform:
"""
Returns a bijected function for transforms from unconstrained to constrained space.
"""
if not self.trainable:
raise ValueError('Is not of `Distribution` instance!')
return biject_to(self._prior.support)
示例15: sample_
# 需要导入模块: from torch import distributions [as 别名]
# 或者: from torch.distributions import Distribution [as 别名]
def sample_(self, shape: Union[int, Tuple[int, ...], torch.Size] = None):
"""
Samples the variable from prior distribution in place.
:param shape: The shape to use
"""
if not self.trainable:
raise ValueError('Cannot initialize parameter as it is not of instance `Distribution`!')
self.data = self._prior.sample(size_getter(shape))
return self