forked from LIVIAETS/boundary-loss
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlosses.py
158 lines (107 loc) · 5.51 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#!/usr/env/bin python3.9
from typing import List, cast
import torch
import numpy as np
from torch import Tensor, einsum
from utils import simplex, probs2one_hot, one_hot
from utils import one_hot2hd_dist
class CrossEntropy():
def __init__(self, **kwargs):
# Self.idc is used to filter out some classes of the target mask. Use fancy indexing
self.idc: List[int] = kwargs["idc"]
print(f"Initialized {self.__class__.__name__} with {kwargs}")
def __call__(self, probs: Tensor, target: Tensor) -> Tensor:
assert simplex(probs) and simplex(target)
log_p: Tensor = (probs[:, self.idc, ...] + 1e-10).log()
mask: Tensor = cast(Tensor, target[:, self.idc, ...].type(torch.float32))
loss = - einsum("bkwh,bkwh->", mask, log_p)
loss /= mask.sum() + 1e-10
return loss
class GeneralizedDice():
def __init__(self, **kwargs):
# Self.idc is used to filter out some classes of the target mask. Use fancy indexing
self.idc: List[int] = kwargs["idc"]
print(f"Initialized {self.__class__.__name__} with {kwargs}")
def __call__(self, probs: Tensor, target: Tensor) -> Tensor:
assert simplex(probs) and simplex(target)
pc = probs[:, self.idc, ...].type(torch.float32)
tc = target[:, self.idc, ...].type(torch.float32)
w: Tensor = 1 / ((einsum("bkwh->bk", tc).type(torch.float32) + 1e-10) ** 2)
intersection: Tensor = w * einsum("bkwh,bkwh->bk", pc, tc)
union: Tensor = w * (einsum("bkwh->bk", pc) + einsum("bkwh->bk", tc))
divided: Tensor = 1 - 2 * (einsum("bk->b", intersection) + 1e-10) / (einsum("bk->b", union) + 1e-10)
loss = divided.mean()
return loss
class DiceLoss():
def __init__(self, **kwargs):
# Self.idc is used to filter out some classes of the target mask. Use fancy indexing
self.idc: List[int] = kwargs["idc"]
print(f"Initialized {self.__class__.__name__} with {kwargs}")
def __call__(self, probs: Tensor, target: Tensor) -> Tensor:
assert simplex(probs) and simplex(target)
pc = probs[:, self.idc, ...].type(torch.float32)
tc = target[:, self.idc, ...].type(torch.float32)
intersection: Tensor = einsum("bcwh,bcwh->bc", pc, tc)
union: Tensor = (einsum("bkwh->bk", pc) + einsum("bkwh->bk", tc))
divided: Tensor = torch.ones_like(intersection) - (2 * intersection + 1e-10) / (union + 1e-10)
loss = divided.mean()
return loss
class SurfaceLoss():
def __init__(self, **kwargs):
# Self.idc is used to filter out some classes of the target mask. Use fancy indexing
self.idc: List[int] = kwargs["idc"]
print(f"Initialized {self.__class__.__name__} with {kwargs}")
def __call__(self, probs: Tensor, dist_maps: Tensor) -> Tensor:
assert simplex(probs)
assert not one_hot(dist_maps)
pc = probs[:, self.idc, ...].type(torch.float32)
dc = dist_maps[:, self.idc, ...].type(torch.float32)
multipled = einsum("bkwh,bkwh->bkwh", pc, dc)
loss = multipled.mean()
return loss
BoundaryLoss = SurfaceLoss
class HausdorffLoss():
"""
Implementation heavily inspired from https://github.com/JunMa11/SegWithDistMap
"""
def __init__(self, **kwargs):
# Self.idc is used to filter out some classes of the target mask. Use fancy indexing
self.idc: List[int] = kwargs["idc"]
print(f"Initialized {self.__class__.__name__} with {kwargs}")
def __call__(self, probs: Tensor, target: Tensor) -> Tensor:
assert simplex(probs)
assert simplex(target)
assert probs.shape == target.shape
B, K, *xyz = probs.shape # type: ignore
pc = cast(Tensor, probs[:, self.idc, ...].type(torch.float32))
tc = cast(Tensor, target[:, self.idc, ...].type(torch.float32))
assert pc.shape == tc.shape == (B, len(self.idc), *xyz)
target_dm_npy: np.ndarray = np.stack([one_hot2hd_dist(tc[b].cpu().detach().numpy())
for b in range(B)], axis=0)
assert target_dm_npy.shape == tc.shape == pc.shape
tdm: Tensor = torch.tensor(target_dm_npy, device=probs.device, dtype=torch.float32)
pred_segmentation: Tensor = probs2one_hot(probs).cpu().detach()
pred_dm_npy: np.nparray = np.stack([one_hot2hd_dist(pred_segmentation[b, self.idc, ...].numpy())
for b in range(B)], axis=0)
assert pred_dm_npy.shape == tc.shape == pc.shape
pdm: Tensor = torch.tensor(pred_dm_npy, device=probs.device, dtype=torch.float32)
delta = (pc - tc)**2
dtm = tdm**2 + pdm**2
multipled = einsum("bkwh,bkwh->bkwh", delta, dtm)
loss = multipled.mean()
return loss
class FocalLoss():
def __init__(self, **kwargs):
# Self.idc is used to filter out some classes of the target mask. Use fancy indexing
self.idc: List[int] = kwargs["idc"]
self.gamma: float = kwargs["gamma"]
print(f"Initialized {self.__class__.__name__} with {kwargs}")
def __call__(self, probs: Tensor, target: Tensor) -> Tensor:
assert simplex(probs) and simplex(target)
masked_probs: Tensor = probs[:, self.idc, ...]
log_p: Tensor = (masked_probs + 1e-10).log()
mask: Tensor = cast(Tensor, target[:, self.idc, ...].type(torch.float32))
w: Tensor = (1 - masked_probs)**self.gamma
loss = - einsum("bkwh,bkwh,bkwh->", w, mask, log_p)
loss /= mask.sum() + 1e-10
return loss