CrossEntropyLoss,BCEWithLogitsLoss,BCEWithLogitsLoss细节(给不同的样本赋予不同的权重;给不同类别的样本赋予不同的权重)

torch.nn.BCELoss,torch.nn.BCEWithLogitsLoss中的weight参数和torch.nn.CrossEntropyLoss的weight参数意义不一样,torch.nn.CrossEntropyLoss,torch.nn.BCEWithLogitsLoss的weight是每个class的权重,torch.nn.BCELoss中的weight是每个样本的权重;torch.nn.BCEWithLogitsLoss对于输入都要做一个sigmoid操作再做average(-ylo
摘要由CSDN通过智能技术生成

torch.nn.BCELoss,torch.nn.BCEWithLogitsLoss中的weight参数和torch.nn.CrossEntropyLoss的weight参数意义不一样,torch.nn.CrossEntropyLoss,torch.nn.BCEWithLogitsLoss的weight是每个class的权重,torch.nn.BCELoss中的weight是每个样本的权重;torch.nn.BCEWithLogitsLoss对于输入都要做一个sigmoid操作再做average(-ylogx-(1-y)log(1-x),这里的x指sigmoid(输入),和torch.nn.CrossEntropyLoss相似,torch.nn.CrossEntropyLoss对于输入都要做一个softmax操作再做average(-ylogx),这里x指softmax(输入)

这里主要详细说明torch.nn.CrossEntropyLoss
https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html#torch.nn.CrossEntropyLoss上说torch.nn.CrossEntropyLoss combines nn.LogSoftmax() and nn.NLLLoss()(即torch.nn.CrossEntropyLoss是nn.LogSoftmax()和nn.NLLLoss()两个操作的结合)
在这里插入图片描述
根据上面公式可知torch.nn.CrossEntropyLoss计算一个样本的损失是先对输入做了softmax再做log,但一般softmax这个操作在自己的写的网络的最后一步就有了,在有softmax层的情况下再使用torch.nn.CrossEntropyLoss就对softmax层前的logits进行了两次softmax再进行log计算损失,所以在网络的最后一层为softmax层的时候,不能用torch.nn.CrossEntropyLoss,需要修改

loss_logsoftmax=torch.nn.CrossEntropyLoss()
loss=torch.nn.NLLLoss()
input=tensor([[-0.3209,  0.0796],
        [-1.1043,  0.3333],
        [ 1.1423,  1.5803]])
input_softmax=torch.nn.Softmax(dim
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值