本文整理匯總了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