/
losses.py
191 lines (147 loc) · 7.63 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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#!/usr/env/bin python3.6
from typing import List, Tuple
# from functools import reduce
from operator import add
from functools import reduce
import numpy as np
import torch
from torch import einsum
from torch import Tensor
import pandas as pd
from utils import simplex, sset, probs2one_hot
import torch.nn.modules.padding
from torch.nn import BCEWithLogitsLoss
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"]
#self.nd: str = kwargs["nd"]
print(f"Initialized {self.__class__.__name__} with {kwargs}")
def __call__(self, probs: Tensor, target: Tensor, _: 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(f"bcwh,bcwh->bc", pc, tc)
union: Tensor = (einsum(f"bkwh->bk", pc) + einsum(f"bkwh->bk", tc))
divided: Tensor = torch.ones_like(intersection) - (2 * intersection + 1e-10) / (union + 1e-10)
loss = divided.mean()
return loss
class EntKLProp():
"""
Entropy minimization with KL proportion regularisation
"""
def __init__(self, **kwargs):
self.power: int = kwargs["power"]
self.__fn__ = getattr(__import__('utils'), kwargs['fn'])
self.curi: bool = kwargs["curi"]
self.idc: bool = kwargs["idc_c"]
self.ivd: bool = kwargs["ivd"]
self.weights: List[float] = kwargs["weights_se"]
self.lamb_se: float = kwargs["lamb_se"]
self.lamb_consprior: float = kwargs["lamb_consprior"]
def __call__(self, probs: Tensor, target: Tensor, bounds) -> Tensor:
assert simplex(probs) # and simplex(target) # Actually, does not care about second part
b, _, w, h = probs.shape # type: Tuple[int, int, int, int]
predicted_mask = probs2one_hot(probs).detach()
est_prop_mask = self.__fn__(predicted_mask,self.power).squeeze(2)
est_prop: Tensor = self.__fn__(probs,self.power)
if self.curi:
if self.ivd:
bounds = bounds[:,:,0]
bounds= bounds.unsqueeze(2)
gt_prop = torch.ones_like(est_prop)*bounds/(w*h)
gt_prop = gt_prop[:,:,0]
else:
gt_prop: Tensor = self.__fn__(target,self.power) # the power here is actually useless if we have 0/1 gt labels
if not self.curi:
gt_prop = gt_prop.squeeze(2)
est_prop = est_prop.squeeze(2)
log_est_prop: Tensor = (est_prop + 1e-10).log()
log_gt_prop: Tensor = (gt_prop + 1e-10).log()
log_est_prop_mask: Tensor = (est_prop_mask + 1e-10).log()
loss_cons_prior = - torch.einsum("bc,bc->", [est_prop, log_gt_prop]) + torch.einsum("bc,bc->", [est_prop, log_est_prop])
# Adding division by batch_size to normalise
loss_cons_prior /= b
log_p: Tensor = (probs + 1e-10).log()
mask: Tensor = probs.type((torch.float32))
mask_weighted = torch.einsum("bcwh,c->bcwh", [mask, Tensor(self.weights).to(mask.device)])
loss_se = - torch.einsum("bcwh,bcwh->", [mask_weighted, log_p])
loss_se /= mask.sum() + 1e-10
assert loss_se.requires_grad == probs.requires_grad # Handle the case for validation
return self.lamb_se*loss_se, self.lamb_consprior*loss_cons_prior,est_prop
class SelfEntropy():
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.weights: List[float] = kwargs["weights"]
self.dtype = kwargs["dtype"]
print(f"Initialized {self.__class__.__name__} with {kwargs}")
def __call__(self, probs: Tensor, target: Tensor, bounds: Tensor) -> Tensor:
assert simplex(probs) and simplex(target)
log_p: Tensor = (probs[:, self.idc, ...] + 1e-10).log()
mask: Tensor = probs[:, self.idc, ...].type((torch.float32))
mask_weighted = torch.einsum("bcwh,c->bcwh", [mask, Tensor(self.weights).to(mask.device)])
loss = - torch.einsum("bcwh,bcwh->", [mask_weighted, log_p])
loss /= mask.sum() + 1e-10
return loss
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"]
self.weights: List[float] = kwargs["weights"]
self.dtype = kwargs["dtype"]
print(f"Initialized {self.__class__.__name__} with {kwargs}")
def __call__(self, probs: Tensor, target: Tensor, bounds: Tensor) -> Tensor:
assert simplex(probs) and simplex(target)
log_p: Tensor = (probs[:, self.idc, ...] + 1e-10).log()
mask: Tensor = target[:, self.idc, ...].type((torch.float32))
mask_weighted = torch.einsum("bcwh,c->bcwh", [mask, Tensor(self.weights).to(mask.device)])
loss = - torch.einsum("bcwh,bcwh->", [mask_weighted, log_p])
loss /= mask.sum() + 1e-10
return loss
class BCELoss():
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.dtype = kwargs["dtype"]
#print(f"Initialized {self.__class__.__name__} with {kwargs}")
def __call__(self, d_out: Tensor, label: float):
bce_loss = torch.nn.BCEWithLogitsLoss()
loss = bce_loss(d_out,Tensor(d_out.data.size()).fill_(label).to(d_out.device))
return loss
class BCEGDice():
def __init__(self, **kwargs):
self.idc: List[int] = kwargs["idc"]
self.lamb: List[int] = kwargs["lamb"]
self.weights: List[float] = kwargs["weights"]
print(f"Initialized {self.__class__.__name__} with {kwargs}")
def __call__(self, probs: Tensor, target: Tensor, _: 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("bcwh->bc", tc).type(torch.float32) + 1e-10) ** 2)
intersection: Tensor = w * einsum("bcwh,bcwh->bc", pc, tc)
union: Tensor = w * (einsum("bcwh->bc", pc) + einsum("bcwh->bc", tc))
divided: Tensor = 1 - 2 * (einsum("bc->b", intersection) + 1e-10) / (einsum("bc->b", union) + 1e-10)
loss_gde = divided.mean()
log_p: Tensor = (probs[:, self.idc, ...] + 1e-10).log()
mask_weighted = torch.einsum("bcwh,c->bcwh", [tc, Tensor(self.weights).to(tc.device)])
loss_ce = - torch.einsum("bcwh,bcwh->", [mask_weighted, log_p])
loss_ce /= tc.sum() + 1e-10
loss = loss_ce + self.lamb*loss_gde
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) -> 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("bcwh->bc", tc).type(torch.float32) + 1e-10) ** 2)
intersection: Tensor = w * einsum("bcwh,bcwh->bc", pc, tc)
union: Tensor = w * (einsum("bcwh->bc", pc) + einsum("bcwh->bc", tc))
divided: Tensor = 1 - 2 * (einsum("bc->b", intersection) + 1e-10) / (einsum("bc->b", union) + 1e-10)
loss = divided.mean()
return loss