Shortcuts

torch.distributions.dirichlet 的源代码

import torch
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.distributions import constraints
from torch.distributions.exp_family import ExponentialFamily

__all__ = ["Dirichlet"]


# 此辅助函数用于测试。
def _Dirichlet_backward(x, concentration, grad_output):
    total = concentration.sum(-1, True).expand_as(concentration)
    grad = torch._dirichlet_grad(x, concentration, total)
    return grad * (grad_output - (x * grad_output).sum(-1, True))


class _Dirichlet(Function):
    @staticmethod
    def forward(ctx, concentration):
        x = torch._sample_dirichlet(concentration)
        ctx.save_for_backward(x, concentration)
        return x

    @staticmethod
    @once_differentiable
    def backward(ctx, grad_output):
        x, concentration = ctx.saved_tensors
        return _Dirichlet_backward(x, concentration, grad_output)


[docs]class Dirichlet(ExponentialFamily): r""" 创建一个由浓度参数 :attr:`concentration` 参数化的 Dirichlet 分布。 示例:: >>> # xdoctest: +IGNORE_WANT("非确定性") >>> m = Dirichlet(torch.tensor([0.5, 0.5])) >>> m.sample() # 浓度为 [0.5, 0.5] 的 Dirichlet 分布 tensor([ 0.1046, 0.8954]) 参数: concentration (Tensor): 分布的浓度参数 (通常称为 alpha) """ arg_constraints = { "concentration": constraints.independent(constraints.positive, 1) } support = constraints.simplex has_rsample = True def __init__(self, concentration, validate_args=None): if concentration.dim() < 1: raise ValueError( "`concentration` 参数必须至少为一维。" ) self.concentration = concentration batch_shape, event_shape = concentration.shape[:-1], concentration.shape[-1:] super().__init__(batch_shape, event_shape, validate_args=validate_args)
[docs] def expand(self, batch_shape, _instance=None): new = self._get_checked_instance(Dirichlet, _instance) batch_shape = torch.Size(batch_shape) new.concentration = self.concentration.expand(batch_shape + self.event_shape) super(Dirichlet, new).__init__( batch_shape, self.event_shape, validate_args=False ) new._validate_args = self._validate_args return new
[docs] def rsample(self, sample_shape=()): shape = self._extended_shape(sample_shape) concentration = self.concentration.expand(shape) return _Dirichlet.apply(concentration)
[docs] def log_prob(self, value): if self._validate_args: self._validate_sample(value) return ( torch.xlogy(self.concentration - 1.0, value).sum(-1) + torch.lgamma(self.concentration.sum(-1)) - torch.lgamma(</
优云智算