Datasets:
Download code/metrics/semantic.py from govtech/municipalbench-full: direct link, hf CLI and curl.
- Browser
- Download file 10.8 kB
-
https://huggingface.co/datasets/govtech/municipalbench-full/resolve/main/code/metrics/semantic.py
- Command line
-
hf download hf://datasets/govtech/municipalbench-full/code/metrics/semantic.py
-
curl -L -o semantic.py https://huggingface.co/datasets/govtech/municipalbench-full/resolve/main/code/metrics/semantic.py
10.8 kB
| """Taxonomy-relaxed metrics driven by a frozen semantic-pair policy.""" | |
| from __future__ import annotations | |
| from collections import defaultdict | |
| from dataclasses import dataclass | |
| from metrics._f_beta import ViolationCounts, aggregate_summary, summarise_counts | |
| from metrics._labels import to_use_case_id | |
| from metrics.localisation import _compute_iou, maximum_match_pairs | |
| from schemas.ground_truth import GoldRecord | |
| from schemas.inference import InferenceResponse | |
| class SemanticPolicy: | |
| """A symmetric class-pair acceptance matrix with similarity provenance.""" | |
| class_ids: tuple[str, ...] | |
| similarities: tuple[tuple[float, ...], ...] | |
| accepted: tuple[tuple[int, ...], ...] | |
| def from_dict(cls, payload: dict) -> "SemanticPolicy": | |
| return cls( | |
| class_ids=tuple(payload["class_ids"]), | |
| similarities=tuple(tuple(row) for row in payload["cosine_matrix"]), | |
| accepted=tuple(tuple(row) for row in payload["accepted_matrix"]), | |
| ) | |
| def _indices(self, predicted: str, gold: str) -> tuple[int, int] | None: | |
| try: | |
| return self.class_ids.index(predicted), self.class_ids.index(gold) | |
| except ValueError: | |
| return None | |
| def allows(self, predicted: str, gold: str) -> bool: | |
| indices = self._indices(predicted, gold) | |
| return bool(indices and self.accepted[indices[0]][indices[1]]) | |
| def similarity(self, predicted: str, gold: str) -> float: | |
| indices = self._indices(predicted, gold) | |
| return self.similarities[indices[0]][indices[1]] if indices else 0.0 | |
| def _maximum_semantic_pairs( | |
| predicted: list[str], gold: list[str], policy: SemanticPolicy | |
| ) -> list[tuple[int, int]]: | |
| """Maximum-cardinality deterministic matching for non-exact class pairs.""" | |
| candidates = [ | |
| sorted( | |
| (j for j, gold_id in enumerate(gold) if pred_id != gold_id and policy.allows(pred_id, gold_id)), | |
| key=lambda j: (-policy.similarity(pred_id, gold[j]), j), | |
| ) | |
| for pred_id in predicted | |
| ] | |
| gold_owner: dict[int, int] = {} | |
| def assign(pred_index: int, seen: set[int]) -> bool: | |
| for gold_index in candidates[pred_index]: | |
| if gold_index in seen: | |
| continue | |
| seen.add(gold_index) | |
| owner = gold_owner.get(gold_index) | |
| if owner is None or assign(owner, seen): | |
| gold_owner[gold_index] = pred_index | |
| return True | |
| return False | |
| for pred_index in sorted( | |
| range(len(predicted)), | |
| key=lambda i: (-max((policy.similarity(predicted[i], gold[j]) for j in candidates[i]), default=0.0), i), | |
| ): | |
| assign(pred_index, set()) | |
| return sorted((pred_index, gold_index) for gold_index, pred_index in gold_owner.items()) | |
| def _negative_fields(prediction_labels: set[str], record: GoldRecord, totals: dict) -> None: | |
| if record.gold.no_violation_detected: | |
| totals["negative_images"] += 1 | |
| if prediction_labels: | |
| totals["false_positive_images"] += 1 | |
| else: | |
| totals["true_negative_images"] += 1 | |
| def compute_semantic_classification_metrics( | |
| predictions: list[InferenceResponse], | |
| ground_truths: list[GoldRecord], | |
| policy: SemanticPolicy, | |
| ) -> dict: | |
| """Score unique class sets with exact-first, one-to-one semantic matching.""" | |
| gt_by_id = {record.image_id: record for record in ground_truths} | |
| counts: dict[str, ViolationCounts] = defaultdict(ViolationCounts) | |
| totals = {"negative_images": 0, "true_negative_images": 0, "false_positive_images": 0} | |
| credited = [] | |
| 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} | |
| exact = gt_labels & pred_labels | |
| for label in exact: | |
| counts[label].tp += 1 | |
| unmatched_pred = sorted(pred_labels - exact) | |
| unmatched_gt = sorted(gt_labels - exact) | |
| pairs = _maximum_semantic_pairs(unmatched_pred, unmatched_gt, policy) | |
| matched_pred = {pred_index for pred_index, _ in pairs} | |
| matched_gt = {gold_index for _, gold_index in pairs} | |
| for pred_index, gold_index in pairs: | |
| predicted_id, gold_id = unmatched_pred[pred_index], unmatched_gt[gold_index] | |
| counts[gold_id].tp += 1 | |
| credited.append({ | |
| "image_id": prediction.image_id, | |
| "predicted_class": predicted_id, | |
| "gold_class": gold_id, | |
| "similarity": round(policy.similarity(predicted_id, gold_id), 6), | |
| }) | |
| for index, label in enumerate(unmatched_pred): | |
| if index not in matched_pred: | |
| counts[label].fp += 1 | |
| for index, label in enumerate(unmatched_gt): | |
| if index not in matched_gt: | |
| counts[label].fn += 1 | |
| _negative_fields(pred_labels, record, totals) | |
| negatives = totals["negative_images"] | |
| return { | |
| "per_violation": summarise_counts(counts), | |
| "summary": aggregate_summary(counts), | |
| "n_images": evaluated, | |
| **totals, | |
| "negative_false_positive_rate": round(totals["false_positive_images"] / negatives, 4) if negatives else None, | |
| "credited_matches": credited, | |
| } | |
| def _maximum_semantic_box_pairs(predictions: list[dict], gold: list[dict], policy: SemanticPolicy, threshold: float) -> list[tuple[int, int, float]]: | |
| candidates = [ | |
| sorted( | |
| ( | |
| j for j, target in enumerate(gold) | |
| if item["label"] != target["label"] | |
| and policy.allows(item["label"], target["label"]) | |
| and _compute_iou(item["bbox"], target["bbox"]) >= threshold | |
| ), | |
| key=lambda j: ( | |
| -policy.similarity(item["label"], gold[j]["label"]), | |
| -_compute_iou(item["bbox"], gold[j]["bbox"]), | |
| gold[j]["index"], | |
| ), | |
| ) | |
| for item in predictions | |
| ] | |
| gold_owner: dict[int, int] = {} | |
| def assign(pred_index: int, seen: set[int]) -> bool: | |
| for gold_index in candidates[pred_index]: | |
| if gold_index in seen: | |
| continue | |
| seen.add(gold_index) | |
| owner = gold_owner.get(gold_index) | |
| if owner is None or assign(owner, seen): | |
| gold_owner[gold_index] = pred_index | |
| return True | |
| return False | |
| for pred_index in sorted(range(len(predictions)), key=lambda i: predictions[i]["index"]): | |
| assign(pred_index, set()) | |
| return sorted( | |
| ( | |
| pred_index, | |
| gold_index, | |
| _compute_iou(predictions[pred_index]["bbox"], gold[gold_index]["bbox"]), | |
| ) | |
| for gold_index, pred_index in gold_owner.items() | |
| ) | |
| def compute_semantic_localisation_metrics( | |
| predictions: list[InferenceResponse], | |
| ground_truths: list[GoldRecord], | |
| policy: SemanticPolicy, | |
| iou_threshold: float = 0.50, | |
| ) -> dict: | |
| """Score boxes with exact-label matches first, then accepted class pairs.""" | |
| gt_by_id = {record.image_id: record for record in ground_truths} | |
| counts: dict[str, ViolationCounts] = defaultdict(ViolationCounts) | |
| totals = {"negative_images": 0, "true_negative_images": 0, "false_positive_images": 0} | |
| credited = [] | |
| evaluated = n_predictions = n_gt_boxes = 0 | |
| for prediction in predictions: | |
| record = gt_by_id.get(prediction.image_id) | |
| if record is None or record.gold.reported: | |
| continue | |
| evaluated += 1 | |
| pred_items = [ | |
| {"index": i, "label": to_use_case_id(item.category_id), "bbox": item.bbox} | |
| for i, item in enumerate(prediction.detections) | |
| ] | |
| gt_items = [ | |
| {"index": i, "label": item.use_case_id, "bbox": item.bbox} | |
| for i, item in enumerate(record.gold.violations) | |
| ] | |
| n_predictions += len(pred_items) | |
| n_gt_boxes += len(gt_items) | |
| matched_pred: set[int] = set() | |
| matched_gt: set[int] = set() | |
| labels = {item["label"] for item in pred_items + gt_items} | |
| for label in sorted(labels): | |
| preds = [item for item in pred_items if item["label"] == label] | |
| golds = [item for item in gt_items if item["label"] == label] | |
| for local_pred, local_gt, _ in maximum_match_pairs( | |
| [item["bbox"] for item in preds], [item["bbox"] for item in golds], iou_threshold | |
| ): | |
| matched_pred.add(preds[local_pred]["index"]) | |
| matched_gt.add(golds[local_gt]["index"]) | |
| counts[label].tp += 1 | |
| remaining_pred = [item for item in pred_items if item["index"] not in matched_pred] | |
| remaining_gt = [item for item in gt_items if item["index"] not in matched_gt] | |
| semantic_pairs = _maximum_semantic_box_pairs(remaining_pred, remaining_gt, policy, iou_threshold) | |
| semantic_pred = {pred_index for pred_index, _, _ in semantic_pairs} | |
| semantic_gt = {gold_index for _, gold_index, _ in semantic_pairs} | |
| for pred_index, gold_index, iou in semantic_pairs: | |
| pred_item, gold_item = remaining_pred[pred_index], remaining_gt[gold_index] | |
| counts[gold_item["label"]].tp += 1 | |
| credited.append({ | |
| "image_id": prediction.image_id, | |
| "prediction_index": pred_item["index"], | |
| "gold_index": gold_item["index"], | |
| "predicted_class": pred_item["label"], | |
| "gold_class": gold_item["label"], | |
| "similarity": round(policy.similarity(pred_item["label"], gold_item["label"]), 6), | |
| "iou": round(iou, 6), | |
| }) | |
| for index, item in enumerate(remaining_pred): | |
| if index not in semantic_pred: | |
| counts[item["label"]].fp += 1 | |
| for index, item in enumerate(remaining_gt): | |
| if index not in semantic_gt: | |
| counts[item["label"]].fn += 1 | |
| _negative_fields({item["label"] for item in pred_items}, record, totals) | |
| negatives = totals["negative_images"] | |
| 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, | |
| **totals, | |
| "negative_false_positive_rate": round(totals["false_positive_images"] / negatives, 4) if negatives else None, | |
| "credited_matches": credited, | |
| } | |