File size: 12,406 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 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 | """Compare robustness curves across three models:
CTA (this project), X-AVDT, AVH-Align.
For each perturbation type, draw one figure with three lines (one per model)
showing AUROC (and AP / Accuracy / Acc@EER) as a function of severity level.
The three input CSVs use different schemas; this script normalizes them to
a common long-table: (model, perturbation, level, AUROC, AP, Accuracy, Acc@EER).
Output:
<out_dir>/
auroc_<perturbation>.{png,pdf} one per perturbation, single metric
ap_<perturbation>.{png,pdf}
acc_<perturbation>.{png,pdf}
acc_at_eer_<perturbation>.{png,pdf}
grid_auroc.{png,pdf} 7 perturbations on one A4-ish grid
merged_long_table.csv normalized long-table for downstream
Usage:
python3 scripts/analysis/plot_robustness_compare.py \\
--cta /apdcephfs_gy4/.../figs_with_jpeg/robustness_table.csv \\
--xavdt /apdcephfs_gy4/.../X-AVDT/results/robustness/robustness_summary.csv \\
--avhalign /apdcephfs_gy5/.../AVH-Align/results/robustness_v2/merged_long_table.csv \\
--out_dir /apdcephfs_gy4/.../X-AVDT/results/robustness/compare
"""
from __future__ import annotations
import argparse
import csv
import os
from collections import defaultdict
from pathlib import Path
from typing import Dict, List, Optional
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
# ---- canonical perturbation names + display order -----------------------
PERTS_CANONICAL = [
"gaussian_noise",
"block_wise",
"jpeg_quality", # canonical name; CTA uses 'jpeg_quality',
# AVH-Align uses 'jpeg_compression' -> we map.
"pixelate",
"gaussian_blur",
"color_saturation",
"color_contrast",
]
# alternate spelling(s) per canonical key, used when normalizing input
PERT_ALIASES: Dict[str, str] = {
"jpeg_compression": "jpeg_quality",
}
PRETTY = {
"gaussian_noise": "Gaussian noise",
"block_wise": "Block occlusion",
"jpeg_quality": "JPEG compression",
"pixelate": "Pixelation",
"gaussian_blur": "Gaussian blur",
"color_saturation": "Color saturation",
"color_contrast": "Color contrast",
}
MODEL_COLORS = {
"CTA": "#C0392B", # red
"X-AVDT": "#2980B9", # blue
"AVH-Align": "#16A085", # teal
}
MODEL_MARKERS = {
"CTA": "o",
"X-AVDT": "s",
"AVH-Align": "^",
}
def _canon(p: str) -> str:
return PERT_ALIASES.get(p, p)
def _to_float(s: str) -> Optional[float]:
try:
v = float(s)
if v != v: # NaN
return None
return v
except (ValueError, TypeError):
return None
# ============================================================================
# Per-source loaders -> list[dict(model, perturbation, level, metrics)]
# ============================================================================
def load_cta(path: str) -> List[dict]:
"""CTA schema (long, narrow):
perturbation,level,param,AUROC,AP,Accuracy,Acc@EER,delta_AUROC_vs_L1
Already long-format: one row per (perturbation, level).
"""
rows = []
with open(path) as f:
reader = csv.DictReader(f)
for r in reader:
p = _canon(r["perturbation"].strip())
L = int(r["level"])
rows.append({
"model": "CTA",
"perturbation": p,
"level": L,
"param": r.get("param", ""),
"AUROC": _to_float(r.get("AUROC")),
"AP": _to_float(r.get("AP")),
"Accuracy": _to_float(r.get("Accuracy")),
"Acc@EER": _to_float(r.get("Acc@EER")),
})
print(f"[load] CTA: {len(rows)} rows from {path}")
return rows
def load_xavdt(path: str) -> List[dict]:
"""X-AVDT schema:
perturbation,level,param,n_clips,
overall_AUROC, overall_AP, overall_Accuracy@0.50, overall_Acc@EER,
overall_TPR@FPR=1%, overall_TPR@FPR=0.1%, ... (per-fake too)
Special row: perturbation='baseline', level=1 (the no-op).
Each non-baseline perturbation only has level 2..5; we fan the baseline
out as L1 of every perturbation so curves start at the same anchor.
"""
rows = []
baseline = None
perts_seen = set()
with open(path) as f:
reader = csv.DictReader(f)
for r in reader:
p_raw = r["perturbation"].strip()
L = int(r["level"])
block = {
"AUROC": _to_float(r.get("overall_AUROC")),
"AP": _to_float(r.get("overall_AP")),
"Accuracy": _to_float(r.get("overall_Accuracy@0.50")),
"Acc@EER": _to_float(r.get("overall_Acc@EER")),
}
if p_raw == "baseline":
baseline = block
continue
p = _canon(p_raw)
perts_seen.add(p)
rows.append({
"model": "X-AVDT",
"perturbation": p,
"level": L,
"param": r.get("param", ""),
**block,
})
# fan out baseline as L1 of every perturbation seen (so the curves anchor at L1)
if baseline is not None:
for p in perts_seen:
rows.append({
"model": "X-AVDT",
"perturbation": p,
"level": 1,
"param": "baseline",
**baseline,
})
print(f"[load] X-AVDT: {len(rows)} rows (incl. {len(perts_seen)} fanned baseline rows)")
return rows
def load_avhalign(path: str, subset: str = "non_diffusion") -> List[dict]:
"""AVH-Align schema:
perturbation,level,param,subset,samples,accuracy,auc,average_precision,acc_at_eer
`subset` is one of {overall, non_diffusion, SadTalk, EDTalk, Float};
we keep only the requested subset.
"""
rows = []
n_skipped = 0
with open(path) as f:
reader = csv.DictReader(f)
for r in reader:
if r["subset"].strip() != subset:
continue
p = _canon(r["perturbation"].strip())
L = int(r["level"])
rows.append({
"model": "AVH-Align",
"perturbation": p,
"level": L,
"param": r.get("param", ""),
"AUROC": _to_float(r.get("auc")),
"AP": _to_float(r.get("average_precision")),
"Accuracy": _to_float(r.get("accuracy")),
"Acc@EER": _to_float(r.get("acc_at_eer")),
})
print(f"[load] AVH-Align: {len(rows)} rows (subset={subset})")
return rows
# ============================================================================
# Plot helpers
# ============================================================================
def _gather(rows: List[dict]):
"""Group by perturbation -> model -> {level: row}."""
out = defaultdict(lambda: defaultdict(dict))
for r in rows:
out[r["perturbation"]][r["model"]][r["level"]] = r
return out
def _plot_metric_one_pert(ax, by_model, metric, title, ylabel,
ylim=None, show_legend=True):
"""`by_model`: {model: {level: row}}."""
for model in ("CTA", "X-AVDT", "AVH-Align"):
if model not in by_model:
continue
levels = sorted(by_model[model].keys())
ys = [by_model[model][L].get(metric) for L in levels]
if all(y is None for y in ys):
continue
ax.plot(
levels, ys,
marker=MODEL_MARKERS[model], linewidth=2.0, markersize=7,
color=MODEL_COLORS[model], label=model,
)
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)
if show_legend:
ax.legend(frameon=False, loc="best", fontsize=10)
def plot_per_perturbation(rows: List[dict], out_dir: Path):
by_pert = _gather(rows)
for metric_key, prefix, ylabel in [
("AUROC", "auroc", "AUROC"),
("AP", "ap", "Average Precision"),
("Accuracy","acc", "Accuracy @ 0.5"),
("Acc@EER", "acc_at_eer", "Acc @ EER threshold"),
]:
for p in PERTS_CANONICAL:
if p not in by_pert:
continue
fig, ax = plt.subplots(figsize=(6.5, 4.5))
_plot_metric_one_pert(
ax, by_pert[p], metric_key,
f"{PRETTY[p]} — {ylabel}",
ylabel,
)
fig.tight_layout()
png = out_dir / f"{prefix}_{p}.png"
pdf = out_dir / f"{prefix}_{p}.pdf"
fig.savefig(png, dpi=200, bbox_inches="tight")
fig.savefig(pdf, bbox_inches="tight")
plt.close(fig)
print(f"[plot] wrote {png}")
def plot_grid_auroc(rows: List[dict], out_path: Path):
"""One A4-ish grid: 7 perturbations, AUROC only, 3 lines each."""
by_pert = _gather(rows)
perts = [p for p in PERTS_CANONICAL if p in by_pert]
n = len(perts)
cols = 4
rows_n = (n + cols - 1) // cols
fig, axes = plt.subplots(rows_n, cols, figsize=(cols * 4.0, rows_n * 3.6))
axes = axes.flatten() if hasattr(axes, "flatten") else [axes]
for ax, p in zip(axes, perts):
_plot_metric_one_pert(
ax, by_pert[p], "AUROC",
PRETTY[p], "AUROC",
show_legend=False,
)
# disable extras
for ax in axes[len(perts):]:
ax.axis("off")
# one shared legend at top
handles, labels = axes[0].get_legend_handles_labels()
fig.legend(handles, labels, loc="upper center", ncol=3,
bbox_to_anchor=(0.5, 1.005), frameon=False, fontsize=11)
fig.tight_layout(rect=(0, 0, 1, 0.97))
fig.savefig(out_path, dpi=200, bbox_inches="tight")
fig.savefig(str(out_path).replace(".png", ".pdf"), bbox_inches="tight")
plt.close(fig)
print(f"[plot] wrote {out_path}")
def save_long_table(rows: List[dict], out_csv: Path):
fields = ["model", "perturbation", "level", "param",
"AUROC", "AP", "Accuracy", "Acc@EER"]
with open(out_csv, "w", newline="") as f:
w = csv.DictWriter(f, fieldnames=fields)
w.writeheader()
for r in sorted(rows, key=lambda x: (x["model"], x["perturbation"], x["level"])):
w.writerow({k: r.get(k, "") for k in fields})
print(f"[plot] wrote {out_csv}")
# ============================================================================
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--cta", required=True, help="CTA robustness_table.csv")
ap.add_argument("--xavdt", required=True, help="X-AVDT robustness_summary.csv")
ap.add_argument("--avhalign", required=True, help="AVH-Align merged_long_table.csv")
ap.add_argument("--avhalign_subset", default="non_diffusion",
choices=["overall", "non_diffusion", "SadTalk", "EDTalk", "Float"],
help="Which subset row to read from AVH-Align (default: "
"non_diffusion, matching CTA's three-family merged set)")
ap.add_argument("--out_dir", required=True)
args = ap.parse_args()
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
rows = []
rows += load_cta(args.cta)
rows += load_xavdt(args.xavdt)
rows += load_avhalign(args.avhalign, subset=args.avhalign_subset)
# report coverage
cov = defaultdict(set)
for r in rows:
cov[r["model"]].add((r["perturbation"], r["level"]))
print()
print("[plot] coverage:")
for m in ("CTA", "X-AVDT", "AVH-Align"):
print(f" {m}: {len(cov[m])} (perturbation, level) cells")
common_perts = sorted(set.intersection(
*[{p for p, _ in cov[m]} for m in cov]
)) if cov else []
print(f"[plot] perturbations covered by all three: {common_perts}")
print()
save_long_table(rows, out_dir / "merged_long_table.csv")
plot_per_perturbation(rows, out_dir)
plot_grid_auroc(rows, out_dir / "grid_auroc.png")
print(f"[plot] DONE. outputs in: {out_dir}")
if __name__ == "__main__":
main()
|