Box IoU and Detection Average Precision
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: hard
Interview Round: Other
Implement `box_iou(boxes_a, boxes_b)` returning the pairwise IoU matrix (shape `(N, M)`) for `[x1, y1, x2, y2]` boxes. Then implement `detection_average_precision(det_boxes, det_scores, det_image_ids, gt_boxes, gt_image_ids, iou_threshold=0.5)` returning all-point interpolated AP as a `float`.
The functions must follow these rules:
- IoU: negative widths and heights clip to 0, and a zero union gives `0.0`.
- Process detections by descending score. The sort is stable, so ties keep input order.
- Each detection considers only still-unmatched ground truths in its own image and picks the highest-IoU one. It is a TP if that IoU is `>= iou_threshold`, and that ground truth becomes matched. Otherwise it is an FP.
- AP sums the recall gains weighted by the best precision at or after each rank, with $r_0 = 0$:
$$
\text{AP} = \sum_{k} (r_k - r_{k-1}) \cdot \max_{j \ge k} p_j
$$
- No ground truths → `nan`. No detections (with ground truths present) → `0.0`.
Example:
```python
gt_boxes = [[0, 0, 4, 4], [10, 10, 14, 14]]
gt_image_ids = ["img_a", "img_b"]
det_boxes = [[20, 20, 24, 24], [0, 0, 4, 4], [10, 10, 14, 14]]
det_scores = [0.95, 0.6, 0.4]
det_image_ids = ["img_a", "img_a", "img_b"]
detection_average_precision(det_boxes, det_scores, det_image_ids, gt_boxes, gt_image_ids)
# 0.6667
# ranks: FP, TP, TP -> precision [0, 1/2, 2/3], recall [0, 1/2, 1]
# envelope [2/3, 2/3, 2/3], AP = 0.5 * 2/3 + 0.5 * 2/3
```
The top-scoring detection is in `img_a` but does not overlap that image's ground truth, so it is a false positive. The other two detections match their ground truths exactly.
```hint Vectorized IoU
Add axes so the corner coordinates of `boxes_a` and `boxes_b` broadcast against each other to shape `(N, M)`, and guard the division for pairs whose union is zero.
```
```hint Precision and recall per rank
Once each ranked detection has a 0/1 TP flag, one cumulative sum gives both curves. The envelope is a running maximum, and its direction matters.
```
```hint Tied scores
Check which sorting algorithm `np.argsort` uses by default and whether it keeps the input order of equal keys.
```
### Constraints & Assumptions
- Inputs may be lists or NumPy arrays, and may be empty.
- Image ids are hashable scalars (ints or strings) compared by equality.
- Scores are finite. The detection arrays have matching lengths, and so do the ground-truth arrays.
### What a Strong Answer Covers
- A vectorized `box_iou` that broadcasts to `(N, M)`, clips negative widths and heights, and returns 0.0 where the union is zero.
- Stable descending-score ordering and greedy matching restricted to unmatched ground truths in the same image.
- Precision and recall from cumulative true positives, a non-increasing precision envelope, and the all-point sum starting from recall 0.
- The `nan` and `0.0` results for empty inputs.
- The cost of the matching pass and how it grows with the number of detections and ground truths.
### Follow-up Questions
- How would you extend this to multi-class mAP and COCO-style mAP@[.5:.95]?
- How would you handle "difficult" or crowd ground truths?
- The per-detection scan over all ground truths is $O(D \cdot G)$. How would you scale it?
Overview: Implement pairwise box IoU and all-point average precision for object detection, matching score-ordered detections to ground truths within each image. It tests NumPy broadcasting, precision and recall curves, interpolation, and careful handling of tied scores and empty inputs.