本文主要记录一下pytorch里面的二分类及多分类交叉熵损失函数的使用。
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.manual_seed(2020)
<torch._C.Generator at 0x7f4e8b3298b0>
二分类交叉熵损失函数
该函数主要用于多标签分类中,针对每个标签进行二分类。
Single
m = nn.Sigmoid()
loss = nn.BCELoss()
input = torch.randn(3, requires_grad=True)
print(input)
target = torch.empty(3).random_(2)
output = loss(m(input), target)
print(output)
f_output = F.binary_cross_entropy(m(input), target)
print(f_output)
l_output = nn.BCEWithLogitsLoss()(input, target)
print(l_output)
tensor([ 1.2372, -0.9604, 1.5415], requires_grad=True)
tensor(0.2576, grad_fn=<BinaryCrossEntropyBackward>)
tensor(0.2576, grad_fn=<BinaryCrossEntropyBackward>)
tensor(0.2576, grad_fn=<BinaryCrossEntropyWithLogitsBackward>)
Batch
m = nn.Sigmoid()
loss = n

本文详细介绍了PyTorch中二分类及多分类交叉熵损失函数的使用方法,并通过实例展示了BCELoss、BCEWithLogitsLoss及CrossEntropyLoss的具体应用。
最低0.47元/天 解锁文章
7927

被折叠的 条评论
为什么被折叠?



