File size: 5,887 Bytes
4ceeb65 | 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 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 | import argparse
import json
import re
from tqdm import tqdm
SUBTASK_CATEGORIES = {
"speed": ["KEEP", "ACCELERATE", "DECELERATE", "STOP"],
"path": ["LEFT", "RIGHT", "STRAIGHT", "UNKNOWN"],
}
REQUIRED_SUBTASKS = set(SUBTASK_CATEGORIES)
def clean_text(s: str):
"""Normalize whitespace and punctuation."""
if not isinstance(s, str):
return ""
s = s.strip()
s = re.sub(r"[.\n\r]+", " ", s)
s = re.sub(r"\s+", " ", s)
return s.strip()
def parse_prediction(text, subtask):
"""
Parse one split-task prediction:
"B ACCELERATE" -> "ACCELERATE"
"C STRAIGHT" -> "STRAIGHT"
"""
if subtask not in SUBTASK_CATEGORIES:
raise ValueError(f"Unexpected prediction subtask: {subtask!r}")
text = clean_text(text).upper()
categories = SUBTASK_CATEGORIES[subtask]
matches = [
word for word in categories
if re.search(rf"(?<![A-Z_]){re.escape(word)}(?![A-Z_])", text)
]
return matches[0] if len(matches) == 1 else None
def group_split_samples(data):
groups = {}
for item in data:
original_id = item.get("original_id")
subtask = item.get("subtask")
if not original_id:
raise ValueError("Prediction sample is missing original_id")
if subtask not in SUBTASK_CATEGORIES:
raise ValueError(f"Missing or invalid prediction subtask: {subtask!r}")
group = groups.setdefault(original_id, {})
if subtask in group:
raise ValueError(f"Duplicate prediction subtask {subtask!r} for {original_id}")
group[subtask] = item
for original_id, group in groups.items():
if set(group) != REQUIRED_SUBTASKS:
raise ValueError(f"Incomplete prediction subtask pair for {original_id}: {sorted(group)}")
return groups
def evaluate(pred_json):
with open(pred_json, "r", encoding="utf-8") as f:
data = json.load(f)
if not data:
raise ValueError(f"No samples found in {pred_json}")
groups = group_split_samples(data)
totals = {subtask: 0 for subtask in SUBTASK_CATEGORIES}
correct = {subtask: 0 for subtask in SUBTASK_CATEGORIES}
classwise = {
subtask: {category: {"total": 0, "correct": 0} for category in categories}
for subtask, categories in SUBTASK_CATEGORIES.items()
}
mismatch_examples = []
joint_correct = 0
for original_id, group in tqdm(groups.items(), desc="Evaluating prediction pairs"):
is_joint_correct = True
for subtask, item in group.items():
gt_raw = item["conversations"][1]["value"]
pred_raw = item.get("model_output", "")
gt = parse_prediction(gt_raw, subtask)
pred = parse_prediction(pred_raw, subtask)
if gt is None:
raise ValueError(f"Invalid {subtask} ground-truth answer: {gt_raw!r}")
totals[subtask] += 1
classwise[subtask][gt]["total"] += 1
is_correct = gt == pred
is_joint_correct = is_joint_correct and is_correct
if is_correct:
correct[subtask] += 1
classwise[subtask][gt]["correct"] += 1
else:
mismatch_examples.append({
"original_id": original_id,
"image": item["image"],
"bbox_2d": item.get("bbox_2d", {}),
"subtask": subtask,
"gt": gt,
"pred": pred,
"model_output": pred_raw,
})
joint_correct += is_joint_correct
total = sum(totals.values())
original_questions = len(groups)
overall_acc = sum(correct.values()) / total * 100
joint_acc = joint_correct / original_questions * 100
print(f"\nTotal samples: {total}")
print(f"Original questions: {original_questions}")
for subtask in SUBTASK_CATEGORIES:
accuracy = correct[subtask] / totals[subtask] * 100 if totals[subtask] else 0.0
print(f"{subtask.upper()} accuracy: {accuracy:.2f}% ({correct[subtask]}/{totals[subtask]})")
print(f"Overall accuracy: {overall_acc:.2f}%")
print(f"Joint accuracy: {joint_acc:.2f}% ({joint_correct}/{original_questions})")
print(f"Wrong examples: {len(mismatch_examples)}")
result_summary = {
"total": total,
"original_questions": original_questions,
"overall_accuracy (%)": round(overall_acc, 2),
"joint_correct": joint_correct,
"joint_accuracy (%)": round(joint_acc, 2),
"subtasks": {
subtask: {
"total": totals[subtask],
"accuracy (%)": round(correct[subtask] / totals[subtask] * 100, 2) if totals[subtask] else None,
"classwise": {
category: round(stats["correct"] / stats["total"] * 100, 2) if stats["total"] else None
for category, stats in classwise[subtask].items()
},
}
for subtask in SUBTASK_CATEGORIES
},
}
error_path = pred_json.replace(".json", "_errors.json")
with open(error_path, "w", encoding="utf-8") as f:
json.dump(mismatch_examples, f, indent=2, ensure_ascii=False)
result_path = pred_json.replace(".json", "_accuracy.json")
with open(result_path, "w", encoding="utf-8") as f:
json.dump(result_summary, f, indent=2, ensure_ascii=False)
print(f"\nError samples saved to {error_path}")
print(f"Accuracy summary saved to {result_path}")
return result_summary
def parse_args():
parser = argparse.ArgumentParser(description="Evaluate EventDrive prediction task results.")
parser.add_argument("--pred-json", required=True, help="Path to prediction JSON with model_output fields.")
return parser.parse_args()
if __name__ == "__main__":
args = parse_args()
evaluate(args.pred_json)
|