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

detection_metrics.py 10 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
  1. from typing import Dict, Optional, Union
  2. import torch
  3. from torchmetrics import Metric
  4. import super_gradients
  5. from super_gradients.training.utils import tensor_container_to_device
  6. from super_gradients.training.utils.detection_utils import compute_detection_matching, compute_detection_metrics
  7. from super_gradients.training.utils.detection_utils import DetectionPostPredictionCallback, IouThreshold
  8. from super_gradients.common.abstractions.abstract_logger import get_logger
  9. logger = get_logger(__name__)
  10. class DetectionMetrics(Metric):
  11. """
  12. DetectionMetrics
  13. Metric class for computing F1, Precision, Recall and Mean Average Precision.
  14. Attributes:
  15. num_cls: Number of classes.
  16. post_prediction_callback: DetectionPostPredictionCallback to be applied on net's output prior
  17. to the metric computation (NMS).
  18. normalize_targets: Whether to normalize bbox coordinates by image size (default=False).
  19. iou_thresholds: IoU threshold to compute the mAP (default=torch.linspace(0.5, 0.95, 10)).
  20. recall_thresholds: Recall threshold to compute the mAP (default=torch.linspace(0, 1, 101)).
  21. score_threshold: Score threshold to compute Recall, Precision and F1 (default=0.1)
  22. top_k_predictions: Number of predictions per class used to compute metrics, ordered by confidence score
  23. (default=100)
  24. dist_sync_on_step: Synchronize metric state across processes at each ``forward()``
  25. before returning the value at the step. (default=False)
  26. accumulate_on_cpu: Run on CPU regardless of device used in other parts.
  27. This is to avoid "CUDA out of memory" that might happen on GPU (default False)
  28. """
  29. def __init__(
  30. self,
  31. num_cls: int,
  32. post_prediction_callback: DetectionPostPredictionCallback,
  33. normalize_targets: bool = False,
  34. iou_thres: Union[IouThreshold, float] = IouThreshold.MAP_05_TO_095,
  35. recall_thres: torch.Tensor = None,
  36. score_thres: float = 0.1,
  37. top_k_predictions: int = 100,
  38. dist_sync_on_step: bool = False,
  39. accumulate_on_cpu: bool = True,
  40. ):
  41. super().__init__(dist_sync_on_step=dist_sync_on_step)
  42. self.num_cls = num_cls
  43. self.iou_thres = iou_thres
  44. if isinstance(iou_thres, IouThreshold):
  45. self.iou_thresholds = iou_thres.to_tensor()
  46. else:
  47. self.iou_thresholds = torch.tensor([iou_thres])
  48. self.map_str = "mAP" + self._get_range_str()
  49. self.greater_component_is_better = {
  50. f"Precision{self._get_range_str()}": True,
  51. f"Recall{self._get_range_str()}": True,
  52. f"mAP{self._get_range_str()}": True,
  53. f"F1{self._get_range_str()}": True,
  54. }
  55. self.component_names = list(self.greater_component_is_better.keys())
  56. self.components = len(self.component_names)
  57. self.post_prediction_callback = post_prediction_callback
  58. self.is_distributed = super_gradients.is_distributed()
  59. self.denormalize_targets = not normalize_targets
  60. self.world_size = None
  61. self.rank = None
  62. self.add_state(f"matching_info{self._get_range_str()}", default=[], dist_reduce_fx=None)
  63. self.recall_thresholds = torch.linspace(0, 1, 101) if recall_thres is None else recall_thres
  64. self.score_threshold = score_thres
  65. self.top_k_predictions = top_k_predictions
  66. self.accumulate_on_cpu = accumulate_on_cpu
  67. def update(self, preds, target: torch.Tensor, device: str, inputs: torch.tensor, crowd_targets: Optional[torch.Tensor] = None):
  68. """
  69. Apply NMS and match all the predictions and targets of a given batch, and update the metric state accordingly.
  70. :param preds : Raw output of the model, the format might change from one model to another, but has to fit
  71. the input format of the post_prediction_callback
  72. :param target: Targets for all images of shape (total_num_targets, 6)
  73. format: (index, x, y, w, h, label) where x,y,w,h are in range [0,1]
  74. :param device: Device to run on
  75. :param inputs: Input image tensor of shape (batch_size, n_img, height, width)
  76. :param crowd_targets: Crowd targets for all images of shape (total_num_targets, 6)
  77. format: (index, x, y, w, h, label) where x,y,w,h are in range [0,1]
  78. """
  79. self.iou_thresholds = self.iou_thresholds.to(device)
  80. _, _, height, width = inputs.shape
  81. targets = target.clone()
  82. crowd_targets = torch.zeros(size=(0, 6), device=device) if crowd_targets is None else crowd_targets.clone()
  83. preds = self.post_prediction_callback(preds, device=device)
  84. new_matching_info = compute_detection_matching(
  85. preds,
  86. targets,
  87. height,
  88. width,
  89. self.iou_thresholds,
  90. crowd_targets=crowd_targets,
  91. top_k=self.top_k_predictions,
  92. denormalize_targets=self.denormalize_targets,
  93. device=self.device,
  94. return_on_cpu=self.accumulate_on_cpu,
  95. )
  96. accumulated_matching_info = getattr(self, f"matching_info{self._get_range_str()}")
  97. setattr(self, f"matching_info{self._get_range_str()}", accumulated_matching_info + new_matching_info)
  98. def compute(self) -> Dict[str, Union[float, torch.Tensor]]:
  99. """Compute the metrics for all the accumulated results.
  100. :return: Metrics of interest
  101. """
  102. mean_ap, mean_precision, mean_recall, mean_f1 = -1.0, -1.0, -1.0, -1.0
  103. accumulated_matching_info = getattr(self, f"matching_info{self._get_range_str()}")
  104. if len(accumulated_matching_info):
  105. matching_info_tensors = [torch.cat(x, 0) for x in list(zip(*accumulated_matching_info))]
  106. # shape (n_class, nb_iou_thresh)
  107. ap, precision, recall, f1, unique_classes = compute_detection_metrics(
  108. *matching_info_tensors,
  109. recall_thresholds=self.recall_thresholds,
  110. score_threshold=self.score_threshold,
  111. device="cpu" if self.accumulate_on_cpu else self.device,
  112. )
  113. # Precision, recall and f1 are computed for IoU threshold range, averaged over classes
  114. # results before version 3.0.4 (Dec 11 2022) were computed only for smallest value (i.e IoU 0.5 if metric is @0.5:0.95)
  115. mean_precision, mean_recall, mean_f1 = precision.mean(), recall.mean(), f1.mean()
  116. # MaP is averaged over IoU thresholds and over classes
  117. mean_ap = ap.mean()
  118. return {
  119. f"Precision{self._get_range_str()}": mean_precision,
  120. f"Recall{self._get_range_str()}": mean_recall,
  121. f"mAP{self._get_range_str()}": mean_ap,
  122. f"F1{self._get_range_str()}": mean_f1,
  123. }
  124. def _sync_dist(self, dist_sync_fn=None, process_group=None):
  125. """
  126. When in distributed mode, stats are aggregated after each forward pass to the metric state. Since these have all
  127. different sizes we override the synchronization function since it works only for tensors (and use
  128. all_gather_object)
  129. @param dist_sync_fn:
  130. @return:
  131. """
  132. if self.world_size is None:
  133. self.world_size = torch.distributed.get_world_size() if self.is_distributed else -1
  134. if self.rank is None:
  135. self.rank = torch.distributed.get_rank() if self.is_distributed else -1
  136. if self.is_distributed:
  137. local_state_dict = {attr: getattr(self, attr) for attr in self._reductions.keys()}
  138. gathered_state_dicts = [None] * self.world_size
  139. torch.distributed.barrier()
  140. torch.distributed.all_gather_object(gathered_state_dicts, local_state_dict)
  141. matching_info = []
  142. for state_dict in gathered_state_dicts:
  143. matching_info += state_dict[f"matching_info{self._get_range_str()}"]
  144. matching_info = tensor_container_to_device(matching_info, device="cpu" if self.accumulate_on_cpu else self.device)
  145. setattr(self, f"matching_info{self._get_range_str()}", matching_info)
  146. def _get_range_str(self):
  147. return "@%.2f" % self.iou_thresholds[0] if not len(self.iou_thresholds) > 1 else "@%.2f:%.2f" % (self.iou_thresholds[0], self.iou_thresholds[-1])
  148. class DetectionMetrics_050(DetectionMetrics):
  149. def __init__(
  150. self,
  151. num_cls: int,
  152. post_prediction_callback: DetectionPostPredictionCallback = None,
  153. normalize_targets: bool = False,
  154. recall_thres: torch.Tensor = None,
  155. score_thres: float = 0.1,
  156. top_k_predictions: int = 100,
  157. dist_sync_on_step: bool = False,
  158. accumulate_on_cpu: bool = True,
  159. ):
  160. super().__init__(
  161. num_cls,
  162. post_prediction_callback,
  163. normalize_targets,
  164. IouThreshold.MAP_05,
  165. recall_thres,
  166. score_thres,
  167. top_k_predictions,
  168. dist_sync_on_step,
  169. accumulate_on_cpu,
  170. )
  171. class DetectionMetrics_075(DetectionMetrics):
  172. def __init__(
  173. self,
  174. num_cls: int,
  175. post_prediction_callback: DetectionPostPredictionCallback = None,
  176. normalize_targets: bool = False,
  177. recall_thres: torch.Tensor = None,
  178. score_thres: float = 0.1,
  179. top_k_predictions: int = 100,
  180. dist_sync_on_step: bool = False,
  181. accumulate_on_cpu: bool = True,
  182. ):
  183. super().__init__(
  184. num_cls, post_prediction_callback, normalize_targets, 0.75, recall_thres, score_thres, top_k_predictions, dist_sync_on_step, accumulate_on_cpu
  185. )
  186. class DetectionMetrics_050_095(DetectionMetrics):
  187. def __init__(
  188. self,
  189. num_cls: int,
  190. post_prediction_callback: DetectionPostPredictionCallback = None,
  191. normalize_targets: bool = False,
  192. recall_thres: torch.Tensor = None,
  193. score_thres: float = 0.1,
  194. top_k_predictions: int = 100,
  195. dist_sync_on_step: bool = False,
  196. accumulate_on_cpu: bool = True,
  197. ):
  198. super().__init__(
  199. num_cls,
  200. post_prediction_callback,
  201. normalize_targets,
  202. IouThreshold.MAP_05_TO_095,
  203. recall_thres,
  204. score_thres,
  205. top_k_predictions,
  206. dist_sync_on_step,
  207. accumulate_on_cpu,
  208. )
Tip!

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

Comments

Loading...