Stores all the information necessary to calculate the AP for one IoU and one class. Note: I type annotated this because why not.
| 252 | ap_obj.push(score_func(i), False) |
| 253 | |
| 254 | class APDataObject: |
| 255 | """ |
| 256 | Stores all the information necessary to calculate the AP for one IoU and one class. |
| 257 | Note: I type annotated this because why not. |
| 258 | """ |
| 259 | |
| 260 | def __init__(self): |
| 261 | self.data_points = [] |
| 262 | self.num_gt_positives = 0 |
| 263 | |
| 264 | def push(self, score: float, is_true: bool): |
| 265 | self.data_points.append((score, is_true)) |
| 266 | |
| 267 | def add_gt_positives(self, num_positives: int): |
| 268 | """ Call this once per image. """ |
| 269 | self.num_gt_positives += num_positives |
| 270 | |
| 271 | def is_empty(self) -> bool: |
| 272 | return len(self.data_points) == 0 and self.num_gt_positives == 0 |
| 273 | |
| 274 | def get_ap(self) -> float: |
| 275 | """ Warning: result not cached. """ |
| 276 | |
| 277 | if self.num_gt_positives == 0: |
| 278 | return 0 |
| 279 | |
| 280 | # Sort descending by score |
| 281 | self.data_points.sort(key=lambda x: -x[0]) |
| 282 | |
| 283 | precisions = [] |
| 284 | recalls = [] |
| 285 | num_true = 0 |
| 286 | num_false = 0 |
| 287 | |
| 288 | # Compute the precision-recall curve. The x axis is recalls and the y axis precisions. |
| 289 | for datum in self.data_points: |
| 290 | # datum[1] is whether the detection a true or false positive |
| 291 | if datum[1]: |
| 292 | num_true += 1 |
| 293 | else: |
| 294 | num_false += 1 |
| 295 | |
| 296 | precision = num_true / (num_true + num_false) |
| 297 | recall = num_true / self.num_gt_positives |
| 298 | |
| 299 | precisions.append(precision) |
| 300 | recalls.append(recall) |
| 301 | |
| 302 | # Smooth the curve by computing [max(precisions[i:]) for i in range(len(precisions))] |
| 303 | # Basically, remove any temporary dips from the curve. |
| 304 | # At least that's what I think, idk. COCOEval did it so I do too. |
| 305 | for i in range(len(precisions)-1, 0, -1): |
| 306 | if precisions[i] > precisions[i-1]: |
| 307 | precisions[i-1] = precisions[i] |
| 308 | |
| 309 | # Compute the integral of precision(recall) d_recall from recall=0->1 using fixed-length riemann summation with 101 bars. |
| 310 | # idx 0 is recall == 0.0 and idx 100 is recall == 1.00 |
| 311 | y_range = [0] * 101 |