-
Notifications
You must be signed in to change notification settings - Fork 3
/
loss.py
40 lines (25 loc) · 1.14 KB
/
loss.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
import torch.nn as nn
import torch
import torch.nn.functional as F
import numpy as np
class BinaryMaskLoss(nn.Module):
def __init__(self, weight=0.8, size_average=True):
super(BinaryMaskLoss, self).__init__()
self.weight = weight
def forward(self, inputs, targets, smooth=1):
intersection = (inputs * targets).sum()
dice = (2.*intersection + smooth)/(inputs.sum() + targets.sum() + smooth)
dice_score = 1-dice
BCE = F.binary_cross_entropy(inputs, targets, reduction='mean')
BCE_EXP = torch.exp(-BCE)
focal_loss = 0.8 * (1 - BCE_EXP)**2 * BCE
return self.weight * dice_score + 20 * focal_loss
class BinaryIoU(nn.Module):
def __init__(self, weight=None, size_average=True):
super(BinaryIoU, self).__init__()
def forward(self, inputs, targets, smooth=1):
intersection = (inputs * targets).sum()
total = (inputs + targets).sum()
union = total - intersection
IoU = (intersection + smooth) / (union + smooth)
return IoU