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∣+∣B∣2∣A∩B∣
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=1−DiceCoefficient
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