Datasets:
Download evaluate.py from LevinShan/300Question-Bench: direct link, hf CLI and curl.
- Browser
- Download file 2.3 kB
-
https://huggingface.co/datasets/LevinShan/300Question-Bench/resolve/refs%2Fpr%2F2/evaluate.py
- Command line
-
hf download hf://datasets/LevinShan/300Question-Bench@refs/pr/2/evaluate.py
-
curl -L -o evaluate.py https://huggingface.co/datasets/LevinShan/300Question-Bench/resolve/refs%2Fpr%2F2/evaluate.py
2.3 kB
| """Score predictions on 300Question-Bench. | |
| python evaluate.py predictions.json [--threshold 0.5] | |
| predictions.json maps every case_id to a hazard probability in [0, 1] or a boolean (true = hazardous). | |
| Prints hazard recall, normal false-positive rate and balanced accuracy, overall and per environment and task. | |
| """ | |
| import argparse | |
| import json | |
| from collections import defaultdict | |
| from pathlib import Path | |
| def metrics(rows): | |
| hazard = [p for p, y in rows if y] | |
| normal = [p for p, y in rows if not y] | |
| recall = sum(hazard) / len(hazard) if hazard else float("nan") | |
| fpr = sum(normal) / len(normal) if normal else float("nan") | |
| return dict(n=len(rows), hazardous=len(hazard), recall=recall, false_positive_rate=fpr, | |
| balanced_accuracy=(recall + 1 - fpr) / 2, accuracy=sum(p == y for p, y in rows) / len(rows)) | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| parser.add_argument("predictions", type=Path) | |
| parser.add_argument("--threshold", type=float, default=0.5, help="probabilities >= threshold count as hazardous") | |
| parser.add_argument("--labels", type=Path, default=Path(__file__).with_name("labels.json")) | |
| args = parser.parse_args() | |
| labels = json.loads(args.labels.read_text())["cases"] | |
| predictions = json.loads(args.predictions.read_text()) | |
| missing = sorted(set(labels) - set(predictions)) | |
| if missing: | |
| raise SystemExit(f"{len(missing)} cases have no prediction, e.g. {missing[:3]}") | |
| groups = defaultdict(list) | |
| for case_id, label in labels.items(): | |
| value = predictions[case_id] | |
| flagged = bool(value) if isinstance(value, bool) else float(value) >= args.threshold | |
| row = (flagged, label["hazardous"]) | |
| for key in ("all", f"env/{label['environment']}", f"task/{label['task']}"): | |
| groups[key].append(row) | |
| print(f"{'subset':45s} {'n':>4s} {'haz':>4s} {'recall':>7s} {'FPR':>7s} {'bal.acc':>8s}") | |
| for key in ["all"] + sorted(k for k in groups if k != "all"): | |
| m = metrics(groups[key]) | |
| print(f"{key:45s} {m['n']:4d} {m['hazardous']:4d} {m['recall']:7.3f} {m['false_positive_rate']:7.3f} " | |
| f"{m['balanced_accuracy']:8.3f}") | |
| if __name__ == "__main__": | |
| main() | |