""" Aggregate all per-model JSON results and print a comparison table. Usage: python compare_results.py \ --results-dir /mnt/bn/bohanzhainas1/jiashuo/exp/active_cases_eval Output: a markdown table + CSV written to results_dir/comparison_table.csv """ import argparse import csv import json from pathlib import Path def load_result(path: Path) -> dict | None: try: d = json.loads(path.read_text()) return d except Exception as e: print(f" Warning: could not load {path.name}: {e}") return None def format_pct(v: float | None) -> str: if v is None: return "N/A" return f"{v*100:.1f}%" def main(): parser = argparse.ArgumentParser() parser.add_argument("--results-dir", default="/mnt/bn/bohanzhainas1/jiashuo/exp/active_cases_eval") parser.add_argument("--output-csv", default=None, help="Path for output CSV (default: results_dir/comparison_table.csv)") args = parser.parse_args() results_dir = Path(args.results_dir) out_csv = args.output_csv or str(results_dir / "comparison_table.csv") # Also save outputs to the inference root dir inference_dir = Path("/mlx/users/jiashuo.fan/playground/inference") inference_dir.mkdir(parents=True, exist_ok=True) result_files = sorted(results_dir.glob("*.json")) if not result_files: print(f"No result files found in {results_dir}") return rows = [] for f in result_files: if f.name == "comparison_table.json": continue d = load_result(f) if d is None: continue model_name = d.get("model_name", f.stem) accuracy = d.get("accuracy", 0.0) correct = d.get("correct", 0) evaluated = d.get("evaluated", 0) parse_fail = d.get("parse_failures", 0) per_class = d.get("per_class", {}) p1 = per_class.get("1", {}) p0 = per_class.get("0", {}) # For the 238 hard cases: # - gt is ALWAYS 1 (all are true positives that model missed) # - recall@1 = fraction that the VLM correctly identifies as label=1 recall_1 = p1.get("recall", None) precision_1= p1.get("precision", None) f1_1 = p1.get("f1", None) recall_0 = p0.get("recall", None) rows.append({ "model": model_name, "accuracy": accuracy, "correct": correct, "evaluated": evaluated, "parse_fail": parse_fail, "recall_1": recall_1, "precision_1": precision_1, "f1_1": f1_1, "recall_0": recall_0, }) if not rows: print("No results to display.") return # Sort by accuracy descending rows.sort(key=lambda r: r["accuracy"], reverse=True) # Print markdown table header = ( f"{'Model':<30} | {'Acc':>6} | {'Correct':>8} | " f"{'Rec@1':>7} | {'Prec@1':>7} | {'F1@1':>6} | " f"{'Evaluated':>9} | {'ParseFail':>9}" ) sep = "-" * len(header) print("\n" + sep) print(header) print(sep) for r in rows: print( f"{r['model']:<30} | {format_pct(r['accuracy']):>6} | " f"{r['correct']:>5}/{r['evaluated']:<3} | " f"{format_pct(r['recall_1']):>7} | " f"{format_pct(r['precision_1']):>7} | " f"{format_pct(r['f1_1']):>6} | " f"{r['evaluated']:>9} | " f"{r['parse_fail']:>9}" ) print(sep) print(f"\nNote: All 238 cases have gt_label=1 (hard false-negatives of the existing model).") print(f" Acc / Recall@1 = fraction correctly identified as causally related.") # Save markdown table md_lines = [ "# VLM Comparison on 238 Hard Cases (False Negatives)\n", "> All 238 cases have gt_label=1. Acc / Recall@1 = fraction correctly identified as causally related.\n", "", f"| {'Model':<30} | {'Acc':>6} | {'Correct':>8} | {'Rec@1':>7} | {'Prec@1':>7} | {'F1@1':>6} | {'Evaluated':>9} | {'ParseFail':>9} |", f"|{'-'*32}|{'-'*8}|{'-'*10}|{'-'*9}|{'-'*9}|{'-'*8}|{'-'*11}|{'-'*11}|", ] for r in rows: md_lines.append( f"| {r['model']:<30} | {format_pct(r['accuracy']):>6} | " f"{r['correct']:>5}/{r['evaluated']:<3} | " f"{format_pct(r['recall_1']):>7} | " f"{format_pct(r['precision_1']):>7} | " f"{format_pct(r['f1_1']):>6} | " f"{r['evaluated']:>9} | " f"{r['parse_fail']:>9} |" ) md_text = "\n".join(md_lines) print(md_text) # Save to both results_dir and inference root for out_dir in [results_dir, inference_dir]: md_path = out_dir / "model_comparison.md" md_path.write_text(md_text) print(f"Markdown saved to: {md_path}") # Save CSV fieldnames = ["model", "accuracy", "correct", "evaluated", "parse_fail", "recall_1", "precision_1", "f1_1", "recall_0"] for out_dir in [results_dir, inference_dir]: csv_path = out_dir / "model_comparison.csv" with open(csv_path, "w", newline="") as f: writer = csv.DictWriter(f, fieldnames=fieldnames) writer.writeheader() writer.writerows(rows) print(f"CSV saved to: {csv_path}") # Save comparison JSON for further analysis comp_json = results_dir / "comparison_table.json" comp_json.write_text(json.dumps(rows, indent=2)) print(f"JSON saved to: {comp_json}") if __name__ == "__main__": main()