评价此页

torch.nn.functional.gumbel_softmax#

torch.nn.functional.gumbel_softmax(logits, tau=1, hard=False, eps=1e-10, dim=-1)[source]#

从 Gumbel-Softmax 分布中采样(链接 1 链接 2),并可选地进行离散化。

参数
  • logits (Tensor) – […, num_features] 未归一化的对数概率

  • tau (float) – 非负标量温度

  • hard (bool) – 如果为 True,则返回的样本将被离散化为 one-hot 向量,但在 autograd 中将其视为 soft 样本进行反向传播

  • dim (int) – softmax 将在其上计算的维度。默认值:-1。

返回

从 Gumbel-Softmax 分布采样的张量,形状与 logits 相同。如果 hard=True,则返回的样本将是 one-hot 的;否则,它们将是跨 dim 求和为 1 的概率分布。

返回类型

张量

注意

此函数用于历史原因,将来可能会从 nn.Functional 中移除。

注意

对于 hard 的主要技巧是执行 y_hard - y_soft.detach() + y_soft

它实现了两件事:- 使输出值精确地为 one-hot(因为我们添加然后减去 y_soft 值)- 使梯度等于 y_soft 的梯度(因为我们剥离了所有其他梯度)

示例:
>>> logits = torch.randn(20, 32)
>>> # Sample soft categorical using reparametrization trick:
>>> F.gumbel_softmax(logits, tau=1, hard=False)
>>> # Sample hard categorical using "Straight-through" trick:
>>> F.gumbel_softmax(logits, tau=1, hard=True)