torch.distributions.dirichlet 的源代码
# mypy: 允许未类型化定义
导入
火炬
来自
火炬
导入
张量
来自
torch 自动微分
导入
函数
来自 torch.autograd.function
导入
一次可微
来自 torch.distributions
导入
约束
来自 torch.distributions.exp_family
导入
指数族
来自
torch 的类型
导入
_大小
全部 = [
费马-狄利克雷分布]
此辅助函数公开供测试使用。
定义
_Dirichlet_后向(x,
浓度, grad_output):
总计 =
浓度.
总和(-1,
是).
展开为(
浓度)
梯度 = torch.
_dirichlet_梯度(x,
浓度,
总计)
返回
梯度 * (
梯度输出 - (x * grad_output).
总和(-1,
是))
类
_Dirichlet_(
函数):
@staticmethod
定义
前向(ctx,
浓度):
x = torch._样本狄利克雷(
浓度)
ctx.保存用于回放(x,
浓度)
返回 x
@staticmethod
@once_differentiable
定义
反向(ctx, grad_output):
x, 浓度 = ctx.
保存的张量
返回
_Dirichlet 向后(x,
浓度, grad_output)
[文档]
类
Dirichlet 分布(
指数族):
r""
创建一个由浓度 :attr:`concentration` 参数化的 Dirichlet 分布。
示例::
>>> # xdoctest: +IGNORE_WANT("非确定性")
>>> m = Dirichlet(torch.tensor([0.5, 0.5]))
>>> m.sample() # Dirichlet 分布,浓度 [0.5, 0.5]
tensor([ 0.1046, 0.8954])
参数:
浓度 (Tensor):分布的浓度参数
(通常称为 alpha)
"沉浸式翻译"
约束参数 = {
"浓度":
约束.
独立的(
约束.
正面, 1)
}
支持 =
约束.
单一的
has_rsample = 真实
def __init__(self, 浓度,
验证参数=
无):
如果
浓度.
暗淡() < 1:
抛出
值错误(
“浓度”参数必须至少是一维的。
)
self.浓度 =
注意力
批量形状,
事件形状 =
浓度.
形状
[-1
]
浓度.
形状[-1
]
超级().__init__(
批量形状,
事件形状,
验证参数=
验证参数)
[文档] def 展开(self, 批量形状, _实例=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
[文档] def rsample(self, sample_shape: _size = ()) -> Tensor:
shape = self._extended_shape(sample_shape)
concentration = self.concentration.expand(shape)
return _Dirichlet.apply(concentration)
[文档] 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(self.concentration).sum(-1)
)
@property
def 均值(self) ->
张量:
返回 self.
注意力 / self.
浓度.
总和(-1,
是)
@property
def 模式(self) ->
张量:
注意力 m1 = (
我.
注意力 - 1).
卡钳(
最小值=0.0)
模式 =
注意力 m1 /
浓度 m1.
总和(-1,
是)
面具 = (
我.
浓度 < 1).
所有(
暗淡=-1)
模式[
面具] = torch.
神经网络.
功能性.one_hot(
模式[
面具].argmax(
暗淡=-1),
浓度 m1.
形状[-1]
).到(
模式)
返回
模式
@property
定义
方差(
自身) ->
张量:
con0 = 自身.
浓度.
总和(-1,
是)
返回 (
自身.
浓度
* (con0 - 自身.
浓度)
/ (con0.pow(2) * (con0 + 1))
)
[文档] def 熵(self):
k = self.concentration.size(-1)
a0 = self.concentration.sum(-1)
return (
torch.lgamma(self.concentration).sum(-1)
- torch.lgamma(a0)
- (k - a0) * torch.digamma(a0)
- ((self.concentration - 1.0) * torch.digamma(self.concentration)).sum(-1)
- (self.concentration - 1.0) * torch.digamma(self.concentration) 的 -1 维求和
)
@property
定义
自然参数(
自身) ->
元组[
张量
]
返回 (
自身.
浓度,)
定义
对数归一化器(
自身, x):
返回 x.lgamma().
总和(-1) - torch.lgamma(x.
总和(-1))