-
Notifications
You must be signed in to change notification settings - Fork 4
/
cbdice_loss.py
153 lines (117 loc) · 6.42 KB
/
cbdice_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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
import torch
from monai.transforms import distance_transform_edt
from nnunetv2.training.loss.skeletonize import Skeletonize
from nnunetv2.training.loss.soft_skeleton import SoftSkeletonize
class SoftcbDiceLoss(torch.nn.Module):
def __init__(self, iter_=10, smooth = 1.):
super(SoftcbDiceLoss, self).__init__()
self.smooth = smooth
# Topology-preserving skeletonization: https://github.com/martinmenten/skeletonization-for-gradient-based-optimization
self.t_skeletonize = Skeletonize(probabilistic=False, simple_point_detection='EulerCharacteristic')
# Morphological skeletonization: https://github.com/jocpae/clDice/tree/master/cldice_loss/pytorch
self.m_skeletonize = SoftSkeletonize(num_iter=iter_)
def forward(self, y_pred, y_true, t_skeletonize_flage=True):
if len(y_true.shape) == 4:
dim = 2
elif len(y_true.shape) == 5:
dim = 3
else:
raise ValueError("y_true should be 4D or 5D tensor.")
y_pred_fore = y_pred[:, 1:]
y_pred_fore = torch.max(y_pred_fore, dim=1, keepdim=True)[0] # C foreground channels -> 1 channel
y_pred_binary = torch.cat([y_pred[:, :1], y_pred_fore], dim=1)
y_prob_binary = torch.softmax(y_pred_binary, 1)
y_pred_prob = y_prob_binary[:, 1] # predicted probability map of foreground
with torch.no_grad():
y_true = torch.where(y_true > 0, 1, 0).squeeze(1).float() # ground truth of foreground
y_pred_hard = (y_pred_prob > 0.5).float()
if t_skeletonize_flage:
skel_pred_hard = self.t_skeletonize(y_pred_hard.unsqueeze(1)).squeeze(1)
skel_true = self.t_skeletonize(y_true.unsqueeze(1)).squeeze(1)
else:
skel_pred_hard = self.m_skeletonize(y_pred_hard.unsqueeze(1)).squeeze(1)
skel_true = self.m_skeletonize(y_true.unsqueeze(1)).squeeze(1)
skel_pred_prob = skel_pred_hard * y_pred_prob
q_vl, q_slvl, q_sl = get_weights(y_true, skel_true, dim, prob_flag=False)
q_vp, q_spvp, q_sp = get_weights(y_pred_prob, skel_pred_prob, dim, prob_flag=True)
w_tprec = (torch.sum(torch.multiply(q_sp, q_vl))+self.smooth)/(torch.sum(combine_tensors(q_spvp, q_slvl, q_sp))+self.smooth)
w_tsens = (torch.sum(torch.multiply(q_sl, q_vp))+self.smooth)/(torch.sum(combine_tensors(q_slvl, q_spvp, q_sl))+self.smooth)
cb_dice_loss = - 2.0 * (w_tprec * w_tsens) / (w_tprec + w_tsens)
return cb_dice_loss
class SoftclMDiceLoss(torch.nn.Module):
def __init__(self, iter_=10, smooth = 1.):
super(SoftclMDiceLoss, self).__init__()
self.smooth = smooth
# Topology-preserving skeletonization: https://github.com/martinmenten/skeletonization-for-gradient-based-optimization
self.t_skeletonize = Skeletonize(probabilistic=False, simple_point_detection='EulerCharacteristic')
# Morphological skeletonization: https://github.com/jocpae/clDice/tree/master/cldice_loss/pytorch
self.m_skeletonize = SoftSkeletonize(num_iter=iter_)
def forward(self, y_pred, y_true, t_skeletonize_flage=True):
if len(y_true.shape) == 4:
dim = 2
elif len(y_true.shape) == 5:
dim = 3
else:
raise ValueError("y_true should be 4D or 5D tensor.")
y_pred_fore = y_pred[:, 1:]
y_pred_fore = torch.max(y_pred_fore, dim=1, keepdim=True)[0] # C foreground channels -> 1 channel
y_pred_binary = torch.cat([y_pred[:, :1], y_pred_fore], dim=1)
y_prob_binary = torch.softmax(y_pred_binary, 1)
y_pred_prob = y_prob_binary[:, 1] # predicted probability map of foreground
with torch.no_grad():
y_true = torch.where(y_true > 0, 1, 0).squeeze(1).float() # ground truth of foreground
y_pred_hard = (y_pred_prob > 0.5).float()
if t_skeletonize_flage:
skel_pred_hard = self.t_skeletonize(y_pred_hard.unsqueeze(1)).squeeze(1)
skel_true = self.t_skeletonize(y_true.unsqueeze(1)).squeeze(1)
else:
skel_pred_hard = self.m_skeletonize(y_pred_hard.unsqueeze(1)).squeeze(1)
skel_true = self.m_skeletonize(y_true.unsqueeze(1)).squeeze(1)
skel_pred_prob = skel_pred_hard * y_pred_prob
q_vl, q_slvl, _ = get_weights(y_true, skel_true, dim, prob_flag=False)
q_vp, q_spvp, _ = get_weights(y_pred_prob, skel_pred_prob, dim, prob_flag=True)
q_sl = skel_true
q_sp = skel_pred_prob
w_tprec = (torch.sum(torch.multiply(q_sp, q_vl))+self.smooth)/(torch.sum(combine_tensors(q_spvp, q_slvl, q_sp))+self.smooth)
w_tsens = (torch.sum(torch.multiply(q_sl, q_vp))+self.smooth)/(torch.sum(combine_tensors(q_slvl, q_spvp, q_sl))+self.smooth)
cl_m_dice_loss = - 2.0 * (w_tprec * w_tsens) / (w_tprec + w_tsens)
return cl_m_dice_loss
def combine_tensors(A, B, C):
A_C = A * C
B_C = B * C
D = B_C.clone()
mask_AC = (A != 0) & (B == 0)
D[mask_AC] = A_C[mask_AC]
return D
def get_weights(mask_input, skel_input, dim, prob_flag=True):
if prob_flag:
mask_prob = mask_input
skel_prob = skel_input
mask = (mask_prob > 0.5).int()
skel = (skel_prob > 0.5).int()
else:
mask = mask_input
skel = skel_input
distances = distance_transform_edt(mask).float()
smooth = 1e-7
distances[mask == 0] = 0
skel_radius = torch.zeros_like(distances, dtype=torch.float32)
skel_radius[skel == 1] = distances[skel == 1]
dist_map_norm = torch.zeros_like(distances, dtype=torch.float32)
skel_R_norm = torch.zeros_like(skel_radius, dtype=torch.float32)
for i in range(skel_radius.shape[0]):
distances_i = distances[i]
skel_i = skel_radius[i]
skel_radius_max = max(skel_i.max(), 1)
distances_i[distances_i > skel_radius_max] = skel_radius_max
dist_map_norm[i] = distances_i / skel_radius_max
skel_R_norm[i] = skel_i / skel_radius_max
if dim == 2:
I_norm = (1 + smooth) / (skel_R_norm + smooth) # weight for skel
else:
I_norm = (1 + smooth) / (skel_R_norm ** 2 + smooth)
I_norm[skel == 0] = 0 # 0 for non-skeleton pixels
if prob_flag:
return dist_map_norm * mask_prob, skel_R_norm * mask_prob, I_norm * skel_prob
else:
return dist_map_norm * mask, skel_R_norm * mask, I_norm * skel