语义分割损失函数系列(3):Dice损失

16 篇文章 0 订阅
12 篇文章 1 订阅

Dice损失在医学图像分割任务中使用得极多,用于度量两个集合得相似性,dice系数的定义如下:
D i c e C o e f f i c i e n t = 2 ∣ A ∩ B ∣ ∣ A ∣ + ∣ B ∣ Dice Coefficient = \frac{2|A\cap B|}{|A| + |B|} DiceCoefficient=A+B2AB

Dice 损失等于1-dice系数

D i c e l o s s = 1 − D i c e C o e f f i c i e n t Dice loss = 1-Dice Coefficient Diceloss=1DiceCoefficient

Pytorch实现的dice损失代码如下:

'''
Author: weifeng liu
Date: 2022-04-13 22:44:33
LastEditTime: 2022-04-14 14:29:34
LastEditors: Please set LastEditors
Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
FilePath: /BIBM-project/segmentation_pipeline/loss/dice.py
'''
import numpy
import torch
import torch.nn as nn
import torch.nn.functional as F

class DiceLoss(nn.Module):
    def __init__(self, weight=None, size_average=True):
        super(DiceLoss, self).__init__()

    def forward(self, inputs, targets, smooth=1):
        """
        Args:
            inputs (tensor): model outputs
            targets (tensor): image labels
            smooth (int, optional): smooth factor. Defaults to 1.

        Returns:
            loss 
        """
        #comment out if your model contains a sigmoid or equivalent activation layer
        inputs = F.sigmoid(inputs)       
        
        #flatten label and prediction tensors
        inputs = inputs.view(-1)
        targets = targets.view(-1)
        
        intersection = (inputs * targets).sum()                            
        dice = (2.*intersection + smooth)/(inputs.sum() + targets.sum() + smooth)  
        
        return 1 - dice
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值