Datasets:
File size: 4,752 Bytes
ff1fb3b | 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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | #!/usr/bin/env python3
"""Compute the PhysCount metrics defined in the paper."""
from __future__ import annotations
import argparse
import json
from collections import defaultdict
from pathlib import Path
QUESTION_TYPES = ("appearance", "entity", "image_formation", "correspondence")
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--data-root", type=Path, default=Path(__file__).parents[1])
parser.add_argument("--predictions", type=Path, required=True)
parser.add_argument("--output", type=Path)
return parser.parse_args()
def read_jsonl(path: Path) -> list[dict]:
with path.open("r", encoding="utf-8") as handle:
return [json.loads(line) for line in handle if line.strip()]
def mean(values: list[float]) -> float:
return sum(values) / len(values)
def reported_mean(
values: list[float], scale: float = 1.0, digits: int = 2
) -> float | None:
# An empty support set has no defined mean; serialize it as JSON null.
return round(scale * mean(values), digits) if values else None
def main() -> None:
args = parse_args()
questions = read_jsonl(args.data_root / "data" / "questions.jsonl")
prediction_rows = read_jsonl(args.predictions)
predictions = {row["question_id"]: row for row in prediction_rows}
if len(predictions) != len(prediction_rows):
raise SystemExit("Predictions contain duplicate question_id values")
per_group: dict[str, dict[str, list[dict]]] = defaultdict(
lambda: defaultdict(list)
)
for question in questions:
prediction_row = predictions.get(question["question_id"], {})
prediction = prediction_row.get("prediction")
valid = (
bool(prediction_row.get("valid"))
and isinstance(prediction, int)
and not isinstance(prediction, bool)
)
valid = valid and 0 <= prediction < 10_000
gold = question["answer"]
absolute_error = abs(prediction - gold) if valid else None
normalized_error = (
min(1.0, absolute_error / max(gold, 1)) if valid else 1.0
)
per_group[question["group_id"]][question["question_type"]].append(
{
"valid": valid,
"exact": valid and prediction == gold,
"ae": absolute_error,
"nae": normalized_error,
}
)
type_naes: dict[str, list[float]] = defaultdict(list)
type_maes: dict[str, list[float]] = defaultdict(list)
group_scores: list[float] = []
group_exact: list[bool] = []
phys_grounding: list[float] = []
for type_rows in per_group.values():
accuracies: dict[str, float] = {}
all_exact = True
for question_type, rows in type_rows.items():
group_nae = mean([row["nae"] for row in rows])
type_naes[question_type].append(group_nae)
accuracies[question_type] = 1.0 - group_nae
valid_aes = [row["ae"] for row in rows if row["ae"] is not None]
if valid_aes:
type_maes[question_type].append(mean(valid_aes))
all_exact = all_exact and all(row["exact"] for row in rows)
product = 1.0
for value in accuracies.values():
product *= value
group_scores.append(product)
group_exact.append(all_exact)
if set(QUESTION_TYPES).issubset(type_rows):
appearance_exact = all(
row["exact"] for row in type_rows["appearance"]
)
if appearance_exact:
values = [
accuracies["entity"],
accuracies["image_formation"],
accuracies["correspondence"],
]
harmonic = 0.0 if min(values) == 0 else 3.0 / sum(1 / v for v in values)
phys_grounding.append(harmonic)
metrics: dict[str, float | None] = {}
short_names = {
"appearance": "A",
"entity": "E",
"image_formation": "I",
"correspondence": "C",
}
for question_type in QUESTION_TYPES:
short = short_names[question_type]
metrics[f"{short}-MAE"] = reported_mean(type_maes[question_type], digits=3)
metrics[f"{short}-NAE"] = reported_mean(type_naes[question_type], scale=100)
metrics["Score"] = reported_mean(group_scores, scale=100)
metrics["Group-Acc"] = reported_mean([float(x) for x in group_exact], scale=100)
metrics["Phys-Gnd"] = reported_mean(phys_grounding, scale=100)
output = json.dumps(metrics, indent=2) + "\n"
print(output, end="")
if args.output:
args.output.write_text(output, encoding="utf-8")
if __name__ == "__main__":
main()
|