-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathlosses.py
81 lines (54 loc) · 2.16 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
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
__all__ = ['BCEDiceLoss', 'BceLoss', 'DiceLoss']
class BCEDiceLoss(nn.Module):
def __init__(self):
super().__init__()
def forward(self, input, target):
bce = F.binary_cross_entropy_with_logits(input, target, reduction='sum')/(input.size(-1)*input.size(-2)*input.size(-3))
smooth = 1e-5
input = torch.sigmoid(input)
num = target.size(0)
input = input.view(num, -1)
target = target.view(num, -1)
intersection = (input * target)
dice = (2 * intersection.sum() + smooth) / (input.sum() + target.sum() +smooth)
dice = 1.0 - dice
return bce + 2 * dice
class DiceLoss(nn.Module):
def __init__(self):
super().__init__()
def forward(self, input, target):
smooth = 1e-5
input = torch.softmax(input, dim=1)
num = target.size(0)
input = input[:,1:,:,:,:]
target = target[:,1:,:,:,:]
input = input.contiguous().view(num, -1)
target = target.contiguous().view(num, -1)
intersection = (input * target)
dice = (2 * intersection.sum(dim=1) + smooth) / (input.sum(dim=1) + target.sum(dim=1) +smooth)
all_dice = 1.0 - dice
return all_dice.sum()
class BceLoss(nn.Module):
def __init__(self):
super().__init__()
def forward(self, input, target, num_classes=2):
depth = input.size(2)
num = input.size(0)
w = input.size(-3)
h = input.size(-2)
target = (target > 0.5).int()
target_n = None
for i in range(num_classes):
if target_n is None:
target_n = i * target[:, i, :, :, :].unsqueeze(1)
else:
target_n = target_n + i * target[:, i, :, :, :].unsqueeze(1)
input = input.contiguous().view(num*depth, num_classes, -1)
target = (target_n.contiguous().view(num*depth, -1)).long()
bce = F.cross_entropy(input, target, reduction='none')
all_bce = torch.sum(bce) / (w * h * depth)
return all_bce