Download scripts/model/evaluation/plot_hard_examples.py from xiaohaoy/ViewingSoundPAQ: direct link, hf CLI and curl.
- Browser
- Download file 6.37 kB
-
https://huggingface.co/xiaohaoy/ViewingSoundPAQ/resolve/main/scripts/model/evaluation/plot_hard_examples.py
- Command line
-
hf download hf://xiaohaoy/ViewingSoundPAQ/scripts/model/evaluation/plot_hard_examples.py
-
curl -L -o plot_hard_examples.py https://huggingface.co/xiaohaoy/ViewingSoundPAQ/resolve/main/scripts/model/evaluation/plot_hard_examples.py
6.37 kB
| #!/usr/bin/env python3 | |
| """Figure of the hardest held-out photos: predicted AQ (with 80% range) vs the real sound's AQ. | |
| Picks the photos whose predicted ISOPleasant is most above ("looks pleasant, sounds unpleasant") and most below | |
| ("looks unpleasant, sounds pleasant") the target, one per recording / place group, from the final model's 10-fold | |
| CV predictions on the original datasets. Under each photo: the 8 AQs (grey = real sound, SoundAQNet on the paired | |
| clip; blue = prediction with its 80% range) and the clip's most likely specific sound events. | |
| """ | |
| 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 | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| from PIL import Image | |
| AQ = ["pleasant", "eventful", "chaotic", "vibrant", "uneventful", "calm", "annoying", "monotonous"] | |
| EVENTS = ["Silence", "Human sounds", "Wind", "Water", "Natural sounds", "Traffic", "Sounds of things", "Vehicle", "Bird", | |
| "Outside, rural or natural", "Environment and background", "Speech", "Music", "Noise", "Animal"] | |
| SPECIFIC = ["Wind", "Water", "Traffic", "Vehicle", "Bird", "Speech", "Music", "Animal", "Silence"] | |
| NEW = {"sonicurban", "open_sipset_v2", "eth_binaural_zurich", "taiwan_linebot"} | |
| REV = "runs_main_all_datasets/direct_aq_dataset_gain/urbansas_whole_yfcc_binaural_v1_yfcc_nogeo_b0_21105_allnew_ref40_usotw4" | |
| GREY, BLUE, INK, QUIET = "#b9b8b2", "#2f7bd6", "#1f1f1f", "#6b6b6b" | |
| def parse_args(): | |
| p = argparse.ArgumentParser(description=__doc__) | |
| p.add_argument("--predictions", type=Path, | |
| default=Path("runs_main_all_datasets/cv_final/range_predictions.csv")) | |
| p.add_argument("--manifest", type=Path, default=Path(REV) / "metadata_manifest.csv") | |
| p.add_argument("--per-side", type=int, default=3) | |
| p.add_argument("--path-map", nargs=2, action="append", default=[], metavar=("FROM", "TO"), | |
| help="rewrite path prefixes (e.g. E:/ /mnt/e/) when running outside Windows") | |
| p.add_argument("--output", type=Path, default=Path("reports/figures/fig_hard_examples")) | |
| return p.parse_args() | |
| def main(): | |
| a = parse_args() | |
| fix = lambda s: (lambda t: [t := t.replace(f, to) for f, to in a.path_map][-1] if a.path_map else t)(str(s).replace("\\", "/")) | |
| d = pd.read_csv(fix(a.predictions)) | |
| d = d[~d.training_dataset.isin(NEW)] | |
| m = pd.read_csv(fix(a.manifest), low_memory=False, usecols=["view_id", "view_path", "direct_aq_target_path"]) | |
| d = d.merge(m, on="view_id").reset_index(drop=True) | |
| P, T = d[[f"pred_{q}" for q in AQ]].to_numpy(), d[[f"target_{q}" for q in AQ]].to_numpy() | |
| c = np.cos(np.pi / 4) | |
| iso = lambda X: ((X[:, 0] - X[:, 6]) + c * (X[:, 5] - X[:, 2]) + c * (X[:, 3] - X[:, 7])) / (4 + np.sqrt(32)) | |
| d["dP"] = iso(P) - iso(T) | |
| d["rec"] = d.view_path.astype(str).str.replace("\\", "/").str.split("/").str[-3] | |
| picks = [] | |
| for side, asc in (("Looks pleasant, sounds unpleasant", False), ("Looks unpleasant, sounds pleasant", True)): | |
| s = d.sort_values("dP", ascending=asc).drop_duplicates("rec").drop_duplicates("group") | |
| picks += [(side, i) for i in s.index[:a.per_side]] | |
| n = a.per_side | |
| fig = plt.figure(figsize=(4.2 * n, 15.0), dpi=150) | |
| for k, (side, i) in enumerate(picks): | |
| r, col = divmod(k, n) | |
| x0, w = col / n + 0.012, 1 / n - 0.024 | |
| y_img, y_aq = (0.712, 0.545) if r == 0 else (0.222, 0.052) | |
| if col == 0: | |
| fig.text(0.012, y_img + 0.255, side, fontsize=15, weight="bold", color=INK) | |
| ax = fig.add_axes([x0, y_img, w, 0.225]) | |
| im = Image.open(fix(d.view_path[i])).convert("RGB") | |
| W_, H_ = im.size # centre crop to 4:3 so all photos line up | |
| if W_ / H_ > 4 / 3: | |
| cw = int(H_ * 4 / 3); im = im.crop(((W_ - cw) // 2, 0, (W_ - cw) // 2 + cw, H_)) | |
| else: | |
| ch = int(W_ * 3 / 4); im = im.crop((0, (H_ - ch) // 2, W_, (H_ - ch) // 2 + ch)) | |
| ax.imshow(im, aspect="auto"); ax.set_xticks([]); ax.set_yticks([]) | |
| for sp in ax.spines.values(): | |
| sp.set_visible(False) | |
| with np.load(fix(d.direct_aq_target_path[i])) as z: | |
| ev = z["event_mean"] | |
| top = sorted(((ev[EVENTS.index(e)], e) for e in SPECIFIC), reverse=True)[:3] | |
| ax.set_title(f"{d.training_dataset[i].split('_')[0]} \u00b7 heard: " + ", ".join(f"{e.lower()} {p:.2f}" for p, e in top), | |
| fontsize=9.5, color=QUIET, loc="left") | |
| bx = fig.add_axes([x0 + 0.075, y_aq, w - 0.085, 0.145]) | |
| ys = np.arange(len(AQ))[::-1] | |
| lo, hi = d.loc[i, [f"lo_{q}" for q in AQ]].to_numpy(float), d.loc[i, [f"hi_{q}" for q in AQ]].to_numpy(float) | |
| bx.hlines(ys, lo, hi, color=BLUE, alpha=0.25, lw=6) | |
| bx.scatter(T[i], ys, s=42, color=GREY, zorder=3, label="real sound") | |
| bx.scatter(P[i], ys, s=30, color=BLUE, zorder=4, label="predicted (80% range)") | |
| bx.set_yticks(ys); bx.set_yticklabels(AQ, fontsize=9.5) | |
| bx.set_xlim(1, 5); bx.set_xticks([1, 2, 3, 4, 5]); bx.tick_params(axis="x", labelsize=9) | |
| bx.grid(axis="x", color="#e6e6e3", lw=0.8); bx.set_axisbelow(True) | |
| for sp in ("top", "right", "left"): | |
| bx.spines[sp].set_visible(False) | |
| if k == 0: | |
| bx.legend(loc="lower right", bbox_to_anchor=(1.0, 1.0), ncol=2, fontsize=9, frameon=False) | |
| fig.text(0.012, 0.012, "Held-out photos (10-fold CV) with the largest ISOPleasant errors, one per recording; AQ on the 1\u20135 scale. " | |
| "Real sound = SoundAQNet on the paired 10-s clip; 'heard' = its event probabilities.", fontsize=9, color=QUIET) | |
| out = Path(fix(a.output)) | |
| out.parent.mkdir(parents=True, exist_ok=True) | |
| fig.savefig(out.with_suffix(".png"), dpi=150, facecolor="white", bbox_inches="tight") | |
| fig.savefig(out.with_suffix(".pdf"), facecolor="white", bbox_inches="tight") | |
| print(f"Wrote {out.with_suffix('.png')} and .pdf") | |
| print(d.loc[[i for _, i in picks], ["training_dataset", "rec", "dP"]].to_string()) | |
| if __name__ == "__main__": | |
| main() | |