PyTorch Softmax输出的总和不为1

时间:2019-10-29 21:53:44

标签: pytorch softmax

交叉发布my question from the PyTorch forum

我开始收到目标Dirichlet分布与模型输出Dirichlet分布之间的负KL散度。网上有人建议这可能表明Dirichlet分布的参数不等于1。我认为这很可笑,因为模型的输出是通过

传递的。

output = F.softmax(self.weights(x), dim=1)

但是仔细研究之后,我发现torch.all(torch.sum(output, dim=1) == 1.)返回False!查看有问题的行,我看到它是tensor([0.0085, 0.9052, 0.0863], grad_fn=<SelectBackward>)。但是torch.sum(output[5]) == 1.会产生tensor(False)

我对softmax有何误解,以致输出概率不等于1?

这是PyTorch版本1.2.0 + cpu。完整模型复制如下:

import torch
import torch.nn as nn
import torch.nn.functional as F



def assert_no_nan_no_inf(x):
    assert not torch.isnan(x).any()
    assert not torch.isinf(x).any()


class Network(nn.Module):
    def __init__(self):
        super().__init__()
        self.weights = nn.Linear(
            in_features=2,
            out_features=3)

    def forward(self, x):
        output = F.softmax(self.weights(x), dim=1)
        assert torch.all(torch.sum(output, dim=1) == 1.)
        assert_no_nan_no_inf(x)
        return output

1 个答案:

答案 0 :(得分:1)

这很可能是由于有限精度导致的浮点数值误差。

代替检查严格的不等式,您应该检查均方误差或在可接受范围内的值。

例如:我得到torch.norm(output.sum(dim=1)-1)/N小于1e-8。 N是批次大小。