美文网首页
BCELoss和BCEWithLogitsLoss

BCELoss和BCEWithLogitsLoss

作者: 三方斜阳 | 来源:发表于2021-10-06 19:39 被阅读0次

计算多标签分类时候的损失函数一般选择BCELoss和BCEWithLogitsLoss,这两者的区别在于:

  • BCELoss 是处理经过Sigmoid之后输出的概率值
  • BCEWithLogitsLoss是把两者合到一起Sigmoid-BCELoss
    具体计算例子:
  1. 准备输入input:
import torch
import torch.nn as nn
input = torch.tensor([[-0.4089,-1.2471,0.5907],
                      [-0.4897,-0.8267,-0.7349],
                      [0.5241,-0.1246,-0.4751]])
print(input)
tensor([[-0.4089, -1.2471,  0.5907],
        [-0.4897, -0.8267, -0.7349],
        [ 0.5241, -0.1246, -0.4751]])
  1. sigmoid 将输出值约束到0-1之间:
m=nn.Sigmoid()
S_input=m(input)
print(S_input)
tensor([[0.3992, 0.2232, 0.6435],
        [0.3800, 0.3043, 0.3241],
        [0.6281, 0.4689, 0.3834]])
  1. 准备目标值target:
target=torch.FloatTensor([[0,1,1],[0,0,1],[1,0,1]])
print(target)
tensor([[0., 1., 1.],
        [0., 0., 1.],
        [1., 0., 1.]])
  1. 接着使用BCELoss计算损失值:
BCELoss=nn.BCELoss()
loss=BCELoss(S_input,target)
print(loss)
tensor(0.7193)
  1. 如下图看BCELoss如何计算多标签分类的损失,验证计算结果一致:


  • 下面通过具体实现验证图示的计算过程:
loss = 0.0
for i in range(S_input.shape[0]):
    for j in range(S_input.shape[1]):
        loss += -(target[i][j] * torch.log(S_input[i][j]) + (1 - target[i][j]) * torch.log(1 - S_input[i][j]))
print(loss/(S_input.shape[0]*S_input.shape[1])) # 默认取均值
tensor(0.7193)
  1. BCEWithLogitsLoss 就是把求Sigmoid 和上图的取log等计算loss合到一起:
BCEWithLogitsLoss=nn.BCEWithLogitsLoss()
loss=BCEWithLogitsLoss(input,target)
print(loss)
tensor(0.7193)

相关文章

  • BCELoss和BCEWithLogitsLoss

    计算多标签分类时候的损失函数一般选择BCELoss和BCEWithLogitsLoss,这两者的区别在于: BCE...

  • 炼丹解惑 五

    Pytorch详解BCELoss和BCEWithLogitsLoss[%5Bhttps://blog.csdn.n...

  • pytorch中BCEWithLogitsLoss&CrossE

    先说结论: BCEWithLogitsLoss函数包括了 Sigmoid 层和 BCELoss 层. 适用于多标签...

  • Pytorch详解BCELoss和BCEWithLogitsLo

    BCELoss 在图片多标签分类时,如果3张图片分3类,会输出一个3*3的矩阵。 先用Sigmoid给这些值都搞到...

  • BCEWithLogitsLoss参数weight

    1. weight: a manual rescaling weight given to the loss of...

  • Pytorch损失函数BCELoss,BCEWithLogits

    1. BCELoss 该类主要用来创建衡量目标和输出之间的二进制交叉熵的标准。用法如下:torch.nn.BCEL...

  • loss函数之BCELoss

    BCELoss 二分类交叉熵损失 单标签二分类 一个输入样本对应于一个分类输出,例如,情感分类中的正向和负向 对于...

  • 多标签分类与BCEloss

    什么是多标签分类 学习过机器学习的你,也许对分类问题很熟悉。比如下图: 图片中是否包含房子?你的回答就是有或者没有...

  • BCEWithLogitsLoss参数pos_weight样本不

    下面是具体的参数: 1. pos_weight: 处理样本不均衡问题torch.nn.BCEWithLogitsL...

  • -和 和 -

    产品介绍:和和是一款会员制共享平台;所有 经营者可在APP内注册和和商家成为会员供 应商(实体店、网店、微商、平台...

网友评论

      本文标题:BCELoss和BCEWithLogitsLoss

      本文链接:https://www.haomeiwen.com/subject/aoronltx.html