| """Plot robustness curves from a sweep JSON. |
| |
| Reads JSON produced by run_robustness_sweep.sh (or single evaluate_robustness.py |
| runs appended to the same file), draws AUROC / AP / Acc / Acc@EER as a function |
| of perturbation level, one line per perturbation kind. |
| |
| Output: |
| outputs/analysis/robustness/figs_<TS>/ |
| ├── robustness_auroc.{png,pdf} |
| ├── robustness_ap.{png,pdf} |
| ├── robustness_acc.{png,pdf} |
| ├── robustness_acceer.{png,pdf} |
| ├── robustness_grid.png (4-in-1 paper figure) |
| └── robustness_table.csv |
| |
| Usage: |
| python3 scripts/analysis/plot_robustness.py \\ |
| --json outputs/analysis/robustness/cta_runs_20260615_205515.json |
| """ |
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import os |
| from collections import defaultdict |
| from pathlib import Path |
|
|
| import matplotlib |
| matplotlib.use("Agg") |
| import matplotlib.pyplot as plt |
|
|
|
|
| |
| PERT_ORDER = [ |
| "gaussian_noise", |
| "block_wise", |
| "jpeg_quality", |
| "color_saturation", |
| "color_contrast", |
| "gaussian_blur", |
| "pixelate", |
| ] |
|
|
| |
| |
| COLORS = { |
| "gaussian_noise": "#C0392B", |
| "block_wise": "#E67E22", |
| "jpeg_quality": "#F1C40F", |
| "color_saturation": "#16A085", |
| "color_contrast": "#2980B9", |
| "gaussian_blur": "#8E44AD", |
| "pixelate": "#7F8C8D", |
| } |
|
|
| PRETTY = { |
| "gaussian_noise": "Gaussian noise", |
| "block_wise": "Block occlusion", |
| "jpeg_quality": "JPEG compression", |
| "color_saturation": "Color saturation", |
| "color_contrast": "Color contrast", |
| "gaussian_blur": "Gaussian blur", |
| "pixelate": "Pixelation", |
| } |
|
|
|
|
| def collect(json_path: str): |
| """Returns dict[perturbation] -> {level: {AUROC, AP, Accuracy, Acc@EER}}.""" |
| with open(json_path) as f: |
| blob = json.load(f) |
| runs = blob.get("runs", []) |
| out = defaultdict(dict) |
| for r in runs: |
| p = r.get("perturbation") |
| L = r.get("level") |
| if not p or not L: |
| continue |
| o = r.get("overall", {}) |
| out[p][L] = { |
| "AUROC": o.get("AUROC"), |
| "AP": o.get("AP"), |
| "Accuracy": o.get("Accuracy"), |
| "Acc@EER": o.get("Acc@EER"), |
| "param": r.get("param"), |
| } |
| return out |
|
|
|
|
| def _plot_one(ax, data, metric_key, title, ylabel, ylim=None): |
| for p in PERT_ORDER: |
| if p not in data: |
| continue |
| levels = sorted(data[p].keys()) |
| ys = [data[p][L].get(metric_key) for L in levels] |
| if all(y is None for y in ys): |
| continue |
| ax.plot(levels, ys, marker="o", linewidth=2.0, markersize=6, |
| color=COLORS[p], label=PRETTY[p]) |
| ax.set_xticks([1, 2, 3, 4, 5]) |
| ax.set_xlabel("Perturbation level (1 = clean, 5 = strongest)") |
| ax.set_ylabel(ylabel) |
| ax.set_title(title) |
| if ylim is not None: |
| ax.set_ylim(ylim) |
| ax.grid(True, alpha=0.3, linestyle=":") |
| ax.spines["top"].set_visible(False) |
| ax.spines["right"].set_visible(False) |
|
|
|
|
| def save_table(data, out_csv): |
| """Wide CSV: rows = perturbation × level, cols = AUROC, AP, Acc, Acc@EER, param.""" |
| with open(out_csv, "w") as f: |
| f.write("perturbation,level,param,AUROC,AP,Accuracy,Acc@EER,delta_AUROC_vs_L1\n") |
| for p in PERT_ORDER: |
| if p not in data: |
| continue |
| base = data[p].get(1, {}).get("AUROC") |
| for L in sorted(data[p].keys()): |
| row = data[p][L] |
| d = (row.get("AUROC") - base) if (base is not None and row.get("AUROC") is not None) else float("nan") |
| f.write( |
| f"{p},{L},{row.get('param')}," |
| f"{row.get('AUROC'):.4f},{row.get('AP'):.4f}," |
| f"{row.get('Accuracy'):.4f},{row.get('Acc@EER'):.4f}," |
| f"{d:+.4f}\n" |
| ) |
| print(f"[plot] wrote {out_csv}") |
|
|
|
|
| def plot_grid(data, out_path): |
| """4-in-1 figure for paper.""" |
| fig, axes = plt.subplots(2, 2, figsize=(12, 8)) |
| _plot_one(axes[0, 0], data, "AUROC", "AUROC vs perturbation level", "AUROC") |
| _plot_one(axes[0, 1], data, "AP", "AP vs perturbation level", "Average Precision") |
| _plot_one(axes[1, 0], data, "Accuracy","Accuracy vs perturbation level","Accuracy @ 0.5") |
| _plot_one(axes[1, 1], data, "Acc@EER", "Acc@EER vs perturbation level", "Acc @ EER threshold") |
|
|
| |
| handles, labels = axes[0, 0].get_legend_handles_labels() |
| fig.legend(handles, labels, loc="upper center", ncol=6, |
| bbox_to_anchor=(0.5, 1.005), frameon=False, fontsize=9) |
| fig.tight_layout(rect=(0, 0, 1, 0.97)) |
| fig.savefig(out_path, dpi=200, bbox_inches="tight") |
| fig.savefig(out_path.replace(".png", ".pdf"), bbox_inches="tight") |
| plt.close(fig) |
| print(f"[plot] wrote {out_path}") |
|
|
|
|
| def plot_single(data, metric_key, title, ylabel, out_path, ylim=None): |
| fig, ax = plt.subplots(figsize=(7.5, 5)) |
| _plot_one(ax, data, metric_key, title, ylabel, ylim=ylim) |
| ax.legend(frameon=False, loc="best", fontsize=9) |
| fig.tight_layout() |
| fig.savefig(out_path, dpi=200, bbox_inches="tight") |
| fig.savefig(out_path.replace(".png", ".pdf"), bbox_inches="tight") |
| plt.close(fig) |
| print(f"[plot] wrote {out_path}") |
|
|
|
|
| def main(): |
| p = argparse.ArgumentParser() |
| p.add_argument("--json", required=True, help="Path to robustness JSON.") |
| p.add_argument("--out_dir", default=None, |
| help="Output dir. Default: alongside the JSON, named figs_<JSON_stem>") |
| p.add_argument("--exclude", nargs="*", default=[], |
| help="Perturbation names to skip in the plots " |
| "(e.g. --exclude gaussian_noise). Useful for cleaner figures " |
| "when one perturbation is an outlier.") |
| p.add_argument("--include", nargs="*", default=None, |
| help="If given, only these perturbations are plotted. " |
| "Mutually exclusive with --exclude.") |
| args = p.parse_args() |
|
|
| json_path = Path(args.json).resolve() |
| suffix_bits = [] |
| if args.exclude: |
| suffix_bits.append("noex_" + "_".join(args.exclude)) |
| if args.include: |
| suffix_bits.append("only_" + "_".join(args.include)) |
| suffix = ("_" + "_".join(suffix_bits)) if suffix_bits else "" |
| if args.out_dir is None: |
| out_dir = json_path.parent / f"figs_{json_path.stem}{suffix}" |
| else: |
| out_dir = Path(args.out_dir).resolve() |
| out_dir.mkdir(parents=True, exist_ok=True) |
|
|
| print(f"[plot] reading {json_path}") |
| data = collect(str(json_path)) |
| if args.include: |
| data = {k: v for k, v in data.items() if k in set(args.include)} |
| print(f"[plot] include filter: keeping {sorted(data.keys())}") |
| if args.exclude: |
| excluded = set(args.exclude) |
| data = {k: v for k, v in data.items() if k not in excluded} |
| print(f"[plot] exclude filter: dropping {sorted(excluded)}") |
| print(f"[plot] perturbations to plot: {sorted(data.keys())}") |
| print(f"[plot] writing to {out_dir}") |
|
|
| plot_single(data, "AUROC", "Robustness — AUROC", "AUROC", |
| str(out_dir / "robustness_auroc.png")) |
| plot_single(data, "AP", "Robustness — AP", "Average Precision", |
| str(out_dir / "robustness_ap.png")) |
| plot_single(data, "Accuracy","Robustness — Accuracy","Accuracy @ 0.5", |
| str(out_dir / "robustness_acc.png")) |
| plot_single(data, "Acc@EER", "Robustness — Acc@EER", "Acc @ EER threshold", |
| str(out_dir / "robustness_acceer.png")) |
|
|
| plot_grid(data, str(out_dir / "robustness_grid.png")) |
| save_table(data, str(out_dir / "robustness_table.csv")) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|