forked from WalterSimoncini/grounded-diffusers
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathloss_fn.py
77 lines (65 loc) · 2.34 KB
/
loss_fn.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
import torch
import torch.nn as nn
loss_bce = nn.BCEWithLogitsLoss()
class DiceLoss(nn.Module):
def __init__(self, p=2, smooth=1):
super(DiceLoss, self).__init__()
self.p = p
self.smooth = smooth
def forward(self, preds, target):
"""
inputs:
preds: tensor of shape (N, C, H, W)
target: tensor of shape(N, C, H, W)
output:
loss: tensor of shape(1, )
"""
preds = preds.contiguous().view(preds.shape[0], -1)
target = target.contiguous().view(target.shape[0], -1)
probs = torch.sigmoid(preds)
numer = (probs * target).sum()
denor = (probs.pow(self.p) + target.pow(self.p)).sum()
loss = 1.0 - (2 * numer + self.smooth) / (denor + self.smooth)
return loss
class BCEDiceLoss(nn.Module):
def __init__(self, p=2, smooth=1):
super(BCEDiceLoss, self).__init__()
self.p = p
self.smooth = smooth
def forward(self, preds, target):
"""
inputs:
preds: tensor of shape (N, C, H, W)
target: tensor of shape(N, C, H, W)
output:
loss: tensor of shape(1, )
"""
preds = preds.contiguous().view(preds.shape[0], -1)
target = target.contiguous().view(target.shape[0], -1)
probs = torch.sigmoid(preds)
numer = (probs * target).sum()
denor = (probs.pow(self.p) + target.pow(self.p)).sum()
dice_loss = 1.0 - (2 * numer + self.smooth) / (denor + self.smooth)
bce = loss_bce(preds, target)
loss = dice_loss + bce
return loss
class BCELogCoshDiceLoss(nn.Module):
def __init__(self, smooth=1):
super(BCELogCoshDiceLoss, self).__init__()
self.smooth = smooth
def forward(self, preds, target):
"""
inputs:
preds: tensor of shape (N, C, H, W)
target: tensor of shape(N, C, H, W)
output:
loss: tensor of shape(1, )
"""
preds = torch.sigmoid(preds)
intersection = (preds * target).sum(dim=(2, 3))
union = (preds + target).sum(dim=(2, 3))
dice = (2.0 * intersection + self.smooth) / (union + self.smooth)
log_cosh_dice = torch.log(torch.cosh(1 - dice))
bce = loss_bce(preds, target)
loss = torch.mean(log_cosh_dice) + bce
return loss