LipFD / plot_compare_with_lipfd.py
huahua123313's picture
Add files using upload-large-folder tool
b58079c verified
Raw
History Blame Contribute Delete
5.48 kB
"""plot_compare_with_lipfd.py — merge LipFD v4 results into X-AVDT's
merged_long_table.csv, then produce a multi-method comparison figure
matching the reference grid_auroc.png layout (2x4, 1 empty cell).
Usage:
/opt/conda/envs/LipFD/bin/python plot_compare_with_lipfd.py
"""
import csv
import json
import os
import matplotlib.pyplot as plt
import numpy as np
X_AVDT_CSV = "/apdcephfs_gy4/share_303628665/joywu/research/X-AVDT/results/robustness/compare/merged_long_table.csv"
LIPFD_RUNS = "/apdcephfs_gy4/share_303628665/joywu/research/LipFD/robustnessv4/runs.json"
OUT_DIR = "/apdcephfs_gy4/share_303628665/joywu/research/LipFD/robustnessv4/compare"
os.makedirs(OUT_DIR, exist_ok=True)
# Order and display labels mirror the reference figure.
PERTURBATIONS = [
("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"),
]
# Methods + styling (reference: CTA red circle, X-AVDT blue square, AVH-Align green tri).
METHODS = [
("CTA", "#d62728", "o"),
("X-AVDT", "#1f77b4", "s"),
("AVH-Align", "#2ca02c", "^"),
("LipFD", "#9467bd", "D"), # purple diamond — new method
]
def load_xavdt_rows(path):
with open(path) as f:
return list(csv.DictReader(f))
def lipfd_to_rows(runs_json):
"""Convert LipFD v4 runs.json to long rows in the same schema as X-AVDT's CSV."""
runs = json.load(open(runs_json))["runs"]
# Identify the level=1 baseline (no-op). In LipFD it lives under gaussian_noise/L1.
baseline = next(r for r in runs if r["level"] == 1)
bl_metrics = baseline["overall_clip"]
rows = []
perturbs = sorted({r["perturbation"] for r in runs})
for p in perturbs:
# Level=1 is the SAME clean baseline for every perturbation.
rows.append({
"model": "LipFD", "perturbation": p, "level": "1", "param": "0.0",
"AUROC": bl_metrics["AUROC"], "AP": bl_metrics["AP"],
"Accuracy": bl_metrics["Accuracy"], "Acc@EER": bl_metrics["Acc@EER"],
})
for r in runs:
if r["perturbation"] != p or r["level"] == 1:
continue
o = r["overall_clip"]
rows.append({
"model": "LipFD", "perturbation": p, "level": str(r["level"]),
"param": str(r["param"]),
"AUROC": o["AUROC"], "AP": o["AP"],
"Accuracy": o["Accuracy"], "Acc@EER": o["Acc@EER"],
})
return rows
def write_merged(xavdt_rows, lipfd_rows, out_path):
cols = ["model", "perturbation", "level", "param",
"AUROC", "AP", "Accuracy", "Acc@EER"]
with open(out_path, "w", newline="") as f:
w = csv.DictWriter(f, fieldnames=cols)
w.writeheader()
for r in xavdt_rows:
w.writerow({k: r[k] for k in cols})
for r in lipfd_rows:
w.writerow(r)
print(f" wrote {out_path} ({len(xavdt_rows) + len(lipfd_rows)} rows)")
def index_by(rows, metric):
"""{model: {perturbation: {level: float}}} for the requested metric."""
out = {}
for r in rows:
out.setdefault(r["model"], {}).setdefault(r["perturbation"], {})[
int(r["level"])] = float(r[metric])
return out
def plot_grid(rows, metric, out_path, title=None):
idx = index_by(rows, metric)
levels = [1, 2, 3, 4, 5]
# 2x4 grid (7 perturbations + 1 empty); reference figure layout.
fig, axes = plt.subplots(2, 4, figsize=(20, 9), sharey=False)
for ax in axes.flatten():
ax.set_visible(False)
for i, (key, label) in enumerate(PERTURBATIONS):
ax = axes.flatten()[i]
ax.set_visible(True)
for method, color, marker in METHODS:
ys = [idx.get(method, {}).get(key, {}).get(L, np.nan) for L in levels]
ax.plot(levels, ys, marker=marker, color=color, label=method,
linewidth=2.0, markersize=8)
ax.set_title(label, fontsize=14)
ax.set_xlabel("Perturbation level (1 = clean, 5 = strongest)", fontsize=11)
ax.set_ylabel(metric, fontsize=11)
ax.set_xticks(levels)
ax.grid(alpha=0.3, linestyle=":")
handles, labels = axes.flatten()[0].get_legend_handles_labels()
fig.legend(handles, labels, loc="upper center", ncol=len(METHODS),
fontsize=13, frameon=False, bbox_to_anchor=(0.5, 1.02))
if title:
fig.suptitle(title, fontsize=14, y=1.05)
plt.tight_layout()
plt.savefig(out_path, dpi=140, bbox_inches="tight")
plt.close()
print(f" wrote {out_path}")
def main():
print(f"Loading X-AVDT rows from {X_AVDT_CSV}")
xavdt_rows = load_xavdt_rows(X_AVDT_CSV)
print(f" {len(xavdt_rows)} rows ({len({r['model'] for r in xavdt_rows})} methods)")
print(f"\nLoading LipFD v4 from {LIPFD_RUNS}")
lipfd_rows = lipfd_to_rows(LIPFD_RUNS)
print(f" {len(lipfd_rows)} rows from LipFD")
merged_csv = os.path.join(OUT_DIR, "merged_long_table.csv")
write_merged(xavdt_rows, lipfd_rows, merged_csv)
all_rows = xavdt_rows + lipfd_rows
for metric in ["AUROC", "AP", "Accuracy", "Acc@EER"]:
out_path = os.path.join(OUT_DIR, f"grid_{metric.lower().replace('@','_')}.png")
plot_grid(all_rows, metric, out_path)
if __name__ == "__main__":
main()