Download scripts/model/evaluation/plot_place_average.py from xiaohaoy/ViewingSoundPAQ: direct link, hf CLI and curl.
- Browser
- Download file 5.65 kB
-
https://huggingface.co/xiaohaoy/ViewingSoundPAQ/resolve/main/scripts/model/evaluation/plot_place_average.py
- Command line
-
hf download hf://xiaohaoy/ViewingSoundPAQ/scripts/model/evaluation/plot_place_average.py
-
curl -L -o plot_place_average.py https://huggingface.co/xiaohaoy/ViewingSoundPAQ/resolve/main/scripts/model/evaluation/plot_place_average.py
5.65 kB
| #!/usr/bin/env python3 | |
| """Place-level average: Spearman per AQ when the predictions of k photos of a place are averaged. | |
| The held-out pairs of the 10-fold CV that count in the report are used (--score-views). A place is a real location: TAU location, Urbansas / Ann Arbor-Detroit | |
| site, Urban Soundscapes of the World / Lion City recording, 360+x / YFCC / SonicUrban video, Open SIPset sound recording | |
| (with its nearby photos), ETH Zurich scene, Taiwan report coordinates. Places are split by how many photos they have (exactly 2, 3, 4, or >= 5); within each set, every k is scored on the | |
| same places. The place's target is the mean over all its clips (fixed); its prediction is the mean of k randomly drawn | |
| photos' held-out predictions (k = 1 .. photos available, at most 5), repeated --draws times. | |
| """ | |
| 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, pandas as pd | |
| import matplotlib; matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| from scipy.stats import spearmanr | |
| AQ = ["pleasant", "eventful", "chaotic", "vibrant", "uneventful", "calm", "annoying", "monotonous"] | |
| REV = "runs_main_all_datasets/direct_aq_dataset_gain/urbansas_whole_yfcc_binaural_v1_yfcc_nogeo_b0_21105_allnew_ref40_usotw4" | |
| KEY = {"360x_outdoor": "recording_id", "lion_city_soundscapes": "recording_id", "michigan": "parent_location_id", | |
| "tau_urban_audio_visual_2021_nonoverlap": "location", "urban_soundscapes_world": "recording_id", | |
| "urbansas_whole": "physical_site", "yfcc100m_street": "yfcc_hash", | |
| "sonicurban": "recording_id", "open_sipset_v2": "recording_id", "eth_binaural_zurich": "recording_id", | |
| "taiwan_linebot": "latlon", "singapore_field": "split_group", "seasonal_local": "split_group"} | |
| p = argparse.ArgumentParser(description=__doc__) | |
| p.add_argument("--predictions", type=Path, required=True, help="compare_ranges.py range_predictions.csv") | |
| p.add_argument("--manifest", type=Path, default=Path(REV) / "metadata_manifest.csv") | |
| p.add_argument("--score-views", type=Path, default=None, help="only these held-out pairs count (make_score_list.py)") | |
| p.add_argument("--draws", type=int, default=200) | |
| p.add_argument("--seed", type=int, default=0) | |
| p.add_argument("--output", type=Path, default=Path("reports/figures/fig_place_average")) | |
| a = p.parse_args() | |
| d = pd.read_csv(a.predictions) | |
| if a.score_views is not None: | |
| d = d[d.view_id.isin(set(pd.read_csv(a.score_views).view_id))] | |
| m = pd.read_csv(a.manifest, low_memory=False, usecols=["view_id", "lat", "lon"] + sorted(set(KEY.values()) - {"latlon"})) | |
| m["latlon"] = m.lat.round(5).astype(str) + "," + m.lon.round(5).astype(str) | |
| d = d.merge(m, on="view_id") | |
| d["place"] = [f"{ds}|{getattr(r, KEY[ds])}" for ds, r in zip(d.training_dataset, d.itertuples())] | |
| n = d.groupby("place").size() | |
| Pall = d[[f"pred_{q}" for q in AQ]].to_numpy() | |
| rng = np.random.default_rng(a.seed) | |
| groups = [(f"places with {k} photos", n[n == k].index, k) for k in (2, 3, 4)] + \ | |
| [(f"places with >= 5 photos", n[n >= 5].index, 5)] | |
| groups = groups[::-1] | |
| panels = [] | |
| for title, places, kmax in groups: | |
| places = list(places) | |
| sub = d[d.place.isin(places)] | |
| T = sub.groupby("place")[[f"target_{q}" for q in AQ]].mean().loc[places].to_numpy() | |
| idx = {pl: np.flatnonzero(d.place.to_numpy() == pl) for pl in places} | |
| res = {} | |
| for k in range(1, kmax + 1): | |
| reps = 1 if k == kmax and kmax < 5 else a.draws | |
| acc = np.zeros(len(AQ)) | |
| for _ in range(reps): | |
| P = np.stack([Pall[rng.choice(idx[pl], k, replace=False)].mean(0) for pl in places]) | |
| acc += [spearmanr(P[:, j], T[:, j]).statistic for j in range(len(AQ))] | |
| res[k] = acc / reps | |
| mix = sub.drop_duplicates("place").training_dataset.value_counts().to_dict() | |
| print(f"{title}: {len(places)} places, {len(sub)} photos, {mix}") | |
| for k, r in res.items(): | |
| print(f" k={k}: mean {r.mean():.3f} " + " ".join(f"{q[:5]} {v:.3f}" for q, v in zip(AQ, r))) | |
| panels.append((title, len(places), res)) | |
| INK, QUIET = "#1f1f1f", "#6b6b6b" | |
| colors = ["#b9b8b2", "#9ec5f4", "#5a9ee8", "#2f7bd6", "#174f99"] | |
| fig, axes = plt.subplots(len(panels), 1, figsize=(10.2, 3.0 * len(panels)), dpi=150, sharex=True) | |
| x = np.arange(len(AQ)) | |
| for ax, (title, npl, res) in zip(axes, panels): | |
| off = np.linspace(-0.28, 0.28, 5) | |
| for k, r in res.items(): | |
| lab = "1 photo" if k == 1 else f"average of {k} photos" | |
| ax.scatter(x + off[k - 1], r, s=40, color=colors[k - 1], zorder=3, label=f"{lab} (mean {r.mean():.3f})") | |
| ax.set_title(f"{title} ({npl:,} places)", fontsize=11, loc="left", color=INK) | |
| ax.grid(axis="y", color="#e6e6e3", lw=0.8); ax.set_axisbelow(True) | |
| for sp in ("top", "right"): ax.spines[sp].set_visible(False) | |
| ax.set_ylabel("Spearman", fontsize=9) | |
| ax.legend(fontsize=8, frameon=False, loc="center left", bbox_to_anchor=(1.0, 0.5)) | |
| axes[-1].set_xticks(x); axes[-1].set_xticklabels(AQ, fontsize=9.5) | |
| fig.suptitle("Place-level average: Spearman with the place's recorded sound when k photos are averaged", x=0.01, ha="left", fontsize=12, color=INK) | |
| fig.tight_layout() | |
| a.output.parent.mkdir(parents=True, exist_ok=True) | |
| fig.savefig(a.output.with_suffix(".png"), dpi=150, facecolor="white", bbox_inches="tight") | |
| fig.savefig(a.output.with_suffix(".pdf"), facecolor="white", bbox_inches="tight") | |
| print(f"Wrote {a.output.with_suffix('.png')}") | |