ViewingSoundPAQ / scripts /model /train_test /report_cv_all.py
xiaohaoy's picture
Initial release
16231ab verified
Raw History Blame Contribute Delete
3.94 kB
#!/usr/bin/env python3
"""Full CV report on a scoring list: every dataset, original datasets, all datasets pooled (reporting_rules.md).
python scripts/model/train_test/report_cv_all.py RUN_DIR --score-views LIST.csv [--compare OTHER_RUN_DIR] [--boot 300]
Prints Spearman / Pearson / RMSE / MAE / 80% coverage / width / Winkler per set and per AQ; with --compare, the paired
difference (RUN - OTHER) with a 95% group-bootstrap interval on the same views.
"""
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
from scipy.stats import spearmanr, pearsonr
AQ = ["pleasant", "eventful", "chaotic", "vibrant", "uneventful", "calm", "annoying", "monotonous"]
NEW = {"sonicurban", "open_sipset_v2", "eth_binaural_zurich", "taiwan_linebot"}
def metrics(x, s=""):
out = {}
for q in AQ:
t, p, lo, hi = x[f"target_{q}"], x[f"pred_{q}{s}"], x[f"lo_{q}{s}"], x[f"hi_{q}{s}"]
out[q] = dict(rho=spearmanr(p, t).statistic, r=pearsonr(p, t).statistic, rmse=np.sqrt(((p - t) ** 2).mean()),
mae=(p - t).abs().mean(), cov=((t >= lo) & (t <= hi)).mean(), width=(hi - lo).mean(),
wink=((hi - lo) + 10 * (lo - t).clip(lower=0) + 10 * (t - hi).clip(lower=0)).mean())
return pd.DataFrame(out).T
def boot_diff(x, B, rng):
g = x.group.to_numpy(); ug = np.unique(g); idx = {u: np.flatnonzero(g == u) for u in ug}; d = []
for _ in range(B):
y = x.iloc[np.concatenate([idx[u] for u in rng.choice(ug, len(ug))])]
d.append(np.mean([spearmanr(y[f"pred_{q}"], y[f"target_{q}"]).statistic - spearmanr(y[f"pred_{q}_b"], y[f"target_{q}"]).statistic for q in AQ]))
return np.percentile(d, [2.5, 97.5])
def main():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("run", type=Path); p.add_argument("--score-views", type=Path, required=True)
p.add_argument("--compare", type=Path); p.add_argument("--boot", type=int, default=300)
a = p.parse_args()
d = pd.read_csv(a.run / "range_predictions.csv")
d = d[d.view_id.isin(set(pd.read_csv(a.score_views).view_id))]
if a.compare:
b = pd.read_csv(a.compare / "range_predictions.csv")[["view_id"] + [f"{k}_{q}" for q in AQ for k in ("pred", "lo", "hi")]]
d = d.merge(b.rename(columns={c: c + "_b" for c in b.columns if c != "view_id"}), on="view_id")
sets = [("ALL DATASETS", d), ("original datasets", d[~d.training_dataset.isin(NEW)])] + \
[(ds, g) for ds, g in sorted(d.groupby("training_dataset"), key=lambda t: -len(t[1]))]
rng = np.random.default_rng(0)
hdr = f"{'set':40s} {'n':>6s} {'Spear':>6s} {'Pears':>6s} {'RMSE':>6s} {'MAE':>6s} {'cov':>6s} {'width':>6s} {'Wink':>6s}"
if a.compare: hdr += f" {'other':>6s} {'diff':>7s} {'95% CI':>17s}"
print(f"{a.run.name}: {len(d)} scored views ({a.score_views.name})"); print(hdr)
for name, x in sets:
m = metrics(x).mean()
line = f"{name[:40]:40s} {len(x):6d} {m['rho']:6.3f} {m['r']:6.3f} {m['rmse']:6.3f} {m['mae']:6.3f} {m['cov']:6.3f} {m['width']:6.2f} {m['wink']:6.3f}"
if a.compare:
o = metrics(x, "_b").mean()["rho"]
ci = boot_diff(x, a.boot if len(x) < 20000 else max(50, a.boot // 3), rng) if len(x) >= 200 else (np.nan, np.nan)
line += f" {o:6.3f} {m['rho'] - o:+7.4f} [{ci[0]:+.4f},{ci[1]:+.4f}]"
print(line)
for name, x in sets[:2]:
m = metrics(x)
print(f"\n{name} per AQ:"); print(m[["rho", "r", "rmse", "mae", "cov", "width", "wink"]].round(3).to_string())
if __name__ == "__main__":
main()