Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

losses.py 8.3 KB

You have to be logged in to leave a comment. Sign In
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
  1. # source: https://github.com/LIVIAETS/boundary-loss
  2. # paper: https://doi.org/10.1016/j.media.2020.101851
  3. # license: unspecified as of 2021-12-06
  4. # only selected code from repo
  5. import logging
  6. from functools import partial
  7. from typing import Any, Callable, cast, Iterable, List, Set, Tuple, TypeVar, Union
  8. from scipy.ndimage import distance_transform_edt as eucl_distance
  9. import numpy as np
  10. import torch
  11. import torch.sparse
  12. from torch import einsum, Tensor
  13. logger = logging.getLogger(__name__)
  14. EPS = 1e-10
  15. A = TypeVar("A")
  16. B = TypeVar("B")
  17. T = TypeVar("T", Tensor, np.ndarray)
  18. # fns
  19. def soft_size(a: Tensor) -> Tensor:
  20. return torch.einsum("bk...->bk", a)[..., None]
  21. def batch_soft_size(a: Tensor) -> Tensor:
  22. return torch.einsum("bk...->k", a)[..., None]
  23. # Assert utils
  24. def uniq(a: Tensor) -> Set:
  25. return set(torch.unique(a.cpu()).numpy())
  26. def sset(a: Tensor, sub: Iterable) -> bool:
  27. return uniq(a).issubset(sub)
  28. def eq(a: Tensor, b) -> bool:
  29. return torch.eq(a, b).all()
  30. # DISABLED: This keeps crashing at random - not sure what's causing this? maybe fp16 training?
  31. def simplex(t: Tensor, axis=1) -> bool:
  32. return True
  33. _sum = cast(Tensor, t.sum(axis).type(torch.float32))
  34. _ones = torch.ones_like(_sum, dtype=torch.float32)
  35. return torch.allclose(_sum, _ones)
  36. def one_hot(t: Tensor, axis=1) -> bool:
  37. return simplex(t, axis) and sset(t, [0, 1])
  38. # # Metrics and shitz
  39. def meta_dice(sum_str: str, label: Tensor, pred: Tensor, smooth: float = EPS) -> Tensor:
  40. assert label.shape == pred.shape
  41. assert one_hot(label)
  42. assert one_hot(pred)
  43. inter_size: Tensor = einsum(sum_str, [intersection(label, pred)]).type(
  44. torch.float32
  45. )
  46. sum_sizes: Tensor = (einsum(sum_str, [label]) + einsum(sum_str, [pred])).type(
  47. torch.float32
  48. )
  49. dices: Tensor = (2 * inter_size + smooth) / (sum_sizes + smooth)
  50. return dices
  51. dice_coef = partial(meta_dice, "bk...->bk")
  52. dice_batch = partial(meta_dice, "bk...->k") # used for 3d dice
  53. def intersection(a: Tensor, b: Tensor) -> Tensor:
  54. assert a.shape == b.shape
  55. assert sset(a, [0, 1])
  56. assert sset(b, [0, 1])
  57. res = a & b
  58. assert sset(res, [0, 1])
  59. return res
  60. def union(a: Tensor, b: Tensor) -> Tensor:
  61. assert a.shape == b.shape
  62. assert sset(a, [0, 1])
  63. assert sset(b, [0, 1])
  64. res = a | b
  65. assert sset(res, [0, 1])
  66. return res
  67. def inter_sum(a: Tensor, b: Tensor) -> Tensor:
  68. return einsum("bk...->bk", intersection(a, b).type(torch.float32))
  69. def union_sum(a: Tensor, b: Tensor) -> Tensor:
  70. return einsum("bk...->bk", union(a, b).type(torch.float32))
  71. # switch between representations
  72. def probs2class(probs: Tensor) -> Tensor:
  73. b, _, *img_shape = probs.shape
  74. assert simplex(probs)
  75. res = probs.argmax(dim=1)
  76. assert res.shape == (b, *img_shape)
  77. return res
  78. def class2one_hot(seg: Tensor, K: int) -> Tensor:
  79. # Breaking change but otherwise can't deal with both 2d and 3d
  80. # if len(seg.shape) == 3: # Only w, h, d, used by the dataloader
  81. # return class2one_hot(seg.unsqueeze(dim=0), K)[0]
  82. assert sset(seg, list(range(K))), (uniq(seg), K)
  83. b, *img_shape = seg.shape # type: Tuple[int, ...]
  84. device = seg.device
  85. res = torch.zeros((b, K, *img_shape), dtype=torch.int32, device=device).scatter_(
  86. 1, seg[:, None, ...], 1
  87. )
  88. assert res.shape == (b, K, *img_shape)
  89. assert one_hot(res)
  90. return res
  91. def np_class2one_hot(seg: np.ndarray, K: int) -> np.ndarray:
  92. return class2one_hot(torch.from_numpy(seg.copy()).type(torch.int64), K).numpy()
  93. def probs2one_hot(probs: Tensor) -> Tensor:
  94. _, K, *_ = probs.shape
  95. assert simplex(probs)
  96. res = class2one_hot(probs2class(probs), K)
  97. assert res.shape == probs.shape
  98. assert one_hot(res)
  99. return res
  100. def one_hot2dist(
  101. seg: np.ndarray, resolution: Tuple[float, float, float] = None, dtype=None
  102. ) -> np.ndarray:
  103. assert one_hot(torch.tensor(seg), axis=0)
  104. K: int = len(seg)
  105. res = np.zeros_like(seg, dtype=dtype)
  106. for k in range(K):
  107. posmask = seg[k].astype(np.bool)
  108. if posmask.any():
  109. negmask = ~posmask
  110. res[k] = (
  111. eucl_distance(negmask, sampling=resolution) * negmask
  112. - (eucl_distance(posmask, sampling=resolution) - 1) * posmask
  113. )
  114. # The idea is to leave blank the negative classes
  115. # since this is one-hot encoded, another class will supervise that pixel
  116. return res
  117. class CrossEntropy:
  118. def __init__(self, **kwargs):
  119. # Self.idc is used to filter out some classes of the target mask. Use fancy indexing
  120. self.idc: List[int] = kwargs["idc"]
  121. logger.debug(f"Initialized {self.__class__.__name__} with {kwargs}")
  122. def __call__(self, probs: Tensor, target: Tensor) -> Tensor:
  123. assert simplex(probs) and simplex(target)
  124. log_p: Tensor = (probs[:, self.idc, ...] + 1e-10).log()
  125. mask: Tensor = cast(Tensor, target[:, self.idc, ...].type(torch.float32))
  126. loss = -einsum("bkwh,bkwh->", mask, log_p)
  127. loss /= mask.sum() + 1e-10
  128. return loss
  129. class GeneralizedDice:
  130. def __init__(self, **kwargs):
  131. # Self.idc is used to filter out some classes of the target mask. Use fancy indexing
  132. self.idc: List[int] = kwargs["idc"]
  133. logger.debug(f"Initialized {self.__class__.__name__} with {kwargs}")
  134. def __call__(self, probs: Tensor, target: Tensor) -> Tensor:
  135. assert simplex(probs) and simplex(target)
  136. pc = probs[:, self.idc, ...].type(torch.float32)
  137. tc = target[:, self.idc, ...].type(torch.float32)
  138. # modification: move EPS outside to reduce risk of zero-division
  139. # orig: w: Tensor = 1 / ((einsum("bkwh->bk", tc).type(torch.float32) + EPS) ** 2)
  140. w: Tensor = 1 / ((einsum("bkwh->bk", tc).type(torch.float32) ** 2) + EPS)
  141. intersection: Tensor = w * einsum("bkwh,bkwh->bk", pc, tc)
  142. union: Tensor = w * (einsum("bkwh->bk", pc) + einsum("bkwh->bk", tc))
  143. divided: Tensor = 1 - 2 * (einsum("bk->b", intersection) + EPS) / (
  144. einsum("bk->b", union) + EPS
  145. )
  146. loss = divided.mean()
  147. return loss
  148. class DiceLoss:
  149. def __init__(self, **kwargs):
  150. # Self.idc is used to filter out some classes of the target mask. Use fancy indexing
  151. self.idc: List[int] = kwargs["idc"]
  152. logger.debug(f"Initialized {self.__class__.__name__} with {kwargs}")
  153. def __call__(self, probs: Tensor, target: Tensor) -> Tensor:
  154. assert simplex(probs) and simplex(target)
  155. pc = probs[:, self.idc, ...].type(torch.float32)
  156. tc = target[:, self.idc, ...].type(torch.float32)
  157. intersection: Tensor = einsum("bcwh,bcwh->bc", pc, tc)
  158. union: Tensor = einsum("bkwh->bk", pc) + einsum("bkwh->bk", tc)
  159. divided: Tensor = torch.ones_like(intersection) - (2 * intersection + EPS) / (
  160. union + EPS
  161. )
  162. loss = divided.mean()
  163. return loss
  164. class SurfaceLoss:
  165. def __init__(self, **kwargs):
  166. # Self.idc is used to filter out some classes of the target mask. Use fancy indexing
  167. self.idc: List[int] = kwargs["idc"]
  168. logger.debug(f"Initialized {self.__class__.__name__} with {kwargs}")
  169. def __call__(self, probs: Tensor, dist_maps: Tensor) -> Tensor:
  170. assert simplex(probs)
  171. assert not one_hot(dist_maps)
  172. pc = probs[:, self.idc, ...].type(torch.float32)
  173. dc = dist_maps[:, self.idc, ...].type(torch.float32)
  174. multipled = einsum("bkwh,bkwh->bkwh", pc, dc)
  175. loss = multipled.mean()
  176. return loss
  177. BoundaryLoss = SurfaceLoss
  178. class FocalLoss:
  179. def __init__(self, **kwargs):
  180. # Self.idc is used to filter out some classes of the target mask. Use fancy indexing
  181. self.idc: List[int] = kwargs["idc"]
  182. self.gamma: float = kwargs["gamma"]
  183. logger.debug(f"Initialized {self.__class__.__name__} with {kwargs}")
  184. def __call__(self, probs: Tensor, target: Tensor) -> Tensor:
  185. assert simplex(probs) and simplex(target)
  186. masked_probs: Tensor = probs[:, self.idc, ...]
  187. log_p: Tensor = (masked_probs + EPS).log()
  188. mask: Tensor = cast(Tensor, target[:, self.idc, ...].type(torch.float32))
  189. w: Tensor = (1 - masked_probs) ** self.gamma
  190. loss = -einsum("bkwh,bkwh,bkwh->", w, mask, log_p)
  191. loss /= mask.sum() + EPS
  192. return loss
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...