File size: 4,664 Bytes
7825400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Instance-level, class-aware localisation metrics."""

from collections import defaultdict

from metrics._f_beta import ViolationCounts, aggregate_summary, summarise_counts
from metrics._labels import to_use_case_id
from schemas.ground_truth import GoldRecord
from schemas.inference import InferenceResponse


def _compute_iou(a: list[float], b: list[float]) -> float:
    ax1, ay1, aw, ah = a
    bx1, by1, bw, bh = b
    intersection = max(0.0, min(ax1 + aw, bx1 + bw) - max(ax1, bx1)) * max(
        0.0, min(ay1 + ah, by1 + bh) - max(ay1, by1)
    )
    union = aw * ah + bw * bh - intersection
    return intersection / union if union > 0 else 0.0


def maximum_match_pairs(
    pred_boxes: list[list[float]], gt_boxes: list[list[float]], threshold: float
) -> list[tuple[int, int, float]]:
    """Return deterministic prediction/GT pairs and their IoUs.

    The aggregate scorer only needs the number of matches, while presentation
    and audit tooling needs to show which exact boxes produced that number.
    Keeping both readings on this one matcher prevents the image inspector from
    drifting away from the published metric.
    """
    candidates = [
        sorted(
            (
                index
                for index, gt in enumerate(gt_boxes)
                if _compute_iou(box, gt) >= threshold
            ),
            key=lambda index: (-_compute_iou(box, gt_boxes[index]), index),
        )
        for box in pred_boxes
    ]
    gt_owner: dict[int, int] = {}

    def assign(pred_index: int, seen: set[int]) -> bool:
        for gt_index in candidates[pred_index]:
            if gt_index in seen:
                continue
            seen.add(gt_index)
            owner = gt_owner.get(gt_index)
            if owner is None or assign(owner, seen):
                gt_owner[gt_index] = pred_index
                return True
        return False

    for index in range(len(pred_boxes)):
        assign(index, set())
    return sorted(
        (
            (pred_index, gt_index, _compute_iou(pred_boxes[pred_index], gt_boxes[gt_index]))
            for gt_index, pred_index in gt_owner.items()
        ),
        key=lambda pair: pair[0],
    )


def _maximum_matches(
    pred_boxes: list[list[float]], gt_boxes: list[list[float]], threshold: float
) -> int:
    """Return the count used by the baseline aggregate report."""
    return len(maximum_match_pairs(pred_boxes, gt_boxes, threshold))


def compute_localisation_metrics(
    predictions: list[InferenceResponse],
    ground_truths: list[GoldRecord],
    iou_threshold: float = 0.50,
) -> dict:
    """Match every prediction and gold instance at most once, within its class."""
    gt_by_id = {record.image_id: record for record in ground_truths}
    counts: dict[str, ViolationCounts] = defaultdict(ViolationCounts)
    n_predictions = n_gt_boxes = evaluated = 0
    negatives = true_negatives = false_positive_images = 0
    for prediction in predictions:
        record = gt_by_id.get(prediction.image_id)
        if record is None or record.gold.reported:
            continue
        evaluated += 1
        n_predictions += len(prediction.detections)
        n_gt_boxes += len(record.gold.violations)
        gt_by_label: dict[str, list[list[float]]] = defaultdict(list)
        pred_by_label: dict[str, list[list[float]]] = defaultdict(list)
        for item in record.gold.violations:
            gt_by_label[item.use_case_id].append(item.bbox)
        for item in prediction.detections:
            pred_by_label[to_use_case_id(item.category_id)].append(item.bbox)
        for label in gt_by_label.keys() | pred_by_label.keys():
            gt_boxes, pred_boxes = gt_by_label[label], pred_by_label[label]
            matches = _maximum_matches(pred_boxes, gt_boxes, iou_threshold)
            counts[label].tp += matches
            counts[label].fp += len(pred_boxes) - matches
            counts[label].fn += len(gt_boxes) - matches
        if record.gold.no_violation_detected:
            negatives += 1
            if prediction.detections:
                false_positive_images += 1
            else:
                true_negatives += 1
    return {
        "per_violation": summarise_counts(counts),
        "summary": aggregate_summary(counts),
        "iou_threshold": iou_threshold,
        "n_images": evaluated,
        "n_predictions": n_predictions,
        "n_gt_boxes": n_gt_boxes,
        "negative_images": negatives,
        "true_negative_images": true_negatives,
        "false_positive_images": false_positive_images,
        "negative_false_positive_rate": round(false_positive_images / negatives, 4) if negatives else None,
    }