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

#578 Feature/sg 516 support head replacement for local pretrained weights unknown dataset

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:feature/SG-516_support_head_replacement_for_local_pretrained_weights_unknown_dataset
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
292
293
  1. import numpy as np
  2. import torch
  3. import torchmetrics
  4. from torchmetrics import Metric
  5. from typing import Optional, Tuple
  6. from torchmetrics.utilities.distributed import reduce
  7. from abc import ABC, abstractmethod
  8. def batch_pix_accuracy(predict, target):
  9. """Batch Pixel Accuracy
  10. Args:
  11. predict: input 4D tensor
  12. target: label 3D tensor
  13. """
  14. _, predict = torch.max(predict, 1)
  15. predict = predict.cpu().numpy() + 1
  16. target = target.cpu().numpy() + 1
  17. pixel_labeled = np.sum(target > 0)
  18. pixel_correct = np.sum((predict == target) * (target > 0))
  19. assert pixel_correct <= pixel_labeled, "Correct area should be smaller than Labeled"
  20. return pixel_correct, pixel_labeled
  21. def batch_intersection_union(predict, target, nclass):
  22. """Batch Intersection of Union
  23. Args:
  24. predict: input 4D tensor
  25. target: label 3D tensor
  26. nclass: number of categories (int)
  27. """
  28. _, predict = torch.max(predict, 1)
  29. mini = 1
  30. maxi = nclass
  31. nbins = nclass
  32. predict = predict.cpu().numpy() + 1
  33. target = target.cpu().numpy() + 1
  34. predict = predict * (target > 0).astype(predict.dtype)
  35. intersection = predict * (predict == target)
  36. # areas of intersection and union
  37. area_inter, _ = np.histogram(intersection, bins=nbins, range=(mini, maxi))
  38. area_pred, _ = np.histogram(predict, bins=nbins, range=(mini, maxi))
  39. area_lab, _ = np.histogram(target, bins=nbins, range=(mini, maxi))
  40. area_union = area_pred + area_lab - area_inter
  41. assert (area_inter <= area_union).all(), "Intersection area should be smaller than Union area"
  42. return area_inter, area_union
  43. # ref https://github.com/CSAILVision/sceneparsing/blob/master/evaluationCode/utils_eval.py
  44. def pixel_accuracy(im_pred, im_lab):
  45. im_pred = np.asarray(im_pred)
  46. im_lab = np.asarray(im_lab)
  47. # Remove classes from unlabeled pixels in gt image.
  48. # We should not penalize detections in unlabeled portions of the image.
  49. pixel_labeled = np.sum(im_lab > 0)
  50. pixel_correct = np.sum((im_pred == im_lab) * (im_lab > 0))
  51. # pixel_accuracy = 1.0 * pixel_correct / pixel_labeled
  52. return pixel_correct, pixel_labeled
  53. def _dice_from_confmat(
  54. confmat: torch.Tensor,
  55. num_classes: int,
  56. ignore_index: Optional[int] = None,
  57. absent_score: float = 0.0,
  58. reduction: str = "elementwise_mean",
  59. ) -> torch.Tensor:
  60. """Computes Dice coefficient from confusion matrix.
  61. Args:
  62. confmat: Confusion matrix without normalization
  63. num_classes: Number of classes for a given prediction and target tensor
  64. ignore_index: optional int specifying a target class to ignore. If given, this class index does not contribute
  65. to the returned score, regardless of reduction method.
  66. absent_score: score to use for an individual class, if no instances of the class index were present in `pred`
  67. AND no instances of the class index were present in `target`.
  68. reduction: a method to reduce metric score over labels.
  69. - ``'elementwise_mean'``: takes the mean (default)
  70. - ``'sum'``: takes the sum
  71. - ``'none'``: no reduction will be applied
  72. """
  73. # Remove the ignored class index from the scores.
  74. if ignore_index is not None and 0 <= ignore_index < num_classes:
  75. confmat[ignore_index] = 0.0
  76. intersection = torch.diag(confmat)
  77. denominator = confmat.sum(0) + confmat.sum(1)
  78. # If this class is absent in both target AND pred (union == 0), then use the absent_score for this class.
  79. scores = 2 * intersection.float() / denominator.float()
  80. scores[denominator == 0] = absent_score
  81. if ignore_index is not None and 0 <= ignore_index < num_classes:
  82. scores = torch.cat(
  83. [
  84. scores[:ignore_index],
  85. scores[ignore_index + 1 :],
  86. ]
  87. )
  88. return reduce(scores, reduction=reduction)
  89. def intersection_and_union(im_pred, im_lab, num_class):
  90. im_pred = np.asarray(im_pred)
  91. im_lab = np.asarray(im_lab)
  92. # Remove classes from unlabeled pixels in gt image.
  93. im_pred = im_pred * (im_lab > 0)
  94. # Compute area intersection:
  95. intersection = im_pred * (im_pred == im_lab)
  96. area_inter, _ = np.histogram(intersection, bins=num_class - 1, range=(1, num_class - 1))
  97. # Compute area union:
  98. area_pred, _ = np.histogram(im_pred, bins=num_class - 1, range=(1, num_class - 1))
  99. area_lab, _ = np.histogram(im_lab, bins=num_class - 1, range=(1, num_class - 1))
  100. area_union = area_pred + area_lab - area_inter
  101. return area_inter, area_union
  102. class AbstractMetricsArgsPrepFn(ABC):
  103. """
  104. Abstract preprocess metrics arguments class.
  105. """
  106. @abstractmethod
  107. def __call__(self, preds, target: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
  108. """
  109. All base classes must implement this function and return a tuple of torch tensors (predictions, target).
  110. """
  111. raise NotImplementedError()
  112. class PreprocessSegmentationMetricsArgs(AbstractMetricsArgsPrepFn):
  113. """
  114. Default segmentation inputs preprocess function before updating segmentation metrics, handles multiple inputs and
  115. apply normalizations.
  116. """
  117. def __init__(self, apply_arg_max: bool = False, apply_sigmoid: bool = False):
  118. """
  119. :param apply_arg_max: Whether to apply argmax on predictions tensor.
  120. :param apply_sigmoid: Whether to apply sigmoid on predictions tensor.
  121. """
  122. self.apply_arg_max = apply_arg_max
  123. self.apply_sigmoid = apply_sigmoid
  124. def __call__(self, preds, target: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
  125. # WHEN DEALING WITH MULTIPLE OUTPUTS- OUTPUTS[0] IS THE MAIN SEGMENTATION MAP
  126. if isinstance(preds, (tuple, list)):
  127. preds = preds[0]
  128. if self.apply_arg_max:
  129. _, preds = torch.max(preds, 1)
  130. elif self.apply_sigmoid:
  131. preds = torch.sigmoid(preds)
  132. target = target.long()
  133. return preds, target
  134. class PixelAccuracy(Metric):
  135. def __init__(self, ignore_label=-100, dist_sync_on_step=False, metrics_args_prep_fn: Optional[AbstractMetricsArgsPrepFn] = None):
  136. super().__init__(dist_sync_on_step=dist_sync_on_step)
  137. self.ignore_label = ignore_label
  138. self.greater_is_better = True
  139. self.add_state("total_correct", default=torch.tensor(0.0), dist_reduce_fx="sum")
  140. self.add_state("total_label", default=torch.tensor(0.0), dist_reduce_fx="sum")
  141. self.metrics_args_prep_fn = metrics_args_prep_fn or PreprocessSegmentationMetricsArgs(apply_arg_max=True)
  142. def update(self, preds: torch.Tensor, target: torch.Tensor):
  143. predict, target = self.metrics_args_prep_fn(preds, target)
  144. labeled_mask = target.ne(self.ignore_label)
  145. pixel_labeled = torch.sum(labeled_mask)
  146. pixel_correct = torch.sum((predict == target) * labeled_mask)
  147. self.total_correct += pixel_correct
  148. self.total_label += pixel_labeled
  149. def compute(self):
  150. _total_correct = self.total_correct.cpu().detach().numpy().astype("int64")
  151. _total_label = self.total_label.cpu().detach().numpy().astype("int64")
  152. pix_acc = np.float64(1.0) * _total_correct / (np.spacing(1, dtype=np.float64) + _total_label)
  153. return pix_acc
  154. class IoU(torchmetrics.JaccardIndex):
  155. def __init__(
  156. self,
  157. num_classes: int,
  158. dist_sync_on_step: bool = False,
  159. ignore_index: Optional[int] = None,
  160. reduction: str = "elementwise_mean",
  161. threshold: float = 0.5,
  162. metrics_args_prep_fn: Optional[AbstractMetricsArgsPrepFn] = None,
  163. ):
  164. if num_classes <= 1:
  165. raise ValueError(f"IoU class only for multi-class usage! For binary usage, please call {BinaryIOU.__name__}")
  166. super().__init__(num_classes=num_classes, dist_sync_on_step=dist_sync_on_step, ignore_index=ignore_index, reduction=reduction, threshold=threshold)
  167. self.metrics_args_prep_fn = metrics_args_prep_fn or PreprocessSegmentationMetricsArgs(apply_arg_max=True)
  168. self.greater_is_better = True
  169. def update(self, preds, target: torch.Tensor):
  170. preds, target = self.metrics_args_prep_fn(preds, target)
  171. super().update(preds=preds, target=target)
  172. class Dice(torchmetrics.JaccardIndex):
  173. def __init__(
  174. self,
  175. num_classes: int,
  176. dist_sync_on_step: bool = False,
  177. ignore_index: Optional[int] = None,
  178. reduction: str = "elementwise_mean",
  179. threshold: float = 0.5,
  180. metrics_args_prep_fn: Optional[AbstractMetricsArgsPrepFn] = None,
  181. ):
  182. if num_classes <= 1:
  183. raise ValueError(f"Dice class only for multi-class usage! For binary usage, please call {BinaryDice.__name__}")
  184. super().__init__(num_classes=num_classes, dist_sync_on_step=dist_sync_on_step, ignore_index=ignore_index, reduction=reduction, threshold=threshold)
  185. self.metrics_args_prep_fn = metrics_args_prep_fn or PreprocessSegmentationMetricsArgs(apply_arg_max=True)
  186. self.greater_is_better = True
  187. def update(self, preds, target: torch.Tensor):
  188. preds, target = self.metrics_args_prep_fn(preds, target)
  189. super().update(preds=preds, target=target)
  190. def compute(self) -> torch.Tensor:
  191. """Computes Dice coefficient"""
  192. return _dice_from_confmat(self.confmat, self.num_classes, self.ignore_index, self.absent_score, self.reduction)
  193. class BinaryIOU(IoU):
  194. def __init__(
  195. self,
  196. dist_sync_on_step=True,
  197. ignore_index: Optional[int] = None,
  198. threshold: float = 0.5,
  199. metrics_args_prep_fn: Optional[AbstractMetricsArgsPrepFn] = None,
  200. ):
  201. metrics_args_prep_fn = metrics_args_prep_fn or PreprocessSegmentationMetricsArgs(apply_sigmoid=True)
  202. super().__init__(
  203. num_classes=2,
  204. dist_sync_on_step=dist_sync_on_step,
  205. ignore_index=ignore_index,
  206. reduction="none",
  207. threshold=threshold,
  208. metrics_args_prep_fn=metrics_args_prep_fn,
  209. )
  210. self.greater_component_is_better = {
  211. "target_IOU": True,
  212. "background_IOU": True,
  213. "mean_IOU": True,
  214. }
  215. self.component_names = list(self.greater_component_is_better.keys())
  216. def compute(self):
  217. ious = super(BinaryIOU, self).compute()
  218. return {"target_IOU": ious[1], "background_IOU": ious[0], "mean_IOU": ious.mean()}
  219. class BinaryDice(Dice):
  220. def __init__(
  221. self,
  222. dist_sync_on_step=True,
  223. ignore_index: Optional[int] = None,
  224. threshold: float = 0.5,
  225. metrics_args_prep_fn: Optional[AbstractMetricsArgsPrepFn] = None,
  226. ):
  227. metrics_args_prep_fn = metrics_args_prep_fn or PreprocessSegmentationMetricsArgs(apply_sigmoid=True)
  228. super().__init__(
  229. num_classes=2,
  230. dist_sync_on_step=dist_sync_on_step,
  231. ignore_index=ignore_index,
  232. reduction="none",
  233. threshold=threshold,
  234. metrics_args_prep_fn=metrics_args_prep_fn,
  235. )
  236. self.greater_component_is_better = {
  237. "target_Dice": True,
  238. "background_Dice": True,
  239. "mean_Dice": True,
  240. }
  241. self.component_names = list(self.greater_component_is_better.keys())
  242. def compute(self):
  243. dices = super().compute()
  244. return {"target_Dice": dices[1], "background_Dice": dices[0], "mean_Dice": dices.mean()}
Discard
Tip!

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