PyTorch Softmax输出的总和不等于1

问题描述 投票:1回答:1

交叉发布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
pytorch softmax
1个回答
1
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.