Datasets:
Download code/metrics/annotation_agreement.py from govtech/municipalbench-full: direct link, hf CLI and curl.
- Browser
- Download file 16.4 kB
-
https://huggingface.co/datasets/govtech/municipalbench-full/resolve/main/code/metrics/annotation_agreement.py
- Command line
-
hf download hf://datasets/govtech/municipalbench-full/code/metrics/annotation_agreement.py
-
curl -L -o annotation_agreement.py https://huggingface.co/datasets/govtech/municipalbench-full/resolve/main/code/metrics/annotation_agreement.py
16.4 kB
| """Symmetric first-pass agreement; no annotation is treated as ground truth. | |
| Per-image sufficient statistics make the cluster bootstrap exact without | |
| re-solving identical box assignments on every resample. | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| import math | |
| from collections import Counter | |
| from itertools import combinations | |
| import numpy as np | |
| from scipy.optimize import linear_sum_assignment | |
| from metrics.localisation import _compute_iou | |
| from metrics.semantic import SemanticPolicy | |
| METHOD_VERSION = "d2-v2-ordinal" | |
| RATING_WIDTH = 43 # Existing summaries, five category counts, 5×5 coincidences. | |
| THRESHOLDS = tuple(i / 10 for i in range(1, 10)) | |
| SEED = 20260911 | |
| def valid_box(box): | |
| return (isinstance(box, list) and len(box) == 4 | |
| and all(type(x) in (int, float) and math.isfinite(x) for x in box) | |
| and box[0] >= 0 and box[1] >= 0 and box[2] > 0 and box[3] > 0 | |
| and box[0] + box[2] <= 1 and box[1] + box[3] <= 1) | |
| def canonical_items(items): | |
| return sorted(items, key=lambda v: (v["use_case_id"], tuple(v.get("bbox") or []))) | |
| def match_items(left, right, policy=None, threshold=None): | |
| """Exact first, then accepted semantic edges. Cardinality precedes IoU. | |
| Canonical side orientation also fixes tie decisions when raters are swapped. | |
| Returned indices refer to the supplied arrays, including duplicate instances. | |
| """ | |
| key = lambda items: tuple((v["use_case_id"], tuple(v.get("bbox") or [])) for v in items) | |
| li = sorted(range(len(left)), key=lambda i: key([left[i]])) | |
| ri = sorted(range(len(right)), key=lambda i: key([right[i]])) | |
| a, b = [left[i] for i in li], [right[i] for i in ri] | |
| swapped = key(a) > key(b) | |
| if swapped: | |
| a, b = b, a | |
| matches = [] | |
| for semantic in (False, True) if policy else (False,): | |
| used_a = {i for i, _, _, _ in matches} | |
| used_b = {j for _, j, _, _ in matches} | |
| aa = [i for i in range(len(a)) if i not in used_a] | |
| bb = [j for j in range(len(b)) if j not in used_b] | |
| if not aa or not bb: | |
| continue | |
| weights = np.zeros((len(aa), len(bb))) | |
| overlaps = {} | |
| for x, i in enumerate(aa): | |
| for y, j in enumerate(bb): | |
| ca, cb = a[i]["use_case_id"], b[j]["use_case_id"] | |
| accepted = (ca != cb and policy.allows(ca, cb)) if semantic else ca == cb | |
| overlap = _compute_iou(a[i]["bbox"], b[j]["bbox"]) if threshold is not None else 1.0 | |
| if accepted and (threshold is None or overlap >= threshold): | |
| # One additional match outweighs every possible IoU gain. | |
| weights[x, y] = min(len(aa), len(bb)) + 1 + overlap | |
| overlaps[x, y] = overlap | |
| xs, ys = linear_sum_assignment(weights, maximize=True) | |
| matches.extend((aa[x], bb[y], overlaps[x, y], semantic) | |
| for x, y in zip(xs, ys) if weights[x, y] > 0) | |
| return sorted((li[j], ri[i], overlap, semantic) if swapped else | |
| (li[i], ri[j], overlap, semantic) for i, j, overlap, semantic in matches) | |
| def alpha_from_totals(n, total, squares, observed): | |
| """Interval alpha from pairable ratings and ordered coincidence cost.""" | |
| n, total, squares, observed = np.broadcast_arrays(n, total, squares, observed) | |
| expected_numerator = 2 * (n * squares - total * total) | |
| out = np.full(n.shape, np.nan, dtype=float) | |
| np.divide(observed * (n - 1), expected_numerator, out=out, | |
| where=(n > 1) & (expected_numerator > 0)) | |
| return 1 - out | |
| def rating_statistics(labels, field): | |
| values = [a[field] for a in labels if not a.get("reported") | |
| and type(a.get(field)) is int and 1 <= a[field] <= 5] | |
| out = np.zeros(RATING_WIDTH) | |
| if len(values) < 2: | |
| return out | |
| n, total, squares = len(values), sum(values), sum(x*x for x in values) | |
| spread = max(values) - min(values) | |
| out[:8] = [1, spread == 0, spread <= 1, n, total, squares, | |
| 2 * (n * squares - total * total) / (n - 1), 0] | |
| out[8 + spread] = 1 | |
| counts = np.bincount(values, minlength=6)[1:6].astype(float) | |
| out[13:18] = counts | |
| out[18:] = ((np.outer(counts, counts) - np.diag(counts)) / (n - 1)).ravel() | |
| return out | |
| def ordinal_alpha_from_totals(totals): | |
| """Standard ordinal alpha using this sample's cumulative category midranks. | |
| Category frequencies and distances are rebuilt for every bootstrap sample, | |
| not frozen to the original population. Coincidences count every ordered | |
| within-image pair with 1/(m-1) normalisation. | |
| """ | |
| counts = totals[:, 13:18] | |
| n = counts.sum(axis=1) | |
| midranks = counts.cumsum(axis=1) - counts / 2 | |
| distance = (midranks[:, :, None] - midranks[:, None, :]) ** 2 | |
| coincidences = totals[:, 18:].reshape(-1, 5, 5) | |
| observed = (coincidences * distance).sum(axis=(1, 2)) | |
| expected = (counts[:, :, None] * counts[:, None, :] * distance).sum(axis=(1, 2)) | |
| cost = np.full(n.shape, np.nan) | |
| np.divide(observed * (n - 1), expected, out=cost, | |
| where=(n > 1) & (expected > 0) & (totals[:, 0] >= 2)) | |
| return 1 - cost | |
| def ratio(a, b): | |
| a, b = np.broadcast_arrays(a, b) | |
| return np.divide(a, b, out=np.full(a.shape, np.nan), where=b > 0) | |
| def bootstrap_estimates(rows, evaluator, names, *, seed=SEED, replicates=2000): | |
| """Image bootstrap, compressed by identical sufficient-statistic vectors. | |
| Multinomial resampling of pattern counts is exactly resampling images with | |
| replacement, including zero-contribution images, not a pair bootstrap. | |
| """ | |
| rows = np.asarray(rows, dtype=float) | |
| totals = rows.sum(axis=0) | |
| values = np.asarray(evaluator(totals[None, :]))[0] | |
| samples = np.empty((0, len(names))) | |
| if len(rows) >= 2 and replicates: | |
| patterns, counts = np.unique(rows, axis=0, return_counts=True) | |
| rng = np.random.default_rng(seed) | |
| chunks = [] | |
| for start in range(0, replicates, 100): | |
| weights = rng.multinomial(len(rows), counts / len(rows), size=min(100, replicates-start)) | |
| chunks.append(evaluator(weights @ patterns)) | |
| samples = np.concatenate(chunks) | |
| result = {} | |
| for i, name in enumerate(names): | |
| value = float(values[i]) if np.isfinite(values[i]) else None | |
| finite = samples[:, i][np.isfinite(samples[:, i])] if len(samples) else [] | |
| ci = [float(x) for x in np.percentile(finite, [2.5, 97.5])] if ( | |
| value is not None and len(finite) >= .95 * replicates and len(finite) > 0) else None | |
| result[name] = {"value": value, "ci": ci, "bootstrap_valid": len(finite), | |
| "reason": None if value is not None else "No eligible denominator or no variation"} | |
| return result | |
| def rating_summary(rows, *, seed=SEED, replicates=2000): | |
| rows = np.asarray(rows, dtype=float).reshape(-1, RATING_WIDTH) | |
| rows = rows[rows[:, 0] > 0] | |
| def evaluate(t): | |
| alpha = alpha_from_totals(t[:, 3], t[:, 4], t[:, 5], t[:, 6]) | |
| alpha[t[:, 0] < 2] = np.nan | |
| return np.column_stack((ratio(t[:, 1], t[:, 0]), ratio(t[:, 2], t[:, 0]), | |
| ordinal_alpha_from_totals(t), alpha)) | |
| result = bootstrap_estimates(rows, evaluate, | |
| ["exact", "within_one", "alpha", "interval_alpha"], seed=seed, replicates=replicates) | |
| result["alpha"]["level"] = "ordinal" | |
| result["interval_alpha"]["level"] = "interval" | |
| totals = rows.sum(axis=0) | |
| return {**result, "eligible": len(rows), "ratings": int(totals[3]), | |
| "exact_count": int(totals[1]), "within_one_count": int(totals[2]), | |
| "ranges": totals[8:13].astype(int).tolist(), "limited_support": len(rows) < 10} | |
| # Columns are additive across images; weighted counts and raw counts are separate. | |
| FIELDS = ("label_n exact label_pairs clean_pairs " | |
| "positive_images both_positive unilateral both_absent alpha_n alpha_sum alpha_o " | |
| "label_endpoints semantic_label_endpoints " | |
| "box_n box_positive box_pairs empty_box_pairs box_endpoints raw_box_endpoints " | |
| "iou_sum raw_matches semantic_box_endpoints " | |
| + " ".join(f"match_{i}" for i in range(1, 10)) + " " | |
| + " ".join(f"iou_bin_{i}" for i in range(10))).split() | |
| F = {name: i for i, name in enumerate(FIELDS)} | |
| def prepare_image(row, gold, category, domains, policy): | |
| """Keep public statistical inputs separate from anonymised private evidence.""" | |
| taxonomy = {c for ids in domains.values() for c in ids} | |
| labels = [] | |
| audit = Counter() | |
| for a in row["first_pass"]: | |
| items = canonical_items(a.get("violations", [])) | |
| known = all(v.get("use_case_id") in taxonomy for v in items) | |
| state_ok = (type(a.get("no_violation_detected")) is bool | |
| and a["no_violation_detected"] != bool(items)) | |
| usable = not a.get("reported") and known and state_ok | |
| geometry = all(valid_box(v.get("bbox")) for v in items) | |
| audit["reported"] += bool(a.get("reported")) | |
| audit["unknown_class"] += not known | |
| audit["invalid_state"] += not a.get("reported") and not state_ok | |
| audit["invalid_geometry"] += not geometry | |
| labels.append({"label": f"Label {chr(65+len(labels))}", | |
| "plausibility": a.get("plausibility"), "naturalness": a.get("naturalness"), | |
| "reported": bool(a.get("reported")), "label_eligible": usable, | |
| "box_eligible": usable and geometry, | |
| "no_violation_detected": a.get("no_violation_detected"), | |
| "violations": [{"use_case_id": v["use_case_id"], | |
| "name": v.get("use_case_name", v["use_case_id"]), | |
| "bbox": v.get("bbox") if valid_box(v.get("bbox")) else None} for v in items]}) | |
| sets = {i: {v["use_case_id"] for v in a["violations"]} for i, a in enumerate(labels) if a["label_eligible"]} | |
| label_pairs = list(combinations(sets, 2)) | |
| box_pairs = list(combinations([i for i, a in enumerate(labels) if a["box_eligible"]], 2)) | |
| pair_data = [] | |
| for i, j in sorted(set(label_pairs) | set(box_pairs)): | |
| a, b = labels[i]["violations"], labels[j]["violations"] | |
| record = {"a": i, "b": j} | |
| if (i, j) in label_pairs: | |
| la, lb = [{"use_case_id": c} for c in sorted(sets[i])], [{"use_case_id": c} for c in sorted(sets[j])] | |
| matched = match_items(la, lb, policy) | |
| record["label_matches"] = [{"a_class": la[x]["use_case_id"], "b_class": lb[y]["use_case_id"], | |
| "semantic": s, "cosine": policy.similarity(la[x]["use_case_id"], lb[y]["use_case_id"])} for x, y, _, s in matched] | |
| if (i, j) in box_pairs: | |
| record["threshold_matches"] = { | |
| str(t): match_items(a, b, threshold=t) for t in THRESHOLDS} | |
| record["box_matches"] = [dict(a=x, b=y, iou=overlap, semantic=s, | |
| a_class=a[x]["use_case_id"], b_class=b[y]["use_case_id"], | |
| cosine=policy.similarity(a[x]["use_case_id"], b[y]["use_case_id"])) | |
| for x, y, overlap, s in match_items(a, b, policy, .5)] | |
| pair_data.append(record) | |
| gold_ids = {v["use_case_id"] for v in gold.get("violations", [])} if gold else set() | |
| return {"image_id": row["image_id"], "category": category, "gold": gold, | |
| "gold_ids": gold_ids, "labels": labels, "sets": sets, "pairs": pair_data, | |
| "audit": dict(audit), "quality": {k: rating_statistics(row["first_pass"], k) for k in ("plausibility", "naturalness")}} | |
| def image_statistics(image, ids, *, per_class=False): | |
| out = np.zeros(len(FIELDS)) | |
| def add(key, value): out[F[key]] += value | |
| sets = {i: s & ids for i, s in image["sets"].items()} | |
| lp = [p for p in image["pairs"] if "label_matches" in p] | |
| bp = [p for p in image["pairs"] if "box_matches" in p] | |
| if lp: | |
| add("label_n", 1); add("exact", len({tuple(sorted(s)) for s in sets.values()}) == 1) | |
| add("positive_images", any(sets.values())) | |
| positive = sum(bool(s) for s in sets.values()) | |
| if per_class: | |
| n = len(sets) | |
| add("alpha_n", n); add("alpha_sum", positive) | |
| add("alpha_o", 2 * positive * (n-positive) / (n-1)) | |
| for p in lp: | |
| a, b = sets[p["a"]], sets[p["b"]] | |
| union, shared = a | b, a & b | |
| w = 1 / len(lp) | |
| endpoints = sum(m["a_class"] in ids for m in p["label_matches"]) + sum(m["b_class"] in ids for m in p["label_matches"]) | |
| add("label_pairs", 1); add("clean_pairs", not union) | |
| add("both_positive", w*len(shared)); add("unilateral", w*len(a ^ b)) | |
| add("both_absent", w*(len(ids)-len(union))) | |
| add("label_endpoints", w*(len(a)+len(b))) | |
| add("semantic_label_endpoints", w*endpoints) | |
| if bp: | |
| add("box_n", 1) | |
| positive = False | |
| for p in bp: | |
| a = image["labels"][p["a"]]["violations"] | |
| b = image["labels"][p["b"]]["violations"] | |
| endpoints = sum(v["use_case_id"] in ids for v in a+b) | |
| positive |= endpoints > 0 | |
| w = 1 / len(bp) | |
| add("box_pairs", 1); add("empty_box_pairs", endpoints == 0) | |
| add("box_endpoints", w*endpoints); add("raw_box_endpoints", endpoints) | |
| for index, t in enumerate(THRESHOLDS, 1): | |
| matches = [m for m in p["threshold_matches"][str(t)] if a[m[0]]["use_case_id"] in ids] | |
| add(f"match_{index}", w*len(matches)) | |
| if t == .5: | |
| add("raw_matches", len(matches)); add("iou_sum", w*sum(m[2] for m in matches)) | |
| for m in matches: | |
| add(f"iou_bin_{min(9, int(m[2]*10))}", w) | |
| add("semantic_box_endpoints", w*sum((m["a_class"] in ids)+(m["b_class"] in ids) for m in p["box_matches"])) | |
| add("box_positive", positive) | |
| return out | |
| def agreement_summary(rows, *, per_class=False, seed=SEED, replicates=2000): | |
| rows = np.asarray(rows, dtype=float).reshape(-1, len(FIELDS)) | |
| names = ["exact", "positive_agreement", "alpha", "semantic_positive_agreement", | |
| "instance_f1", "semantic_instance_f1", "matched_iou"] + [f"iou_{i}" for i in range(1, 10)] | |
| def evaluate(t): | |
| c = lambda key: t[:, F[key]] | |
| alpha = alpha_from_totals(c("alpha_n"), c("alpha_sum"), c("alpha_sum"), c("alpha_o")) | |
| alpha[c("label_n") < 2] = np.nan | |
| if not per_class: alpha[:] = np.nan | |
| return np.column_stack([ | |
| ratio(c("exact"), c("label_n")), | |
| ratio(2*c("both_positive"), 2*c("both_positive")+c("unilateral")), alpha, | |
| ratio(c("semantic_label_endpoints"), c("label_endpoints")), | |
| ratio(2*c("match_5"), c("box_endpoints")), | |
| ratio(c("semantic_box_endpoints"), c("box_endpoints")), ratio(c("iou_sum"), c("match_5")), | |
| *[ratio(2*c(f"match_{i}"), c("box_endpoints")) for i in range(1, 10)]]) | |
| result = bootstrap_estimates(rows, evaluate, names, seed=seed, replicates=replicates) | |
| if not per_class: | |
| result["alpha"]["reason"] = "Nominal alpha is defined per class, not for a pooled set/domain" | |
| totals = dict(zip(FIELDS, rows.sum(axis=0).tolist())) | |
| result["support"] = totals | |
| result["limited_support"] = totals["label_n"] < 10 or totals["positive_images"] < 10 | |
| result["instance_limited_support"] = totals["box_n"] < 10 or totals["box_positive"] < 10 | |
| return result | |
| def stable_seed(key): | |
| return (SEED + int(hashlib.sha256(key.encode()).hexdigest()[:8], 16)) % (2**32) | |
| def public_evidence(image): | |
| """Private image evidence with image-local aliases, never source identities.""" | |
| return {"image_id": image["image_id"], "category": image["category"], | |
| "gold": image["gold"], "gold_ids": sorted(image["gold_ids"]), | |
| "labels": image["labels"], "audit": image["audit"], | |
| "rating_ranges": {k: int(np.argmax(v[8:])) if v[0] else None for k, v in image["quality"].items()}, | |
| "pairs": [{k: v for k, v in p.items() if k != "threshold_matches"} | { | |
| "exact_box_matches": [dict(a=a, b=b, iou=iou) for a,b,iou,_ in p.get("threshold_matches", {}).get("0.5", [])] | |
| } for p in image["pairs"]]} | |