File size: 8,040 Bytes
eea47ad | 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 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | """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
# Order chosen so visually similar perturbations are adjacent on the legend
PERT_ORDER = [
"gaussian_noise",
"block_wise",
"jpeg_quality",
"color_saturation",
"color_contrast",
"gaussian_blur",
"pixelate",
]
# Color palette: noise/block/jpeg use warm colors (the dangerous ones),
# color/blur/pixelate use cool (the harmless ones)
COLORS = {
"gaussian_noise": "#C0392B", # red
"block_wise": "#E67E22", # orange
"jpeg_quality": "#F1C40F", # yellow
"color_saturation": "#16A085", # teal
"color_contrast": "#2980B9", # blue
"gaussian_blur": "#8E44AD", # purple
"pixelate": "#7F8C8D", # grey
}
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")
# one shared legend at the top
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()
|