File size: 1,948 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
"""Image-level multi-label classification 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_classification_metrics(
    predictions: list[InferenceResponse], ground_truths: list[GoldRecord]
) -> dict:
    """Compare class sets; repeated detections of one class count once."""
    gt_by_id = {record.image_id: record for record in ground_truths}
    counts: dict[str, ViolationCounts] = defaultdict(ViolationCounts)
    negatives = true_negatives = false_positive_images = evaluated = 0
    for prediction in predictions:
        record = gt_by_id.get(prediction.image_id)
        if record is None or record.gold.reported:
            continue
        evaluated += 1
        gt_labels = {item.use_case_id for item in record.gold.violations}
        pred_labels = {to_use_case_id(item.category_id) for item in prediction.detections}
        for label in gt_labels | pred_labels:
            target = counts[label]
            if label in gt_labels and label in pred_labels:
                target.tp += 1
            elif label in pred_labels:
                target.fp += 1
            else:
                target.fn += 1
        if record.gold.no_violation_detected:
            negatives += 1
            if pred_labels:
                false_positive_images += 1
            else:
                true_negatives += 1
    return {
        "per_violation": summarise_counts(counts),
        "summary": aggregate_summary(counts),
        "n_images": evaluated,
        "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,
    }