pytorch中实现Balanced Cross-Entropy

当你明白了pytorch中F.cross_entropy以及F.binary_cross_entropy是如何实现的之后,你再基于它们做改进重新实现一个损失函数就很容易了。
1、背景
变化检测中,往往存在样本不均衡的情况,也就是changed pixel很少,而unchange pixel占据大多数,论文DASNet: Dual Attentive Fully Convolutional Siamese Networks for Change Detection in High-Resolution Satellite Images中统计了在CCD和BCCD数据集中change-pixel与unchanged-pixel的比例。
在这里插入图片描述
显然,样本间存在严重的不平衡问题,这个时候为了解决数据不平衡的问题,我们需要改进损失函数,如使用同时为正负样本加权的Balanced Cross-Entropy损失函数,可通过beta控制,该函数的公式如下:
在这里插入图片描述
这里给大家分享篇论文,A survey of loss functions for semantic segmentation介绍了语义分割中常用的损失函数,包括上面的Balanced Cross-Entropy。

2、pytorch中实现Balanced Cross-Entropy

class Balanced_CE_loss(torch.nn.Module):
    def __init__(self):
        super(Balanced_CE_loss, self).__init__()

    def forward(self, input, target):
        input = input.view(input.shape[0], -1)
        target = target.view(target.shape[0], -1)
        loss = 0.0
        for i in range(input.shape[0]):
            beta = 1-torch.sum(target[i])/target.shape[1]
            for j in range(input.shape[1]):
                loss += -(beta*target[i][j] * torch.log(input[i][j]) + (1-beta)*(1 - target[i][j]) * torch.log(1 - input[i][j]))
        return loss

发现其实上述的代码也就是在binary_cross_entropy的实现基础上加了一个beta系数,其中beta=1-y/(w*h)。

3、优化
如果按照上面的写法,那你在训练的时候你就会无语了,对于嵌套的for循环,cuda加速巨慢无比,所以我们将上述代码进行一些优化。而且在pytorch实现的损失函数中对log的输出做了限制(我在一文搞懂F.binary_cross_entropy的具体实现中有提及),所以我们也对其做一个限制,否则训练的时候可能会出现无穷值,导致方向传播出问题。

class Balanced_CE_loss(torch.nn.Module):
    def __init__(self):
        super(Balanced_CE_loss, self).__init__()

    def forward(self, input, target):
        input = input.view(input.shape[0], -1)
        target = target.view(target.shape[0], -1)
        loss = 0.0
        # version2
        for i in range(input.shape[0]):
            beta = 1-torch.sum(target[i])/target.shape[1]
            x = torch.max(torch.log(input[i]), torch.tensor([-100.0]))
            y = torch.max(torch.log(1-input[i]), torch.tensor([-100.0]))
            l = -(beta*target[i] * x + (1-beta)*(1 - target[i]) * y)
            loss += torch.sum(l)
        return loss

注:如有错误还请指出!

  • 4
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值