这两个函数的区别在pytorch的帖子中已经描述过:log_softmax和softmax有什么区别?,softmax的公式为:exp(x_i) / exp(x).sum()
,而log softmax的公式为:log(exp(x_i) / exp(x).sum())
。
但对于下面的Pytorch代码,为什么我得到的输出不同:
>>> it = autograd.Variable(torch.FloatTensor([0.6229,0.3771]))>>> op = autograd.Variable(torch.LongTensor([0]))>>> m = nn.Softmax()>>> log = nn.LogSoftmax()>>> m(it)Variable containing:`0.5611 0.4389`[torch.FloatTensor of size 1x2]>>>log(it)Variable containing:-0.5778 -0.8236[torch.FloatTensor of size 1x2]
然而,log(0.5611)的值是-0.25095973129,log(0.4389)的值是-0.35763441915
为什么会有这样的差异?
回答:
默认情况下,torch.log
提供的是输入的自然对数,因此PyTorch的输出是正确的:
ln([0.5611,0.4389])=[-0.5778,-0.8236]
您的最后结果是使用以10为底的对数得到的。