https://blog.csdn.net/weixin_40476348/article/details/94562240
class torch.nn.NLLLoss(weight=None, size_average=None, ignore_index=-100,
reduce=None, reduction=‘mean‘)
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.manual_seed(2019)
output = torch.randn(1, 3) # 网络输出
target = torch.ones(1, dtype=torch.long).random_(3) # 真实标签
print(output)
print(target)
# 直接调用
loss = F.nll_loss(output, target)
print(loss)
# 实例化类
criterion = nn.NLLLoss()
loss = criterion(output, target)
print(loss)
"""
tensor([[-0.1187, 0.2110, 0.7463]])
tensor([1])
tensor(-0.2110)
tensor(-0.2110)
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.manual_seed(2019)
output = torch.randn(2, 3) # 网路输出
target = torch.ones(2, dtype=torch.long).random_(3) # 真实标签
print(output)
print(target)
# 直接调用
loss = F.nll_loss(output, target)
print(loss)
# 实例化类
criterion = nn.NLLLoss(reduction=‘none‘)
loss = criterion(output, target)
print(loss)
"""
tensor([[-0.1187, 0.2110, 0.7463],
[-0.6136, -0.1186, 1.5565]])
tensor([2, 0])
tensor(-0.0664)
tensor([-0.7463, 0.6136])
"""
原文:https://www.cnblogs.com/leebxo/p/11913939.html