ViewingSoundPAQ / scripts /model /evaluation /plot_scene_contrasts.py
xiaohaoy's picture
Scene-type figure on the final pairs
274f87c verified
Raw History Blame Contribute Delete
3.86 kB
#!/usr/bin/env python3
"""Scene-type contrasts figure from scene_type_validation.py output: predicted vs real AQ difference per photo group."""
import sys as _sys
from pathlib import Path as _Path
_SCRIPTS = next(_p for _p in _Path(__file__).resolve().parents if _p.name == "scripts")
_sys.path[:0] = [str(_SCRIPTS.parent), str(_SCRIPTS.parent / "models")] + [str(_d) for _d in sorted(_SCRIPTS.rglob("*")) if _d.is_dir() and _d.name != "__pycache__"]
import argparse, json
from pathlib import Path
import numpy as np
import matplotlib; matplotlib.use("Agg")
import matplotlib.pyplot as plt
from scipy.stats import spearmanr
AQ = ["pleasant", "eventful", "chaotic", "vibrant", "uneventful", "calm", "annoying", "monotonous"]
PANELS = [("urban - natural (neither)", "Urban − natural", "urban/neither", "natural/neither"),
("urban: traffic - neither", "Urban: traffic", "urban/traffic", "urban/neither"),
("urban: people - neither", "Urban: people", "urban/people", "urban/neither"),
("natural: traffic - neither", "Natural: traffic", "natural/traffic", "natural/neither"),
("natural: people - neither", "Natural: people", "natural/people", "natural/neither")]
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--validation", type=Path, required=True); p.add_argument("--output", type=Path, required=True)
a = p.parse_args()
j = json.load(open(a.validation)); G = j["groups"]; C = j["contrasts"]
INK, QUIET, GREY, BLUE, RULE = "#1f1f1f", "#5f5f5f", "#c4c3bb", "#2f7bd6", "#d9d8d2"
fig, axes = plt.subplots(1, 5, figsize=(13.4, 7.6), dpi=150, sharey=True)
y = np.arange(len(AQ))[::-1]
rhos = []
for ax, (key, title, g1, g2) in zip(axes, PANELS):
c = C[key]; pr = np.array([c[q]["pred"] for q in AQ]); tg = np.array([c[q]["target"] for q in AQ])
rhos.append(spearmanr(pr, tg).statistic)
for v in (-0.5, 0.5): ax.axvline(v, color="#ececea", lw=1, zorder=0)
ax.axvline(0, color=GREY, lw=1.2, zorder=0)
for yi, a_, b_ in zip(y, tg, pr): ax.plot([a_, b_], [yi, yi], color=RULE, lw=2, zorder=1)
ax.scatter(tg, y, s=90, color=GREY, zorder=2); ax.scatter(pr, y, s=90, color=BLUE, zorder=3)
ax.set_xlim(-1.15, 1.15); ax.set_xticks([-0.5, 0, 0.5]); ax.set_xticklabels(["−0.5", "0", "+0.5"], color=QUIET)
ax.set_title(f"{title}\n", fontsize=12, fontweight="bold", color=INK, pad=2)
ax.text(0.5, 1.005, f"n {G[g1]['n']:,} vs {G[g2]['n']:,}", transform=ax.transAxes, ha="center", va="bottom", fontsize=10, color=QUIET)
for s in ("top", "right", "left", "bottom"): ax.spines[s].set_visible(False)
ax.tick_params(length=0)
axes[0].set_yticks(y); axes[0].set_yticklabels(AQ, fontsize=12, color=INK)
fig.text(0.02, 0.965, "Predicted AQ differences follow the real sound across scene types and events", fontsize=15, fontweight="bold", color=INK)
fig.text(0.02, 0.928, f"Difference in mean AQ between photo groups (1-5 scale), held-out photos; pattern over the 8 AQs matches at ρ {min(rhos):.2f}-{max(rhos):.2f}",
fontsize=11, color=QUIET)
fig.legend(handles=[plt.Line2D([], [], marker="o", ls="", color=GREY, ms=9, label="real sound (SoundAQNet on the recorded clip)"),
plt.Line2D([], [], marker="o", ls="", color=BLUE, ms=9, label="predicted from the photo")],
loc="upper left", bbox_to_anchor=(0.012, 0.915), ncol=2, frameon=False, fontsize=11)
fig.text(0.02, 0.03, "Groups from segmentation (not a model input): natural = vegetation + terrain ≥ 40%; urban = road + sidewalk + building ≥ 30%;\n"
"traffic or people ≥ 10% of the image, compared with photos where both are below 2%.", fontsize=10, color=QUIET)
fig.subplots_adjust(left=0.10, right=0.99, top=0.80, bottom=0.17, wspace=0.12)
a.output.parent.mkdir(parents=True, exist_ok=True)
fig.savefig(a.output, dpi=150, facecolor="white"); print(f"Wrote {a.output}")