-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
32 lines (28 loc) · 1.09 KB
/
Copy pathutils.py
File metadata and controls
32 lines (28 loc) · 1.09 KB
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
import torch
import torch.nn.functional as F
def dice_coef(pred, target, eps=1e-6):
pred = torch.sigmoid(pred)
pred = (pred>0.5).float()
inter = (pred*target).sum(dim=(2,3))
union = pred.sum(dim=(2,3)) + target.sum(dim=(2,3))
dice = (2*inter + eps)/(union + eps)
return dice.mean().item()
def iou_score(pred, target, eps=1e-6):
pred = torch.sigmoid(pred)
pred = (pred>0.5).float()
inter = (pred*target).sum(dim=(2,3))
union = pred.sum(dim=(2,3)) + target.sum(dim=(2,3)) - inter
iou = (inter + eps)/(union + eps)
return iou.mean().item()
class BCEDiceLoss:
def __init__(self, bce_weight=0.5, dice_weight=0.5):
self.bce_w = bce_weight
self.dice_w = dice_weight
def __call__(self, logits, targets):
bce = F.binary_cross_entropy_with_logits(logits, targets)
probs = torch.sigmoid(logits)
inter = (probs*targets).sum(dim=(2,3))
union = probs.sum(dim=(2,3)) + targets.sum(dim=(2,3))
dice = 1 - (2*inter + 1e-6)/(union + 1e-6)
dice = dice.mean()
return self.bce_w*bce + self.dice_w*dice