-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlosses.py
189 lines (141 loc) · 5.4 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
#Import the required libraries
import numpy as np
import torch
from torch.autograd import Variable
from metrics import*
import torch.nn as nn
import numpy as np
import torch
import torch.nn as nn
from torch.nn import functional as F
class FocalLoss(nn.Module):
def __init__(self, alpha=0.8, gamma=2, logits=False, reduce=True):
super(FocalLoss, self).__init__()
self.alpha = alpha
self.gamma = gamma
self.logits = logits
self.reduce = reduce
def forward(self, inputs, targets):
if self.logits:
BCE_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduce=False)
else:
BCE_loss = F.binary_cross_entropy(inputs, targets, reduce=False)
pt = torch.exp(-BCE_loss)
F_loss = self.alpha * (1-pt)**self.gamma * BCE_loss
if self.reduce:
return torch.mean(F_loss)
else:
return F_loss
class JaccardLoss(nn.Module):
__name__ = 'jaccard_loss'
def __init__(self, eps=1e-7, activation='sigmoid'):
super().__init__()
self.activation = activation
self.eps = eps
def forward(self, y_pr, y_gt):
return 1 - jaccard(y_pr, y_gt, eps=self.eps, threshold=None, activation=self.activation)
class DiceLoss(nn.Module):
__name__ = 'dice_loss'
def __init__(self, eps=1e-7, activation='sigmoid'):
super().__init__()
self.activation = activation
self.eps = eps
def forward(self, y_pr, y_gt):
return 1 - f_score(y_pr, y_gt, beta=1., eps=self.eps, threshold=None, activation=self.activation)
class BCEJaccardLoss(JaccardLoss):
__name__ = 'bce_jaccard_loss'
def __init__(self, eps=1e-7, activation='sigmoid'):
super().__init__(eps, activation)
self.bce = nn.BCEWithLogitsLoss(reduction='mean')
def forward(self, y_pr, y_gt):
jaccard = super().forward(y_pr, y_gt)
bce = self.bce(y_pr, y_gt)
return jaccard + bce
class BCEFocalLoss(DiceLoss, FocalLoss):
__name__ = 'bce_focal_loss'
def __init__(self, eps=1e-7, activation='sigmoid'):
super().__init__(eps, activation)
self.bce = nn.BCEWithLogitsLoss(reduction='mean')
def forward(self, y_pr, y_gt):
dice = super().forward(y_pr, y_gt)
f_loss = super().forward(y_pr, y_gt)
# bce = self.bce(y_pr, y_gt)
return dice + f_loss
class BCEDiceLoss(DiceLoss):
__name__ = 'bce_dice_loss'
def __init__(self, eps=1e-7, activation='sigmoid'):
super().__init__(eps, activation)
self.bce = nn.BCEWithLogitsLoss(reduction='mean')
def forward(self, y_pr, y_gt):
dice = super().forward(y_pr, y_gt)
bce = self.bce(y_pr, y_gt)
return 0.4*dice + 0.6*bce
class BCEFocalLoss(DiceLoss, FocalLoss):
__name__ = 'bce_focal_loss'
def __init__(self, eps=1e-7, activation='sigmoid'):
super().__init__(eps, activation)
self.bce = nn.BCEWithLogitsLoss(reduction='mean')
def forward(self, y_pr, y_gt):
dice = super().forward(y_pr, y_gt)
f_loss = super().forward(y_pr, y_gt)
# bce = self.bce(y_pr, y_gt)
return dice + f_loss
def iou(pr, gt, eps=1e-7, threshold=None, activation='sigmoid'):
"""
Source:
https://github.com/catalyst-team/catalyst/
Args:
pr (torch.Tensor): A list of predicted elements
gt (torch.Tensor): A list of elements that are to be predicted
eps (float): epsilon to avoid zero division
threshold: threshold for outputs binarization
Returns:
float: IoU (Jaccard) score
"""
if activation is None or activation == "none":
activation_fn = lambda x: x
elif activation == "sigmoid":
activation_fn = torch.nn.Sigmoid()
elif activation == "softmax2d":
activation_fn = torch.nn.Softmax2d()
else:
raise NotImplementedError(
"Activation implemented for sigmoid and softmax2d"
)
pr = activation_fn(pr)
if threshold is not None:
pr = (pr > threshold).float()
intersection = torch.sum(gt * pr)
union = torch.sum(gt) + torch.sum(pr) - intersection + eps
return (intersection + eps) / union
jaccard = iou
def f_score(pr, gt, beta=1, eps=1e-7, threshold=None, activation='sigmoid'):
"""
Args:
pr (torch.Tensor): A list of predicted elements
gt (torch.Tensor): A list of elements that are to be predicted
beta (float): positive constant
eps (float): epsilon to avoid zero division
threshold: threshold for outputs binarization
Returns:
float: F score
"""
if activation is None or activation == "none":
activation_fn = lambda x: x
elif activation == "sigmoid":
activation_fn = torch.nn.Sigmoid()
elif activation == "softmax2d":
activation_fn = torch.nn.Softmax2d()
else:
raise NotImplementedError(
"Activation implemented for sigmoid and softmax2d"
)
pr = activation_fn(pr)
if threshold is not None:
pr = (pr > threshold).float()
tp = torch.sum(gt * pr)
fp = torch.sum(pr) - tp
fn = torch.sum(gt) - tp
score = ((1 + beta ** 2) * tp + eps) \
/ ((1 + beta ** 2) * tp + beta ** 2 * fn + fp + eps)
return score