Pytorch的损失函数BCELoss(), BCEWithLogitsLoss(), nn.CrossEntropyLoss()区别

 (BCELoss)BCEWithLogitsLoss用于单标签二分类或者多标签二分类,输出和目标的维度是(batch,C),batch是样本数量,C是类别数量,对于每一个batch的C个值,对每个值求sigmoid到0-1之间,所以每个batch的C个值之间是没有关系的,相互独立的,所以之和不一定为1。每个C值代表属于一类标签的概率。如果是单标签二分类,那输出和目标的维度是(batch,1)即可。
 BCELoss是CrossEntropyLoss的一个特例,只用于二分类问题,而CrossEntropyLoss可以用于二分类,也可以用于多分类。

1.nn.BCELoss():

 使用nn.BCELoss需要在该层前面加上Sigmoid函数:

criterion = nn.BCELoss()
# pred和target的shape要相同
# pred.shape: (batch, dim)
# target.shape: (batch, dim)
loss = criterion(pred, target)

2.nn.BCEWithLogitsLoss():

 BCEWithLogitsLoss = Sigmoid+BCELoss
 【官网的话:This loss combines a Sigmoid layer and the BCELoss in one single class. This version is more numerically stable than using a plain Sigmoid followed by a BCELoss as, by combining the operations into one layer, we take advantage of the log-sum-exp trick for numerical stability.】
 这因为它用了log-sum-exp trick在数值上更稳定,并在您的模型预测非常错误时防止出现任何不稳定性。如果您不使用logit损失函数,则当模型预测不正确的非常高或非常低的值时,您可能会遇到问题。(关于log-sum-exp,看文末链接)

criterion = nn.BCEWithLogitsLoss()
# pred和target的shape要相同
# pred.shape: (batch, dim)
# target.shape: (batch, dim)
loss = criterion(pred, target)

3.nn.CrossEntropyLoss():

 使用nn.CrossEntropyLoss会自动加上Sofrmax层。
 CrossEntropyLoss用于多类别分类,输出维度是(batch,C),目标的维度是(batch, )。batch是样本数量,C是类别数量,每一个C之间是互斥的,相互关联的,对于每一个batch的C个值,一起求每个C的softmax,所以每个batch的所有C个值之和是1,哪个值大,代表其属于哪一类。如果用于二分类,那输出和目标的维度是(batch,2)。

criterion = nn.CrossEntropyLoss()
# pred.shape: (batch, num_class)
# target.shape: (batch, )
loss = criterion(pred, target)



链接
【1】log-sum-exp trick
【2】LogSumExp增强数值稳定性
【3】二分类问题,应该选择sigmoid还是softmax?(初识CV的回答)

你可能感兴趣的:(NLP,pytorch,pytorch,损失函数,深度学习)