【mmsegmentation】Loss模块(进阶)自定义自己的LOSS

1、定义自己的loss

driving\models\losses\shuai_loss.py

import torch
from torch import nn
from mmseg.models import LOSSES

@LOSSES.register_module()
class ShuaiLoss(nn.Module):
    def __init__(self,loss_weight=1.0):
        super().__init__()
        self.ce_loss = nn.CrossEntropyLoss()
        self.loss_weight = loss_weight
    def forward(self,input,target,device_id='cpu',sample_ratio=1.0):
        loss = {}
        if len(target)==0:
            loss["cls_cost"] = torch.tensor(0.0,dtype=torch.float32,device=device_id)
        else:
            loss["cls_cost"] = self.ce_loss(input,target)
        
        loss["total_road_cls_loss"] = loss["cls_cost"] * self.loss_weight * sample_ratio # + other losses, if have

        return loss

看下LOSSES注册表(@LOSSES.register_module())
在这里插入图片描述

  • 可以看到ShuaiLoss可以被注册到LOSSES
  • 其实,这里的LOSSES是BACKBONES NECKS HEADS LOSSES SEGMENTORS的总和

2、调用Shuai_loss

if __name__ == "__main__":
    print("call shuai_loss:")
    from mmseg.models import build_loss
    # 1.配置 dict
    loss = dict(type='ShuaiLoss',
                 loss_weight=1.0,
                 loss_name='loss_shuai')
    # 从注册器中构建
    shuai_loss = build_loss(loss)

    # 使用shuai loss
    pred = torch.Tensor([[0, 2, 3, 0], [0,2,3,0]])   # [2,4]
    target = torch.Tensor([[1, 1, 1, 0], [1,1,1,1]]) # [2,4]
    loss = shuai_loss(pred, target)
    print("loss:",loss)

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

BILLY BILLY

你的奖励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值