jzzheng20's picture
Upload release (part 2)
10c460e verified
Raw History Blame Contribute Delete
4.4 kB
#!/usr/bin/env python3
"""
Score predictions against the FriendBench validation answer key.
The answer key lives in data/metadata.csv (column `relationship`, values
`familiar` / `stranger`), keyed by `sample_id`.
Your predictions file is a CSV with at least two columns:
sample_id,prediction
where `prediction` is `familiar`, `stranger`, or blank (a declined / unanswered
trial). Accuracy is computed over ANSWERED trials; coverage reports the share of
the 96 samples you answered.
Usage:
python eval.py my_predictions.csv
python eval.py my_predictions.csv --metadata data/metadata.csv
No third-party dependencies (standard library only).
"""
import argparse
import csv
from collections import defaultdict
from pathlib import Path
LABELS = ("familiar", "stranger")
def norm(x: str) -> str:
x = (x or "").strip().lower()
return x if x in LABELS else ""
def load_key(metadata: Path) -> dict:
key = {}
with metadata.open() as f:
for row in csv.DictReader(f):
key[row["sample_id"]] = norm(row["relationship"])
return key
def load_predictions(path: Path) -> dict:
with path.open() as f:
reader = csv.DictReader(f)
if "sample_id" not in reader.fieldnames or "prediction" not in reader.fieldnames:
raise SystemExit(
f"{path} must have columns `sample_id` and `prediction` "
f"(found: {reader.fieldnames})"
)
return {r["sample_id"]: norm(r["prediction"]) for r in reader}
def accuracy(pairs):
"""pairs: list of (truth, pred). Returns (acc_over_answered, n_answered, n_total)."""
n_total = len(pairs)
answered = [(t, p) for t, p in pairs if p]
if not answered:
return 0.0, 0, n_total
correct = sum(1 for t, p in answered if t == p)
return 100 * correct / len(answered), len(answered), n_total
def breakdown(rows, field):
groups = defaultdict(list)
for r in rows:
groups[r[field]].append((r["truth"], r["pred"]))
out = []
for name in sorted(groups):
acc, n_ans, n_tot = accuracy(groups[name])
out.append((name, acc, n_ans, n_tot))
return out
def main():
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("predictions", type=Path, help="CSV with sample_id,prediction")
ap.add_argument("--metadata", type=Path, default=Path(__file__).parent / "data/metadata.csv",
help="answer-key manifest (default: data/metadata.csv)")
args = ap.parse_args()
key = load_key(args.metadata)
preds = load_predictions(args.predictions)
missing = [s for s in key if s not in preds]
extra = [s for s in preds if s not in key]
if extra:
print(f"! {len(extra)} prediction rows are not in the answer key (ignored): "
f"{extra[:5]}{'...' if len(extra) > 5 else ''}")
# join on the manifest so we can break results out by design factor
rows = []
with args.metadata.open() as f:
for m in csv.DictReader(f):
sid = m["sample_id"]
rows.append({
"sample_id": sid,
"truth": key[sid],
"pred": preds.get(sid, ""),
"relationship": m["relationship"],
"gender_config": m.get("gender_config", ""),
"temporal_position": m.get("temporal_position", ""),
"cell": m.get("cell", ""),
})
overall_acc, n_ans, n_tot = accuracy([(r["truth"], r["pred"]) for r in rows])
print(f"\nFriendBench validation — evaluation")
print("=" * 46)
print(f"Overall accuracy : {overall_acc:5.1f}% (over {n_ans} answered)")
print(f"Coverage : {100*n_ans/n_tot:5.1f}% ({n_ans}/{n_tot} answered)")
if missing:
print(f"Unanswered : {len(missing)} sample(s) had no prediction")
for field, title in [("relationship", "By relationship (per-class recall)"),
("gender_config", "By gender_config"),
("temporal_position", "By temporal_position"),
("cell", "By design cell")]:
print(f"\n{title}")
for name, acc, na, nt in breakdown(rows, field):
print(f" {name:28} {acc:5.1f}% ({na}/{nt})")
print()
if __name__ == "__main__":
main()