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_distance_based_test.py 28 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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
  1. import math
  2. import unittest
  3. import torch
  4. import random
  5. from typing import List, Optional, Tuple, Dict
  6. from super_gradients.training.metrics.detection_metrics import DetectionMetricsDistanceBased
  7. from super_gradients.training.utils.detection_utils import EuclideanDistance, ManhattanDistance
  8. class TestDetectionMetricsDistanceBased(unittest.TestCase):
  9. def setUp(self):
  10. # Set random seeds for reproducibility
  11. torch.manual_seed(42)
  12. random.seed(42)
  13. self.num_classes = 3
  14. self.predefined_correct_class = 1 # random.randint(0, self.num_classes - 1)
  15. self.using_predefined_class = True
  16. self.verbose = True
  17. self.distance_thresholds = [5.0]
  18. self.score_thres = 0.1
  19. self.img_width = 640
  20. self.img_height = 480
  21. # Mock input image tensor (1 batch, 1 image, 640x480 size)
  22. self.img_tensor = (torch.randint(0, 256, (1, 1, self.img_height, self.img_width), dtype=torch.uint8)).int()
  23. self.metric = DetectionMetricsDistanceBased(
  24. num_cls=self.num_classes,
  25. post_prediction_callback=self.mock_post_prediction_callback,
  26. distance_thresholds=self.distance_thresholds,
  27. score_thres=self.score_thres,
  28. distance_metric=EuclideanDistance(),
  29. )
  30. def mock_post_prediction_callback(self, batch_preds: List[torch.Tensor], device="cpu") -> List[torch.Tensor]:
  31. batch_transformed_preds = []
  32. for preds in batch_preds: # Iterate over each image's raw predictions in the batch
  33. transformed_preds = []
  34. for i in range(preds.size(0)): # Iterate over each prediction for the current image
  35. # Get the bounding box coordinates (cx, cy, w, h) from raw preds
  36. cx, cy, w, h = preds[i]
  37. # Generate a random confidence score (for testing)
  38. confidence = random.uniform(0.1, 0.9)
  39. # Generate a random class label (for testing)
  40. if self.using_predefined_class:
  41. class_label = self.predefined_correct_class
  42. else:
  43. class_label = random.randint(0, self.num_classes - 1)
  44. # Calculate absolute coordinates (x1, y1, x2, y2)
  45. x1 = cx - w / 2.0
  46. y1 = cy - h / 2.0
  47. x2 = cx + w / 2.0
  48. y2 = cy + h / 2.0
  49. # Store the transformed prediction in a tensor
  50. transformed_pred = torch.tensor([x1, y1, x2, y2, confidence, class_label], device=device)
  51. # Append the tensor to the list
  52. transformed_preds.append(transformed_pred)
  53. # Convert list of tensors to a single tensor for this image
  54. transformed_preds = torch.stack(transformed_preds)
  55. # Add this image's transformed predictions to the batch list
  56. batch_transformed_preds.append(transformed_preds)
  57. return batch_transformed_preds
  58. def validate_results(self, results: Dict, precision, recall, mAP, F1, places=4, verbose=False, description=None):
  59. if verbose and description:
  60. test_name = self.id().split(".")[-1]
  61. print(f"\n{test_name}():")
  62. print(f"Description: {description}")
  63. results = dict((k.split("@")[0].lower().replace("distance_based_", ""), v) for k, v in results.items())
  64. self.assertAlmostEqual(results["precision"].item(), precision, places=places)
  65. self.assertAlmostEqual(results["recall"].item(), recall, places=places)
  66. if mAP is not None:
  67. self.assertAlmostEqual(results["map"].item(), mAP, places=places)
  68. self.assertAlmostEqual(results["f1"].item(), F1, places=places)
  69. def generate_targets(self, img_width, img_height, num_classes, num_targets):
  70. targets = []
  71. for index in range(num_targets):
  72. # Generate random coordinates and dimensions for the target
  73. cx, cy = random.randint(0, img_width - 1), random.randint(0, img_height - 1)
  74. max_w = min(cx, img_width - cx) * 2
  75. max_h = min(cy, img_height - cy) * 2
  76. w = random.randint(1, max_w)
  77. h = random.randint(1, max_h)
  78. # Pick label
  79. if self.using_predefined_class:
  80. label = self.predefined_correct_class
  81. else:
  82. label = random.randint(0, num_classes - 1)
  83. # Normalize target coordinates and dimensions to [0, 1]
  84. target_x1, target_y1, target_x2, target_y2 = self.normalize_coordinates(cx, cy, w, h, img_width, img_height)
  85. target_w = target_x2 - target_x1
  86. target_h = target_y2 - target_y1
  87. target_cx = target_x1 + target_w / 2
  88. target_cy = target_y1 + target_h / 2
  89. # Append target data in LABEL_CXCYWH format
  90. targets.append([index, label, target_cx, target_cy, target_w, target_h])
  91. targets = torch.tensor(targets, dtype=torch.float32).reshape(num_targets, 6)
  92. return targets
  93. @staticmethod
  94. def generate_predictions(distance_thresholds, img_height, img_width, num_correct_preds, num_targets, num_total_predictions, targets):
  95. predictions = []
  96. for _ in range(num_correct_preds):
  97. # Generate predictions close to some targets
  98. target_idx = random.randint(0, num_targets - 1)
  99. _, _, x_center, y_center, _, _ = targets[target_idx]
  100. dist_idx = random.randint(0, len(distance_thresholds) - 1)
  101. distance = random.randint(0, distance_thresholds[dist_idx])
  102. angle = random.uniform(0, 2 * math.pi)
  103. x_center_scalar = int(x_center.item() * img_width) # As denormalized
  104. y_center_scalar = int(y_center.item() * img_height) # As denormalized
  105. pred_x = int(round(x_center_scalar + distance * math.cos(angle)))
  106. pred_y = int(round(y_center_scalar + distance * math.sin(angle)))
  107. max_w = min(pred_x, img_width - pred_x) * 2
  108. max_h = min(pred_y, img_height - pred_y) * 2
  109. w = random.randint(1, max_w)
  110. h = random.randint(1, max_h)
  111. # Append prediction data in CXCYWH format
  112. prediction = torch.tensor([pred_x, pred_y, w, h])
  113. predictions.append(prediction)
  114. for _ in range(num_total_predictions - num_correct_preds):
  115. # Generate predictions far from any target
  116. pred_x, pred_y = random.randint(0, img_width - 1), random.randint(0, img_height - 1)
  117. max_w = min(pred_x, img_width - pred_x) * 2
  118. max_h = min(pred_y, img_height - pred_y) * 2
  119. w = random.randint(1, max_w)
  120. h = random.randint(1, max_h)
  121. # Append prediction data in CXCYWH format
  122. prediction = torch.tensor([pred_x, pred_y, w, h])
  123. predictions.append(prediction)
  124. # Convert the list of tensors into a single tensor and reshape it
  125. predictions = torch.stack(predictions)
  126. return [predictions]
  127. @staticmethod
  128. def normalize_coordinates(cx: int, cy: int, w: int, h: int, img_width: int, img_height: int) -> Tuple[float, float, float, float]:
  129. """
  130. Normalize coordinates and dimensions to [0, 1] range.
  131. Args:
  132. cx (int): Center x-coordinate.
  133. cy (int): Center y-coordinate.
  134. w (int): Width.
  135. h (int): Height.
  136. img_width (int): Width of the image.
  137. img_height (int): Height of the image.
  138. Returns:
  139. Tuple[float, float, float, float]: Normalized coordinates and dimensions (x1, y1, x2, y2).
  140. """
  141. x1 = max(0, (cx - w / 2) / img_width)
  142. y1 = max(0, (cy - h / 2) / img_height)
  143. x2 = min(1, (cx + w / 2) / img_width)
  144. y2 = min(1, (cy + h / 2) / img_height)
  145. return x1, y1, x2, y2
  146. @staticmethod
  147. def generate_mock_data(
  148. self,
  149. img_width: int,
  150. img_height: int,
  151. num_classes: int,
  152. num_targets: int,
  153. distance_thresholds: List[float],
  154. target_precision: float,
  155. target_recall: float,
  156. crowd_targets: bool = False,
  157. ) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
  158. """
  159. Generate mock data for testing object detection metrics.
  160. Args:
  161. img_width (int): Width of the image.
  162. img_height (int): Height of the image.
  163. num_classes (int): Number of classes.
  164. num_targets (int): Number of mock target objects.
  165. distance_thresholds: (List[float]): List of distance thresholds.
  166. target_precision (float): Desired precision value (between 0 and 1).
  167. target_recall (float): Desired recall value (between 0 and 1).
  168. crowd_targets (bool, optional): Whether to create crowded targets. Default is False.
  169. Returns:
  170. Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
  171. - Mock targets with shape (num_targets, 6) in LABEL_CXCYWH format.
  172. - Mock predictions with shape (num_total_predictions, 4) in CXCYWH format.
  173. - Crowd targets with shape (num_crowd_targets, 6) in LABEL_CXCYWH format, or None if crowd_targets is False.
  174. """
  175. # Generate targets
  176. targets = self.generate_targets(img_width, img_height, num_classes, num_targets)
  177. # Calculate TP, FP, and FN
  178. TP = num_targets
  179. FP = int((TP / target_precision) - TP)
  180. # Calculate the total number of predictions you'll need to generate
  181. num_total_predictions = TP + FP # Because TP + FP = total predictions
  182. num_correct_preds = math.ceil(num_total_predictions * target_precision)
  183. # Generate predictions accordingly to scenario
  184. predictions = self.generate_predictions(distance_thresholds, img_height, img_width, num_correct_preds, num_targets, num_total_predictions, targets)
  185. crowd_targets_data = None
  186. if crowd_targets:
  187. # Create crowded targets (similar to targets)
  188. crowd_targets_data = self.generate_targets(img_width, img_height, num_classes, num_targets)
  189. return targets, predictions, crowd_targets_data
  190. @staticmethod
  191. def calculate_expected_metrics(self, precision, recall):
  192. # Calculate expected mAP (simplified in this context)
  193. expected_mAP = precision
  194. # Calculate expected F1-score
  195. if precision + recall == 0:
  196. expected_f1 = 0.0
  197. else:
  198. expected_f1 = (2 * precision * recall) / (precision + recall)
  199. return expected_mAP, expected_f1
  200. # Test Scenario: Single target in the image, single match out of three total predictions.
  201. # Desired precision: 0.33 (1 out of 3 predictions should match).
  202. # Desired recall: 0.33 (1 out of 3 targets should be detected).
  203. # Total predictions: 3 (to meet the precision and recall requirements).
  204. # Crowd targets: None
  205. def test_random_case_generation_and_verification(self):
  206. # Set random seeds for reproducibility (to ensure the seeds even at this level)
  207. torch.manual_seed(42)
  208. random.seed(42)
  209. # Test configuration
  210. num_targets = 1 # Number of mock target objects
  211. target_precision = 0.3333
  212. target_recall = 1
  213. crowd_targets = False # Set to True to generate crowd targets
  214. # Generate mock data
  215. targets, predictions, crowd_targets_data = self.generate_mock_data(
  216. self, self.img_width, self.img_height, self.num_classes, num_targets, self.distance_thresholds, target_precision, target_recall, crowd_targets
  217. )
  218. # Call the update and compute methods with generated data
  219. self.metric.update(preds=predictions, target=targets, device="cpu", inputs=self.img_tensor, crowd_targets=None)
  220. results = self.metric.compute()
  221. # Calculate expected mAP and F1-score
  222. expected_mAP, expected_f1 = self.calculate_expected_metrics(self, target_precision, target_recall)
  223. # Validate the results
  224. self.validate_results(results, precision=target_precision, recall=target_recall, mAP=None, F1=expected_f1)
  225. # checks whether a single prediction that matches a single target will yield a perfect score
  226. # (Precision, Recall, F1 score, and mAP all set to 1.0). Using Manhattan distance.
  227. def test_distance_based_score_l1_norm_distance_single_target_single_prediction_match(self):
  228. scenario = "a single prediction that matches a single target using L1 Norm as a metric"
  229. # Set random seeds for reproducibility (to ensure the seeds even at this level)
  230. torch.manual_seed(42)
  231. random.seed(42)
  232. # Mock raw_preds (model's output) in format cx, cy, w, h; coordinates within image dimensions
  233. # One prediction is 5px away from the center of the target
  234. raw_preds = [torch.tensor([[15, 15, 10, 10]])] # Close to target
  235. # Define target (unnormalized) coordinates within image dimensions
  236. target_x1, target_y1, target_x2, target_y2 = 10, 10, 20, 20
  237. # Normalize target coordinates
  238. target_x1, target_x2 = target_x1 / self.img_width, target_x2 / self.img_width
  239. target_y1, target_y2 = target_y1 / self.img_height, target_y2 / self.img_height
  240. # Calculate normalized width and height
  241. target_w = target_x2 - target_x1
  242. target_h = target_y2 - target_y1
  243. # Calculate normalized center coordinates
  244. target_cx = target_x1 + target_w / 2
  245. target_cy = target_y1 + target_h / 2
  246. # Mock targets
  247. # Create a single target for one image with shape (1, 6).
  248. # Format: (index, label, cx, cy, w, h)
  249. targets = torch.tensor([[0, self.predefined_correct_class, target_cx, target_cy, target_w, target_h]], dtype=torch.float32).reshape(1, 6)
  250. self.metric = DetectionMetricsDistanceBased(
  251. num_cls=self.num_classes,
  252. post_prediction_callback=self.mock_post_prediction_callback,
  253. distance_thresholds=[5.0],
  254. score_thres=self.score_thres,
  255. distance_metric=ManhattanDistance(),
  256. )
  257. # Call the update method
  258. self.metric.update(preds=raw_preds, target=targets, device="cpu", inputs=self.img_tensor, crowd_targets=None)
  259. # Call the compute method to get the results
  260. results = self.metric.compute()
  261. # Validate the results
  262. self.validate_results(results, precision=1.0, recall=1.0, mAP=1.0, F1=1.0, verbose=self.verbose, description=scenario)
  263. # checks whether a single prediction that matches a single crowd target will yield a perfect score
  264. # (Precision, Recall, F1 score, and mAP all set to 1.0). Using Manhattan distance.
  265. def test_distance_based_score_euclidean_distance_single_crowd_target_single_prediction_target_miss(self):
  266. scenario = "A single prediction, single target and a single crowd target. Prediction close to crowd target and far from target."
  267. # Set random seeds for reproducibility (to ensure the seeds even at this level)
  268. torch.manual_seed(42)
  269. random.seed(42)
  270. # Mock raw_preds (model's output) in format cx, cy, w, h; coordinates within image dimensions
  271. # One prediction is 5px away from the center of the crowd target
  272. raw_preds = [torch.tensor([[15, 15, 10, 10]])] # Close to crowd target
  273. # Define target (unnormalized) coordinates within image dimensions
  274. target_x1, target_y1, target_x2, target_y2 = 100, 100, 200, 200
  275. # Normalize target coordinates
  276. target_x1, target_x2 = target_x1 / self.img_width, target_x2 / self.img_width
  277. target_y1, target_y2 = target_y1 / self.img_height, target_y2 / self.img_height
  278. # Calculate normalized width and height
  279. target_w = target_x2 - target_x1
  280. target_h = target_y2 - target_y1
  281. # Calculate normalized center coordinates
  282. target_cx = target_x1 + target_w / 2
  283. target_cy = target_y1 + target_h / 2
  284. # Mock targets
  285. # Create a single target for one image with shape (1, 6).
  286. # Format: (index, label, cx, cy, w, h)
  287. targets = torch.tensor([[0, self.predefined_correct_class, target_cx, target_cy, target_w, target_h]], dtype=torch.float32).reshape(1, 6)
  288. # Define crowd target (unnormalized) coordinates within image dimensions
  289. crowd_target_x1, crowd_target_y1, crowd_target_x2, crowd_target_y2 = 10, 10, 20, 20
  290. # Normalize crowd target coordinates
  291. crowd_target_x1, crowd_target_x2 = crowd_target_x1 / self.img_width, crowd_target_x2 / self.img_width
  292. crowd_target_y1, crowd_target_y2 = crowd_target_y1 / self.img_height, crowd_target_y2 / self.img_height
  293. # Calculate normalized width and height for crowd target
  294. crowd_target_w = crowd_target_x2 - crowd_target_x1
  295. crowd_target_h = crowd_target_y2 - crowd_target_y1
  296. # Calculate normalized center coordinates for crowd target
  297. crowd_target_cx = crowd_target_x1 + crowd_target_w / 2
  298. crowd_target_cy = crowd_target_y1 + crowd_target_h / 2
  299. # Mock crowd targets
  300. # Create a single crowd target for one image with shape (1, 6).
  301. # Format: (index, label, cx, cy, w, h)
  302. crowd_targets = torch.tensor(
  303. [[0, self.predefined_correct_class, crowd_target_cx, crowd_target_cy, crowd_target_w, crowd_target_h]], dtype=torch.float32
  304. ).reshape(1, 6)
  305. self.metric = DetectionMetricsDistanceBased(
  306. num_cls=self.num_classes,
  307. post_prediction_callback=self.mock_post_prediction_callback,
  308. distance_thresholds=[5.0],
  309. score_thres=self.score_thres,
  310. distance_metric=ManhattanDistance(),
  311. )
  312. # Call the update method
  313. self.metric.update(preds=raw_preds, target=targets, device="cpu", inputs=self.img_tensor, crowd_targets=crowd_targets)
  314. # Call the compute method to get the results
  315. results = self.metric.compute()
  316. # Validate the results
  317. self.validate_results(results, precision=0, recall=0, mAP=0, F1=0, verbose=self.verbose, description=scenario)
  318. def test_distance_based_score_euclidean_distance_single_crowd_target_single_prediction_target_match(self):
  319. scenario = "A single prediction, single target and a single crowd target. Prediction match target and far from the crowd target."
  320. # Set random seeds for reproducibility (to ensure the seeds even at this level)
  321. torch.manual_seed(42)
  322. random.seed(42)
  323. # Mock raw_preds (model's output) in format cx, cy, w, h; coordinates within image dimensions
  324. # One prediction is 5px away from the center of the crowd target
  325. raw_preds = [torch.tensor([[15, 15, 10, 10]])] # Close to crowd target
  326. # Define target (unnormalized) coordinates within image dimensions
  327. target_x1, target_y1, target_x2, target_y2 = 10, 10, 20, 20
  328. # Normalize target coordinates
  329. target_x1, target_x2 = target_x1 / self.img_width, target_x2 / self.img_width
  330. target_y1, target_y2 = target_y1 / self.img_height, target_y2 / self.img_height
  331. # Calculate normalized width and height
  332. target_w = target_x2 - target_x1
  333. target_h = target_y2 - target_y1
  334. # Calculate normalized center coordinates
  335. target_cx = target_x1 + target_w / 2
  336. target_cy = target_y1 + target_h / 2
  337. # Mock targets
  338. # Create a single target for one image with shape (1, 6).
  339. # Format: (index, label, cx, cy, w, h)
  340. targets = torch.tensor([[0, self.predefined_correct_class, target_cx, target_cy, target_w, target_h]], dtype=torch.float32).reshape(1, 6)
  341. # Define crowd target (unnormalized) coordinates within image dimensions
  342. crowd_target_x1, crowd_target_y1, crowd_target_x2, crowd_target_y2 = 100, 100, 200, 200
  343. # Normalize crowd target coordinates
  344. crowd_target_x1, crowd_target_x2 = crowd_target_x1 / self.img_width, crowd_target_x2 / self.img_width
  345. crowd_target_y1, crowd_target_y2 = crowd_target_y1 / self.img_height, crowd_target_y2 / self.img_height
  346. # Calculate normalized width and height for crowd target
  347. crowd_target_w = crowd_target_x2 - crowd_target_x1
  348. crowd_target_h = crowd_target_y2 - crowd_target_y1
  349. # Calculate normalized center coordinates for crowd target
  350. crowd_target_cx = crowd_target_x1 + crowd_target_w / 2
  351. crowd_target_cy = crowd_target_y1 + crowd_target_h / 2
  352. # Mock crowd targets
  353. # Create a single crowd target for one image with shape (1, 6).
  354. # Format: (index, label, cx, cy, w, h)
  355. crowd_targets = torch.tensor(
  356. [[0, self.predefined_correct_class, crowd_target_cx, crowd_target_cy, crowd_target_w, crowd_target_h]], dtype=torch.float32
  357. ).reshape(1, 6)
  358. self.metric = DetectionMetricsDistanceBased(
  359. num_cls=self.num_classes,
  360. post_prediction_callback=self.mock_post_prediction_callback,
  361. distance_thresholds=[5.0],
  362. score_thres=self.score_thres,
  363. distance_metric=ManhattanDistance(),
  364. )
  365. # Call the update method
  366. self.metric.update(preds=raw_preds, target=targets, device="cpu", inputs=self.img_tensor, crowd_targets=crowd_targets)
  367. # Call the compute method to get the results
  368. results = self.metric.compute()
  369. # Validate the results
  370. self.validate_results(results, precision=1, recall=1, mAP=1, F1=1, verbose=self.verbose, description=scenario)
  371. # checks whether a single prediction that matches a single target will yield a perfect score
  372. # (Precision, Recall, F1 score, and mAP all set to 1.0). Using Euclidean distance.
  373. def test_distance_based_score_euclidean_distance_single_target_single_prediction_match(self):
  374. scenario = "a single prediction that matches a single target using Euclidean distance as a metric"
  375. # Set random seeds for reproducibility (to ensure the seeds even at this level)
  376. torch.manual_seed(42)
  377. random.seed(42)
  378. # Mock raw_preds (model's output) in format cx, cy, w, h; coordinates within image dimensions
  379. # One prediction is 5px away from the center of the target
  380. raw_preds = [torch.tensor([[15, 15, 10, 10]])] # Close to target
  381. # Define target (unnormalized) coordinates within image dimensions
  382. target_x1, target_y1, target_x2, target_y2 = 10, 10, 20, 20
  383. # Normalize target coordinates
  384. target_x1, target_x2 = target_x1 / self.img_width, target_x2 / self.img_width
  385. target_y1, target_y2 = target_y1 / self.img_height, target_y2 / self.img_height
  386. # Calculate normalized width and height
  387. target_w = target_x2 - target_x1
  388. target_h = target_y2 - target_y1
  389. # Calculate normalized center coordinates
  390. target_cx = target_x1 + target_w / 2
  391. target_cy = target_y1 + target_h / 2
  392. # Mock targets
  393. # Create a single target for one image with shape (1, 6).
  394. # Format: (index, label, cx, cy, w, h)
  395. targets = torch.tensor([[0, self.predefined_correct_class, target_cx, target_cy, target_w, target_h]], dtype=torch.float32).reshape(1, 6)
  396. self.metric = DetectionMetricsDistanceBased(
  397. num_cls=self.num_classes,
  398. post_prediction_callback=self.mock_post_prediction_callback,
  399. distance_thresholds=[5.0],
  400. score_thres=self.score_thres,
  401. distance_metric=EuclideanDistance(),
  402. )
  403. # Call the update method
  404. self.metric.update(preds=raw_preds, target=targets, device="cpu", inputs=self.img_tensor, crowd_targets=None)
  405. # Call the compute method to get the results
  406. results = self.metric.compute()
  407. # Validate the results
  408. self.validate_results(results, precision=1.0, recall=1.0, mAP=1.0, F1=1.0, verbose=self.verbose, description=scenario)
  409. # checks whether a single prediction that doesn't match the target will yield zero for all metrics.
  410. def test_distance_based_score_euclidean_distance_single_target_single_prediction_miss(self):
  411. scenario = "a single prediction that doesn't match the target using Euclidean distance as a metric"
  412. # Set random seeds for reproducibility (to ensure the seeds even at this level)
  413. torch.manual_seed(42)
  414. random.seed(42)
  415. # Mock raw_preds (model's output) in format cx, cy, w, h; coordinates within image dimensions
  416. # One prediction is more than 5px away from the center of the target
  417. raw_preds = [torch.tensor([[15, 15, 10, 10]])] # Far from target
  418. # Define target (unnormalized) coordinates within image dimensions
  419. target_x1, target_y1, target_x2, target_y2 = 40, 40, 80, 80
  420. # Normalize target coordinates
  421. target_x1, target_x2 = target_x1 / self.img_width, target_x2 / self.img_width
  422. target_y1, target_y2 = target_y1 / self.img_height, target_y2 / self.img_height
  423. # Calculate normalized width and height
  424. target_w = target_x2 - target_x1
  425. target_h = target_y2 - target_y1
  426. # Calculate normalized center coordinates
  427. target_cx = target_x1 + target_w / 2
  428. target_cy = target_y1 + target_h / 2
  429. # Mock targets
  430. # Create a single target for one image with shape (1, 6).
  431. # Format: (index, label, cx, cy, w, h)
  432. targets = torch.tensor([[0, self.predefined_correct_class, target_cx, target_cy, target_w, target_h]], dtype=torch.float32).reshape(1, 6)
  433. self.metric = DetectionMetricsDistanceBased(
  434. num_cls=self.num_classes,
  435. post_prediction_callback=self.mock_post_prediction_callback,
  436. distance_thresholds=[5.0],
  437. score_thres=self.score_thres,
  438. distance_metric=EuclideanDistance(),
  439. )
  440. # Call the update method
  441. self.metric.update(preds=raw_preds, target=targets, device="cpu", inputs=self.img_tensor, crowd_targets=None)
  442. # Call the compute method to get the results
  443. results = self.metric.compute()
  444. # Validate the results
  445. self.validate_results(results, precision=0, recall=0, mAP=0, F1=0, verbose=self.verbose, description=scenario)
  446. # checks whether the metrics are calculated correctly when there are multiple
  447. # predictions but only one matches with a single target.
  448. def test_distance_based_score_euclidean_distance_single_target_few_predictions(self):
  449. scenario = "a few predictions 1 - match, 2 - don't, single target using Euclidean distance as a metric"
  450. # Set random seeds for reproducibility (to ensure the seeds even at this level)
  451. torch.manual_seed(42)
  452. random.seed(42)
  453. # Mock raw_preds (model's output) in format cx, cy, w, h; coordinates within image dimensions
  454. # One prediction is 5px away from the center of the target
  455. # The other two predictions are placed randomly
  456. raw_preds = [torch.tensor([[15, 15, 10, 10], [100, 50, 10, 10], [200, 300, 20, 15]])] # Close to target # Randomly placed # Randomly placed
  457. # Define target (unnormalized) coordinates within image dimensions
  458. target_x1, target_y1, target_x2, target_y2 = 10, 10, 20, 20
  459. # Normalize target coordinates
  460. target_x1, target_x2 = target_x1 / self.img_width, target_x2 / self.img_width
  461. target_y1, target_y2 = target_y1 / self.img_height, target_y2 / self.img_height
  462. # Calculate normalized width and height
  463. target_w = target_x2 - target_x1
  464. target_h = target_y2 - target_y1
  465. # Calculate normalized center coordinates
  466. target_cx = target_x1 + target_w / 2
  467. target_cy = target_y1 + target_h / 2
  468. # Mock targets
  469. # Create a single target for one image with shape (1, 6).
  470. # Format: (index, label, cx, cy, w, h)
  471. targets = torch.tensor([[0, self.predefined_correct_class, target_cx, target_cy, target_w, target_h]], dtype=torch.float32).reshape(1, 6)
  472. # Call the update method
  473. self.metric.update(preds=raw_preds, target=targets, device="cpu", inputs=self.img_tensor, crowd_targets=None)
  474. # Call the compute method to get the results
  475. results = self.metric.compute()
  476. # Validate the results
  477. self.validate_results(results, precision=0.3333, recall=1.0, mAP=1, F1=0.5, verbose=self.verbose, description=scenario)
  478. if __name__ == "__main__":
  479. unittest.main()
Tip!

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

Comments

Loading...