"""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, }