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

#381 Feature/sg 000 connect to lab

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