File size: 7,664 Bytes
8bd3ef8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Copyright (c) 2023 Image Processing Research Group of University Federico II of Naples ('GRIP-UNINA').
#
# All rights reserved.
# This work should only be used for nonprofit purposes.
#
# By downloading and/or using any of these files, you implicitly agree to all the
# terms of the license, as specified in the document LICENSE.txt
# (included in this package) and online at
# http://www.grip.unina.it/download/LICENSE_OPEN.txt

"""
Created in September 2022
@author: fabrizio.guillaro
"""

import torch
import torch.nn as nn
from torch.nn import functional as F



class CrossEntropy(nn.Module):
    def __init__(self, ignore_label=-1, weight=None):
        super(CrossEntropy, self).__init__()
        self.ignore_label = ignore_label
        self.criterion = nn.CrossEntropyLoss(weight=weight, 
                                             ignore_index=ignore_label)

    def forward(self, score, target):        
        ph, pw = score.size(2), score.size(3)
        h, w = target.size(1), target.size(2)
        if ph != h or pw != w:
            score = F.upsample(
                    input=score, size=(h, w), mode='bilinear')

        loss = self.criterion(score, target)
        return loss

    
    
class DiceLoss(nn.Module):
    def __init__(self, ignore_label=-1, smooth=1, exponent=2): #because padding adds -1 to the targets
        super(DiceLoss, self).__init__()  
        self.ignore_index = ignore_label
        self.smooth = smooth
        self.exponent = exponent
        
    def dice_loss(self, pred, target, valid_mask):
        assert pred.shape[0] == target.shape[0]
        total_loss = 0
        num_classes = pred.shape[1]
        for i in range(num_classes):
            if i != self.ignore_index:
                dice_loss = self.binary_dice_loss(
                    pred[:, i],
                    target[..., i],
                    valid_mask=valid_mask,)
                total_loss += dice_loss
        return total_loss / num_classes

    def binary_dice_loss(self, pred, target, valid_mask):
        assert pred.shape[0] == target.shape[0]
        pred = pred.reshape(pred.shape[0], -1)
        target = target.reshape(target.shape[0], -1)
        valid_mask = valid_mask.reshape(valid_mask.shape[0], -1)

        num = torch.sum(torch.mul(pred, target) * valid_mask, dim=1) * 2 + self.smooth
        den = torch.sum(pred.pow(self.exponent)*valid_mask + target.pow(self.exponent)*valid_mask, dim=1) + max(self.smooth, 1e-5)
        
        dice = num / den
        dice = torch.mean(dice)
        return 1 - dice
        
    def forward(self, score, target):
        ph, pw = score.size(2), score.size(3)
        h, w = target.size(1), target.size(2)
        if ph != h or pw != w:
            score = F.upsample(
                    input=score, size=(h, w), mode='bilinear')
        
        score = F.softmax(score,dim=1)
        num_classes = score.shape[1]
        
        one_hot_target = F.one_hot(
            torch.clamp(target.long(), 0, num_classes - 1),
            num_classes=num_classes)
        valid_mask = (target != self.ignore_index).long()
        
        loss = self.dice_loss(score, one_hot_target, valid_mask)
        return loss
    

class BinaryDiceLoss(nn.Module):
    def __init__(self, smooth=1, exponent=2, ignore_label=-1): #because padding adds -1 to the targets
        super(BinaryDiceLoss, self).__init__()  
        self.ignore_index = ignore_label
        self.smooth = smooth
        self.exponent = exponent

    def binary_dice_loss(self, pred, target, valid_mask):
        assert pred.shape[0] == target.shape[0]
        pred = pred.reshape(pred.shape[0], -1)
        target = target.reshape(target.shape[0], -1)
        valid_mask = valid_mask.reshape(valid_mask.shape[0], -1)

        num = torch.sum(torch.mul(pred, target) * valid_mask, dim=1) * 2 + self.smooth
        den = torch.sum(pred.pow(self.exponent)*valid_mask + target.pow(self.exponent)*valid_mask, dim=1) + max(self.smooth, 1e-5)
        
        dice = num / den
        dice = torch.mean(dice)
        return 1 - dice
        
    def forward(self, score, target):
        ph, pw = score.size(2), score.size(3)
        h, w = target.size(1), target.size(2)
        if ph != h or pw != w:
            score = F.upsample(
                    input=score, size=(h, w), mode='bilinear')
        
        score = F.softmax(score,dim=1)
        num_classes = score.shape[1]
        
        one_hot_target = F.one_hot(
            torch.clamp(target.long(), 0, num_classes - 1),
            num_classes=num_classes)
        valid_mask = (target != self.ignore_index).long()
        
        loss = self.binary_dice_loss(
                    score[:, 1],
                    one_hot_target[..., 1],
                    valid_mask)
        return loss
    

class DiceEntropyLoss(nn.Module):
    def __init__(self, smooth=1, exponent=2, ignore_label=-1, weight=None): #because padding adds -1 to the targets
        super(DiceEntropyLoss, self).__init__()  
        self.ignore_label = ignore_label
        self.smooth = smooth
        self.exponent = exponent
        self.cross_entropy = nn.CrossEntropyLoss(weight=weight, 
                                             ignore_index=ignore_label)
    
    def binary_dice_loss(self, pred, target, valid_mask):
        print(pred.shape, target.shape, "this is second list")
        assert pred.shape[0] == target.shape[0]
        pred = pred.reshape(pred.shape[0], -1)
        target = target.reshape(target.shape[0], -1)
        valid_mask = valid_mask.reshape(valid_mask.shape[0], -1)
        
        # print(pred.shape, target.shape)
        num = torch.sum(torch.mul(pred, target) * valid_mask, dim=1) * 2 + self.smooth
        den = torch.sum(pred.pow(self.exponent)*valid_mask + target.pow(self.exponent)*valid_mask, dim=1) + max(self.smooth, 1e-5)
        
        dice = num / den
        dice = torch.mean(dice)
        return 1 - dice
        
    def forward(self, score, target):
        ph, pw = score.size(2), score.size(3)
        h, w = target.size(1), target.size(2)
        # if ph != h or pw != w:
        #     score = F.upsample(
        #             input=score, size=(h, w), mode='bilinear')
        CE_loss   = self.cross_entropy(score, target)
        
        
        score = F.softmax(score,dim=1)
        num_classes = score.shape[1]
        
        one_hot_target = F.one_hot(
            torch.clamp(target.long(), 0, num_classes - 1),
            num_classes=num_classes)
        valid_mask = (target != self.ignore_label).long()
        # print(score.shape,one_hot_target.shape)
        dice_loss = self.binary_dice_loss(
                    score[:, 1],
                    one_hot_target[:,1][..., 1],
                    valid_mask)

        return 0.3*CE_loss + 0.7*dice_loss



    
class FocalLoss(nn.Module):

    def __init__(self, alpha=0.25, gamma=2., ignore_label=-1):  #alpha 0.25, gamma=2.
        super(FocalLoss, self).__init__()
        self.alpha=alpha
        self.gamma= gamma
        self.criterion = nn.CrossEntropyLoss(ignore_index=ignore_label, reduction="none")
       
    def forward(self, score, target):  
        ph, pw = score.size(2), score.size(3)
        h, w = target.size(1), target.size(2)
        if ph != h or pw != w:
            score = F.upsample(
                    input=score, size=(h, w), mode='bilinear')
            
        ce_loss = self.criterion(score, target)
        pt = torch.exp(-ce_loss)
        f_loss = self.alpha * (1-pt)**self.gamma * ce_loss
        return f_loss.mean()