forked from babbu3682/SMART-Net
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlosses.py
271 lines (214 loc) · 11.1 KB
/
losses.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
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
from typing import Optional, List
import torch
from torch import nn
import torch.nn.functional as F
from utils import to_tensor
from torch.nn.modules.loss import _Loss
def soft_dice_score(output: torch.Tensor, target: torch.Tensor, smooth: float = 0.0, eps: float = 1e-7, dims=None,) -> torch.Tensor:
assert output.size() == target.size()
if dims is not None:
intersection = torch.sum(output * target, dim=dims)
cardinality = torch.sum(output + target, dim=dims)
else:
intersection = torch.sum(output * target)
cardinality = torch.sum(output + target)
dice_score = (2.0 * intersection + smooth) / (cardinality + smooth).clamp_min(eps)
return dice_score
class DiceLoss(_Loss):
def __init__(
self,
mode: str,
classes: Optional[List[int]] = None,
log_loss: bool = False,
from_logits: bool = True,
smooth: float = 0.0,
ignore_index: Optional[int] = None,
eps: float = 1e-7,
):
"""Dice loss for image segmentation task.
It supports binary, multiclass and multilabel cases
Args:
mode: Loss mode 'binary', 'multiclass' or 'multilabel'
classes: List of classes that contribute in loss computation. By default, all channels are included.
log_loss: If True, loss computed as `- log(dice_coeff)`, otherwise `1 - dice_coeff`
from_logits: If True, assumes input is raw logits
smooth: Smoothness constant for dice coefficient (a)
ignore_index: Label that indicates ignored pixels (does not contribute to loss)
eps: A small epsilon for numerical stability to avoid zero division error
(denominator will be always greater or equal to eps)
Shape
- **y_pred** - torch.Tensor of shape (N, C, H, W)
- **y_true** - torch.Tensor of shape (N, H, W) or (N, C, H, W)
Reference
https://github.com/BloodAxe/pytorch-toolbelt
"""
assert mode in {'binary', 'multilabel', 'multiclass'}
super(DiceLoss, self).__init__()
self.mode = mode
if classes is not None:
assert mode != 'binary', "Masking classes is not supported with mode=binary"
classes = to_tensor(classes, dtype=torch.long)
self.classes = classes
self.from_logits = from_logits
self.smooth = smooth
self.eps = eps
self.log_loss = log_loss
self.ignore_index = ignore_index
def forward(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> torch.Tensor:
assert y_true.size(0) == y_pred.size(0)
if self.from_logits:
# Apply activations to get [0..1] class probabilities
# Using Log-Exp as this gives more numerically stable result and does not cause vanishing gradient on
# extreme values 0 and 1
if self.mode == 'multiclass':
y_pred = y_pred.log_softmax(dim=1).exp()
else:
y_pred = F.logsigmoid(y_pred).exp()
bs = y_true.size(0)
num_classes = y_pred.size(1)
dims = (0, 2)
if self.mode == 'binary':
y_true = y_true.view(bs, 1, -1)
y_pred = y_pred.view(bs, 1, -1)
if self.ignore_index is not None:
mask = y_true != self.ignore_index
y_pred = y_pred * mask
y_true = y_true * mask
if self.mode == 'multiclass':
y_true = y_true.view(bs, -1)
y_pred = y_pred.view(bs, num_classes, -1)
if self.ignore_index is not None:
mask = y_true != self.ignore_index
y_pred = y_pred * mask.unsqueeze(1)
y_true = F.one_hot((y_true * mask).to(torch.long), num_classes) # N,H*W -> N,H*W, C
y_true = y_true.permute(0, 2, 1) * mask.unsqueeze(1) # H, C, H*W
else:
y_true = F.one_hot(y_true, num_classes) # N,H*W -> N,H*W, C
y_true = y_true.permute(0, 2, 1) # H, C, H*W
if self.mode == 'multilabel':
y_true = y_true.view(bs, num_classes, -1)
y_pred = y_pred.view(bs, num_classes, -1)
if self.ignore_index is not None:
mask = y_true != self.ignore_index
y_pred = y_pred * mask
y_true = y_true * mask
scores = self.compute_score(y_pred, y_true.type_as(y_pred), smooth=self.smooth, eps=self.eps, dims=dims)
if self.log_loss:
loss = -torch.log(scores.clamp_min(self.eps))
else:
loss = 1.0 - scores
# Dice loss is undefined for non-empty classes
# So we zero contribution of channel that does not have true pixels
# NOTE: A better workaround would be to use loss term `mean(y_pred)`
# for this case, however it will be a modified jaccard loss
mask = y_true.sum(dims) > 0
loss *= mask.to(loss.dtype)
if self.classes is not None:
loss = loss[self.classes]
return self.aggregate_loss(loss)
def aggregate_loss(self, loss):
return loss.mean()
def compute_score(self, output, target, smooth=0.0, eps=1e-7, dims=None) -> torch.Tensor:
return soft_dice_score(output, target, smooth, eps, dims)
class Dice_BCE_Loss(torch.nn.Module):
def __init__(self):
super().__init__()
self.loss_function_1 = DiceLoss(mode='binary', from_logits=True)
self.loss_function_2 = torch.nn.BCEWithLogitsLoss()
self.dice_weight = 1.0
self.bce_weight = 1.0
def forward(self, y_pred, y_true):
dice_loss = self.loss_function_1(y_pred, y_true)
bce_loss = self.loss_function_2(y_pred, y_true)
return self.dice_weight*dice_loss + self.bce_weight*bce_loss
class Consistency_Loss(torch.nn.Module):
def __init__(self):
super().__init__()
self.L2_loss = torch.nn.MSELoss()
self.maxpool = torch.nn.MaxPool2d(kernel_size=16, stride=16, padding=0)
self.avgpool = torch.nn.AvgPool2d(kernel_size=16, stride=16, padding=0)
def forward(self, y_cls, y_seg):
y_cls = torch.sigmoid(y_cls) # (B, C)
y_seg = torch.sigmoid(y_seg) # (B, C, H, W)
# We have to adjust the segmentation pred depending on classification pred
# ResNet50 uses four 2x2 maxpools and 1 global avgpool to extract classification pred. that is the same as 16x16 maxpool and 16x16 avgpool
y_seg = self.avgpool(self.maxpool(y_seg)).flatten(start_dim=1, end_dim=-1) # (B, C)
loss = self.L2_loss(y_seg, y_cls)
return loss
# To Do
# 1. using Contrastive Learning for Consistency_Loss
# 2. uncertainty for losses weights
###################################################################################
## Uptask Loss
class Uptask_Loss(torch.nn.Module):
def __init__(self, name='Up_SMART_Net'):
super().__init__()
self.loss_cls = torch.nn.BCEWithLogitsLoss()
self.loss_seg = Dice_BCE_Loss()
self.loss_rec = torch.nn.L1Loss()
self.loss_consist = Consistency_Loss()
self.name = name
self.cls_weight = 1.0
self.seg_weight = 1.0
self.rec_weight = 1.0
self.consist_weight = 0.5
# We will consider uncertainty loss weight...! (To Do...)
# if uncert:
# self.cls_weight = nn.Parameter(torch.tensor([1.0], requires_grad=True, device='cuda'))
# self.seg_weight = nn.Parameter(torch.tensor([1.0], requires_grad=True, device='cuda'))
# self.consist_weight = nn.Parameter(torch.tensor([1.0], requires_grad=True, device='cuda'))
# def cal_weighted_loss(self, loss, uncert_w):
# return torch.exp(-uncert_w)*loss + 0.5*uncert_w
def forward(self, cls_pred=None, seg_pred=None, rec_pred=None, cls_gt=None, seg_gt=None, rec_gt=None):
if self.name == 'Up_SMART_Net':
loss_cls = self.loss_cls(cls_pred, cls_gt)
loss_seg = self.loss_seg(seg_pred, seg_gt)
loss_rec = self.loss_rec(rec_pred, rec_gt)
loss_consist = self.loss_consist(y_cls=cls_pred, y_seg=seg_pred)
total = self.cls_weight*loss_cls + self.seg_weight*loss_seg + self.rec_weight*loss_rec + self.consist_weight*loss_consist
return total, {'CLS_Loss':(self.cls_weight*loss_cls).item(), 'SEG_Loss':(self.seg_weight*loss_seg).item(), 'REC_Loss':(self.rec_weight*loss_rec).item(), 'Consist_Loss':(self.consist_weight*loss_consist).item()}
elif self.name == 'Up_SMART_Net_Dual_CLS_SEG':
loss_cls = self.loss_cls(cls_pred, cls_gt)
loss_seg = self.loss_seg(seg_pred, seg_gt)
total = self.cls_weight*loss_cls + self.seg_weight*loss_seg
return total, {'CLS_Loss':(self.cls_weight*loss_cls).item(), 'SEG_Loss':(self.seg_weight*loss_seg).item()}
elif self.name == 'Up_SMART_Net_Dual_CLS_REC':
loss_cls = self.loss_cls(cls_pred, cls_gt)
loss_rec = self.loss_rec(rec_pred, rec_gt)
total = self.cls_weight*loss_cls + self.rec_weight*loss_rec
return total, {'CLS_Loss':(self.cls_weight*loss_cls).item(), 'REC_Loss':(self.rec_weight*loss_rec).item()}
elif self.name == 'Up_SMART_Net_Dual_SEG_REC':
loss_seg = self.loss_seg(seg_pred, seg_gt)
loss_rec = self.loss_rec(rec_pred, rec_gt)
total = self.seg_weight*loss_seg + self.rec_weight*loss_rec
return total, {'SEG_Loss':(self.seg_weight*loss_seg).item(), 'REC_Loss':(self.rec_weight*loss_rec).item()}
elif self.name == 'Up_SMART_Net_Single_CLS':
loss_cls = self.loss_cls(cls_pred, cls_gt)
total = self.cls_weight*loss_cls
return total, {'CLS_Loss':(self.cls_weight*loss_cls).item()}
elif self.name == 'Up_SMART_Net_Single_SEG':
loss_seg = self.loss_seg(seg_pred, seg_gt)
total = self.seg_weight*loss_seg
return total, {'SEG_Loss':(self.seg_weight*loss_seg).item()}
elif self.name == 'Up_SMART_Net_Single_REC':
loss_rec = self.loss_rec(rec_pred, rec_gt)
total = self.rec_weight*loss_rec
return total, {'REC_Loss':(self.rec_weight*loss_rec).item()}
else :
raise KeyError("Wrong Loss name `{}`".format(self.name))
## Downtask Loss
class Downtask_Loss(torch.nn.Module):
def __init__(self, name='Down_SMART_Net_CLS'):
super().__init__()
self.loss_cls = torch.nn.BCEWithLogitsLoss()
self.loss_seg = Dice_BCE_Loss()
self.name = name
def forward(self, cls_pred=None, seg_pred=None, cls_gt=None, seg_gt=None):
if self.name == 'Down_SMART_Net_CLS':
loss_cls = self.loss_cls(cls_pred, cls_gt)
return loss_cls, {'CLS_Loss':loss_cls.item()}
elif self.name == 'Down_SMART_Net_SEG':
loss_seg = self.loss_seg(seg_pred, seg_gt)
return loss_seg, {'SEG_Loss':loss_seg.item()}
else :
raise KeyError("Wrong Loss name `{}`".format(self.name))