首页 > 解决方案 > nll_loss 的范围是多少?

问题描述

我认为该范围仅在正域内,但我得到 F.nll_loss 的负数和正数?

这是为什么?我很困惑。Softmax 的范围从 0 到 1,-log(0 到 1) 从无穷大到 0。那么,为什么我会得到负数?

标签: pytorch

解决方案


以下是该功能的实现方式:

f = F.nll_loss

def NLLLoss(logs, targets):
    out = logs[range(len(targets)), targets]
    return -out.sum()/len(out)


i = torch.randn(3, 5)
print(i)


t = torch.empty(3).random_(0, 5).to(dtype=torch.long)
print(t)

o = f(i,t)
print(o)

f = NLLLoss

o = f(i,t)
print(o)

# tensor([[ 0.0684,  0.9493, -0.9932, -1.9325, -0.1642],
#         [ 1.7073,  0.8153, -0.6435, -1.0128,  0.9894],
#         [ 0.6948, -1.3770, -0.0932, -0.0951, -1.4226]])
# tensor([2, 0, 3])
# tensor(-0.2063)
# tensor(-0.2063)

它只是值的总和,范围可以从 -inf 到 inf。


推荐阅读