二分类损失
- NCELoss
- NCEWithLogitsLoss
import torch.nn as nn
import torch
import numpy as np
def bce_loss(pred, y):
return -y*np.log(pred) - (1-y)*np.log(1-pred)
m = nn.Sigmoid()
input = torch.randn(3, requires_grad=True)
input_m = m(input)
target = torch.empty(3).random_(2)
print("predict origin:", input.data)
print("predict after sigmoid:", input_m.data)
print("actual label:", target)
print("BCE Loss:", nn.BCELoss(reduction='none')(input_m, target).data)
print("BCEwithLogitsLoss:", nn.BCEWithLogitsLoss(reduction='none')(input, target).data)
print("BCE Loss Mean:", nn.BCELoss(reduction='mean')(input_m, target).data)
input_m = input_m.detach().numpy()
target = target.detach().numpy()
print("Loss DIY", bce_loss(input_m, target))
-- output
predict origin: tensor([0.9719, 0.0456, 0.0118])
predict after sigmoid: tensor([0.7255, 0.5114, 0.5029])
actual label: tensor([1., 0., 0.])
BCE Loss: tensor([0.3209, 0.7162, 0.6990])
BCEwithLogitsLoss: tensor([0.3209, 0.7162, 0.6990])
BCE Loss Mean: tensor(0.5787)
Loss DIY [0.32090703 0.71618414 0.6990468 ]
根据官方文档,计算结果与手动计算结果一致,pytorch默认会是求平均。