-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathEDiceLoss_loss.py
85 lines (69 loc) · 2.46 KB
/
EDiceLoss_loss.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
"""
Created on March 10, 2022.
EDiceLoss_loss.py
@ref: https://github.com/lescientifik/open_brats2020
Dice loss (multi label) tailored to Brats needs.
"""
import pdb
import torch
import torch.nn as nn
class EDiceLoss(nn.Module):
"""Dice loss tailored to Brats need.
"""
def __init__(self, do_sigmoid=True):
super(EDiceLoss, self).__init__()
self.do_sigmoid = do_sigmoid
self.labels = ["ET", "TC", "WT"]
self.setup_cuda()
def binary_dice(self, inputs, targets, label_index, metric_mode=False):
smooth = 1.
if self.do_sigmoid:
inputs = torch.sigmoid(inputs)
if metric_mode:
inputs = inputs > 0.5
if targets.sum() == 0:
print(f"No {self.labels[label_index]} for this patient")
if inputs.sum() == 0:
return torch.tensor(1., device=self.device)
else:
return torch.tensor(0., device=self.device)
# Threshold the pred
intersection = EDiceLoss.compute_intersection(inputs, targets)
if metric_mode:
dice = (2 * intersection) / ((inputs.sum() + targets.sum()) * 1.0)
else:
dice = (2 * intersection + smooth) / (inputs.pow(2).sum() + targets.pow(2).sum() + smooth)
if metric_mode:
return dice
return 1 - dice
@staticmethod
def compute_intersection(inputs, targets):
intersection = torch.sum(inputs * targets)
return intersection
def forward(self, inputs, target):
dice = 0
for i in range(target.shape[1]):
dice = dice + self.binary_dice(inputs[:, i, ...], target[:, i, ...], i)
final_dice = dice / target.shape[1]
return final_dice
def metric(self, inputs, target):
dices = []
for j in range(target.shape[0]):
dice = []
for i in range(target.shape[1]):
dice.append(self.binary_dice(inputs[j, i], target[j, i], i, True))
dices.append(dice)
return dices
def setup_cuda(self, cuda_device_id=0):
"""setup the device.
Parameters
----------
cuda_device_id: int
cuda device id
"""
if torch.cuda.is_available():
torch.backends.cudnn.fastest = True
torch.cuda.set_device(cuda_device_id)
self.device = torch.device('cuda')
else:
self.device = torch.device('cpu')