-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjaccard_loss.py
66 lines (44 loc) · 1.97 KB
/
jaccard_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
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
import torch
import torch.nn.functional as F
from torch.nn.modules.loss import _Loss
class JaccardLoss(_Loss):
def __init__(self, eps=1e-7, ignore_index=None):
super().__init__()
self.eps = eps
self.ignore_index = ignore_index
def forward(self, logits, label):
classes = set(label.unique().tolist())
if self.ignore_index in classes:
classes.remove(self.ignore_index)
if len(classes) < 1:
return 0. * logits.sum()
batch_size, num_classes, _, _ = logits.shape
if num_classes == 1:
prob = F.logsigmoid(logits).exp()
prob = prob.view(-1)
label = label.view(-1)
not_ignore = label != self.ignore_index
prob = prob[not_ignore]
label = label[not_ignore]
iou = self.compute_iou(prob, label)
losses = 1.0 - iou
return losses
else:
losses = []
prob = logits.log_softmax(dim=1).exp()
prob = prob.view(batch_size, num_classes, -1)
label = label.view(batch_size, -1)
not_ignore = label != self.ignore_index
label = F.one_hot(label, num_classes + 1)
label = label.permute(0, 2, 1)
for j in classes:
prob_j = prob[:, j, :][not_ignore]
label_j = label[:, j, :][not_ignore]
iou = self.compute_iou(prob_j, label_j)
losses.append(1.0 - iou)
return sum(losses) / len(losses)
def compute_iou(self, prob, label):
intersection = torch.sum(prob * label)
difference = torch.sum(torch.abs(prob - label))
union = difference + intersection
return intersection / union.clamp_min(self.eps)