当前位置:   article > 正文

PyTorch中CrossEntropyLoss、BCELoss、BCEWithLogitsLoss的理解_crossentropyloss bcewithlogitsloss

crossentropyloss bcewithlogitsloss

import torch
predict =torch.Tensor([[0.5796,0.4403,0.9087],[-1.5673,-0.3150,1.6660]])
#predict =torch.Tensor([[0.5796,0.4403],[-1.5673,-0.3150]])
print(predict)

target =torch.tensor([0,2])
target_bce =torch.Tensor([[1,0,0],[0,0,1]])
ce_loss=torch.nn.CrossEntropyLoss()


soft_max=torch.nn.Softmax(dim=-1)
sig_max=torch.nn.Sigmoid()

soft_out=soft_max(predict)
sig_out=sig_max(predict)

bce_loss=torch.nn.BCELoss()
bce_loss1=torch.nn.BCEWithLogitsLoss()
print(ce_loss(predict,target))
print(bce_loss(soft_out,target_bce))
print(bce_loss(sig_out,target_bce))
print(bce_loss1(predict,target_bce))

输出:

#predict:

tensor([[ 0.5796,  0.4403,  0.9087],
        [-1.5673, -0.3150,  1.6660]])

#print(ce_loss(predict,target)):

tensor(0.6725)

#print(bce_loss(soft_out,target_bce))
tensor(0.3950)


#print(bce_loss(sig_out,target_bce))

tensor(0.5900)

print(bce_loss1(predict,target_bce))
tensor(0.5900)

结论:

1.sigmoid激活+BCELoss等于BCEWithLogitsLoss

2.BCEWithLogitsLoss和CrossEntropyLoss不一样,但都可以不加激活

3.sigmoid激活+BCELoss和softmax激活+BCELoss有很大区别

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/951111
推荐阅读
相关标签
  

闽ICP备14008679号