-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlosses.py
More file actions
328 lines (278 loc) · 11.2 KB
/
losses.py
File metadata and controls
328 lines (278 loc) · 11.2 KB
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import torch
from torch.nn import functional as F
import numpy as np
from scipy.ndimage import distance_transform_edt as distance
from skimage import segmentation as skimage_seg
def dice_loss(score, target):
target = target.float()
smooth = 1e-5
intersect = torch.sum(score * target)
y_sum = torch.sum(target * target)
z_sum = torch.sum(score * score)
loss = (2 * intersect + smooth) / (z_sum + y_sum + smooth)
loss = 1 - loss
return loss
def dice_loss1(score, target):
# non-square
target = target.float()
smooth = 1e-5
intersect = torch.sum(score * target)
y_sum = torch.sum(target)
z_sum = torch.sum(score)
loss = (2 * intersect + smooth) / (z_sum + y_sum + smooth)
loss = 1 - loss
return loss
def iou_loss(score, target):
target = target.float()
smooth = 1e-5
tp_sum = torch.sum(score * target)
fp_sum = torch.sum(score * (1-target))
fn_sum = torch.sum((1-score) * target)
loss = (tp_sum + smooth) / (tp_sum + fp_sum + fn_sum + smooth)
loss = 1 - loss
return loss
def entropy_loss(p,C=2):
## p N*C*W*H*D
y1 = -1*torch.sum(p*torch.log(p+1e-6), dim=1)/torch.tensor(np.log(C)).cuda()
ent = torch.mean(y1)
return ent
def softmax_dice_loss(input_logits, target_logits):
"""Takes softmax on both sides and returns MSE loss
Note:
- Returns the sum over all examples. Divide by the batch size afterwards
if you want the mean.
- Sends gradients to inputs but not the targets.
"""
assert input_logits.size() == target_logits.size()
input_softmax = F.softmax(input_logits, dim=1)
target_softmax = F.softmax(target_logits, dim=1)
n = input_logits.shape[1]
dice = 0
for i in range(0, n):
dice += dice_loss1(input_softmax[:, i], target_softmax[:, i])
mean_dice = dice / n
return mean_dice
def entropy_loss_map(p, C=2):
ent = -1*torch.sum(p * torch.log(p + 1e-6), dim=1, keepdim=True)/torch.tensor(np.log(C)).cuda()
return ent
def softmax_mse_loss(input_logits, target_logits):
"""Takes softmax on both sides and returns MSE loss
Note:
- Returns the sum over all examples. Divide by the batch size afterwards
if you want the mean.
- Sends gradients to inputs but not the targets.
"""
assert input_logits.size() == target_logits.size()
input_softmax = F.softmax(input_logits, dim=1)
target_softmax = F.softmax(target_logits, dim=1)
mse_loss = (input_softmax-target_softmax)**2
return mse_loss
def softmax_kl_loss(input_logits, target_logits):
"""Takes softmax on both sides and returns KL divergence
Note:
- Returns the sum over all examples. Divide by the batch size afterwards
if you want the mean.
- Sends gradients to inputs but not the targets.
"""
assert input_logits.size() == target_logits.size()
input_log_softmax = F.log_softmax(input_logits, dim=1)
target_softmax = F.softmax(target_logits, dim=1)
# return F.kl_div(input_log_softmax, target_softmax)
kl_div = F.kl_div(input_log_softmax, target_softmax, reduction='none')
# mean_kl_div = torch.mean(0.2*kl_div[:,0,...]+0.8*kl_div[:,1,...])
return kl_div
def symmetric_mse_loss(input1, input2):
"""Like F.mse_loss but sends gradients to both directions
Note:
- Returns the sum over all examples. Divide by the batch size afterwards
if you want the mean.
- Sends gradients to both input1 and input2.
"""
assert input1.size() == input2.size()
return torch.mean((input1 - input2)**2)
def scc_loss(cos_sim,tau,lb_center_12_bg,lb_center_12_la, un_center_12_bg, un_center_12_la):
loss_intra_bg = torch.exp((cos_sim(lb_center_12_bg, un_center_12_bg))/tau)
loss_intra_la = torch.exp((cos_sim(lb_center_12_la, un_center_12_la))/tau)
loss_inter_bg_la = torch.exp((cos_sim(lb_center_12_bg, un_center_12_la))/tau)
loss_inter_la_bg = torch.exp((cos_sim(lb_center_12_la, un_center_12_bg))/tau)
loss_contrast_bg = -torch.log(loss_intra_bg)+torch.log(loss_inter_bg_la)
loss_contrast_la = -torch.log(loss_intra_la)+torch.log(loss_inter_la_bg)
loss_contrast = torch.mean(loss_contrast_bg+loss_contrast_la)
return loss_contrast
def compute_sdf01(segmentation):
"""
compute the signed distance map of binary mask
input: segmentation, shape = (batch_size, class, x, y, z)
output: the Signed Distance Map (SDM)
sdm(x) = 0; x in segmentation boundary
-inf|x-y|; x in segmentation
+inf|x-y|; x out of segmentation
"""
# print(type(segmentation), segmentation.shape)
segmentation = segmentation.astype(np.uint8)
if len(segmentation.shape) == 4: # 3D image
segmentation = np.expand_dims(segmentation, 1)
normalized_sdf = np.zeros(segmentation.shape)
if segmentation.shape[1] == 1:
dis_id = 0
else:
dis_id = 1
for b in range(segmentation.shape[0]): # batch size
for c in range(dis_id, segmentation.shape[1]): # class_num
# ignore background
posmask = segmentation[b][c]
negmask = ~posmask
posdis = distance(posmask)
negdis = distance(negmask)
boundary = skimage_seg.find_boundaries(posmask, mode='inner').astype(np.uint8)
sdf = negdis/np.max(negdis)/2 - posdis/np.max(posdis)/2 + 0.5
sdf[boundary>0] = 0.5
normalized_sdf[b][c] = sdf
return normalized_sdf
def compute_sdf1_1(segmentation):
"""
compute the signed distance map of binary mask
input: segmentation, shape = (batch_size, class, x, y, z)
output: the Signed Distance Map (SDM)
sdm(x) = 0; x in segmentation boundary
-inf|x-y|; x in segmentation
+inf|x-y|; x out of segmentation
"""
# print(type(segmentation), segmentation.shape)
segmentation = segmentation.astype(np.uint8)
if len(segmentation.shape) == 4: # 3D image
segmentation = np.expand_dims(segmentation, 1)
normalized_sdf = np.zeros(segmentation.shape)
if segmentation.shape[1] == 1:
dis_id = 0
else:
dis_id = 1
for b in range(segmentation.shape[0]): # batch size
for c in range(dis_id, segmentation.shape[1]): # class_num
# ignore background
posmask = segmentation[b][c]
negmask = ~posmask
posdis = distance(posmask)
negdis = distance(negmask)
boundary = skimage_seg.find_boundaries(posmask, mode='inner').astype(np.uint8)
sdf = negdis/np.max(negdis) - posdis/np.max(posdis)
sdf[boundary>0] = 0
normalized_sdf[b][c] = sdf
return normalized_sdf
def compute_fore_dist(segmentation):
"""
compute the foreground of binary mask
input: segmentation, shape = (batch_size, class, x, y, z)
output: the Signed Distance Map (SDM)
sdm(x) = 0; x in segmentation boundary
-inf|x-y|; x in segmentation
+inf|x-y|; x out of segmentation
"""
# print(type(segmentation), segmentation.shape)
segmentation = segmentation.astype(np.uint8)
if len(segmentation.shape) == 4: # 3D image
segmentation = np.expand_dims(segmentation, 1)
normalized_sdf = np.zeros(segmentation.shape)
if segmentation.shape[1] == 1:
dis_id = 0
else:
dis_id = 1
for b in range(segmentation.shape[0]): # batch size
for c in range(dis_id, segmentation.shape[1]): # class_num
# ignore background
posmask = segmentation[b][c]
posdis = distance(posmask)
normalized_sdf[b][c] = posdis/np.max(posdis)
return normalized_sdf
def sum_tensor(inp, axes, keepdim=False):
axes = np.unique(axes).astype(int)
if keepdim:
for ax in axes:
inp = inp.sum(int(ax), keepdim=True)
else:
for ax in sorted(axes, reverse=True):
inp = inp.sum(int(ax))
return inp
def AAAI_sdf_loss(net_output, gt):
"""
net_output: net logits; shape=(batch_size, class, x, y, z)
gt: ground truth; (shape (batch_size, 1, x, y, z) OR (batch_size, x, y, z))
"""
smooth = 1e-5
axes = tuple(range(2, len(net_output.size())))
shp_x = net_output.shape
shp_y = gt.shape
with torch.no_grad():
if len(shp_x) != len(shp_y):
gt = gt.view((shp_y[0], 1, *shp_y[1:]))
if all([i == j for i, j in zip(net_output.shape, gt.shape)]):
# if this is the case then gt is probably already a one hot encoding
y_onehot = gt
else:
gt = gt.long()
y_onehot = torch.zeros(shp_x)
if net_output.device.type == "cuda":
y_onehot = y_onehot.cuda(net_output.device.index)
y_onehot.scatter_(1, gt, 1)
gt_sdm_npy = compute_sdf1_1(y_onehot.cpu().numpy())
gt_sdm = torch.from_numpy(gt_sdm_npy).float().cuda(net_output.device.index)
intersect = sum_tensor(net_output * gt_sdm, axes, keepdim=False)
pd_sum = sum_tensor(net_output ** 2, axes, keepdim=False)
gt_sum = sum_tensor(gt_sdm ** 2, axes, keepdim=False)
L_product = (intersect + smooth) / (intersect + pd_sum + gt_sum)
# print('L_product.shape', L_product.shape) (4,2)
L_SDF_AAAI = - L_product.mean() + torch.norm(net_output - gt_sdm, 1)/torch.numel(net_output)
return L_SDF_AAAI
def sdf_kl_loss(net_output, gt):
"""
net_output: net logits; shape=(batch_size, class, x, y, z)
gt: ground truth; (shape (batch_size, 1, x, y, z) OR (batch_size, x, y, z))
"""
smooth = 1e-5
axes = tuple(range(2, len(net_output.size())))
shp_x = net_output.shape
shp_y = gt.shape
with torch.no_grad():
if len(shp_x) != len(shp_y):
gt = gt.view((shp_y[0], 1, *shp_y[1:]))
if all([i == j for i, j in zip(net_output.shape, gt.shape)]):
# if this is the case then gt is probably already a one hot encoding
y_onehot = gt
else:
gt = gt.long()
y_onehot = torch.zeros(shp_x)
if net_output.device.type == "cuda":
y_onehot = y_onehot.cuda(net_output.device.index)
y_onehot.scatter_(1, gt, 1)
# print('y_onehot.shape', y_onehot.shape)
gt_sdf_npy = compute_sdf(y_onehot.cpu().numpy())
gt_sdf = torch.from_numpy(gt_sdf_npy+smooth).float().cuda(net_output.device.index)
# print('net_output, gt_sdf', net_output.shape, gt_sdf.shape)
# exit()
sdf_kl_loss = F.kl_div(net_output, gt_sdf[:,1:2,...], reduction='batchmean')
return sdf_kl_loss
def weighted_ce_loss(net_output, gt):
n_dims = gt.shape[-1]
soft_pred = F.softmax(net_output)
loss = 0.
for i in range(n_dims):
gti = gt[:,i,:,:,:]
predi = soft_pred[:,i,:,:,:]
weighted = 1-(torch.sum(gti)/torch.sum(gt))
loss = loss -torch.mean(weighted*gti*torch.log(torch.clip_by_value(predi, 0.005, 1)))
return loss
def focal_loss(net_output, gt):
n_dims = net_output.shape[1]
soft_pred = F.softmax(net_output)
gt = F.one_hot(gt)#cls channel在最后一维
#print(gt.shape)
#gt = gt.transpose(1,4)
print(gt.shape)
print(soft_pred.shape)
loss = 0.
for i in range(n_dims):
gti = gt[:,:,:,:,i]
predi = soft_pred[:,i,:,:,:]
focal_loss=torch.pow( (1-predi), 4, name=None)
loss = loss -torch.mean(focal_loss*gti*torch.log(predi))
return loss