【【Pytorch】】BCELoss和和BCEWithLogitsLoss损失函数详解
损失函数详解
在Pytorch中,BCELoss和BCEWithLogitsLoss是一组常用的二元交叉熵损失函数
进行sigmoid处理过的值,而后者为sigmoid函数11+exp(−x)\frac{1}{1+\exp(-x)}1+exp(−x)1中的xxx。
二元交叉熵损失函数,常用于二分类问题,其区别在于前者的输入为已
下面为一个简单的示例:
import torch
import torch.nn as nn
predicts = torch.tensor([[0.4,0.7,1.2,0.3], [1.1,0.6,0.9,1.6]])
labels = torch.tensor([[1,0,1,0],[0,1,1,0]], dtype=torch.float)
# 通过BCELoss计算sigmoid处理后的值
criterion1 = nn.BCELoss()
loss1= criterion1(torch.sigmoid(predicts), labels)
# 通过BCEWithLogitsLoss直接计算输入值
criterion2 = nn.BCEWithLogitsLoss()
loss2 = criterion2(predicts, labels)
# 会发现loss1=loss2
BCELoss和BCEWithLogitsLoss还提供了两个重要参数:
weight:可用于控制各样本的权重,常用作对对齐后的数据进行mask操作(设为0)
reduction:控制损失输出模式。设为”sum”表示对样本进行求损失和;设为”mean”表示对样本进行求损失的平均值;而设
为”none”表示对样本逐个求损失,输出与输入的shape一样。
此外BCEWithLogitsLoss还提供了参数pos_weight用于设置损失的class权重,用于缓解样本的不均衡问题。
作者:guofei_fly