ViewingSoundPAQ / scripts /data_preparation /assemble /fold_training_only.py
xiaohaoy's picture
Initial release
16231ab verified
Raw History Blame Contribute Delete
4.24 kB
#!/usr/bin/env python3
"""Give the training-only views (fold -1) a CV fold so that every trained dataset is also scored (reporting_rules.md).
fold -1 before: YFCC non-geotagged expansion (uploader groups, uploaders not used elsewhere), seasonal_local (25 Ann
Arbor sites), singapore_field (31 Singapore grid cells).
- YFCC expansion: whole uploader groups to folds, balanced by size (no uploader appears in another fold).
- singapore_field: a site within --sg-radius m of a Lion City site takes that Lion City site's fold (the nearest one),
so the two never sit on opposite sides of a split (before, every Singapore site trained while its Lion City
neighbour was scored: leakage into Lion City); other sites are balanced by group.
- seasonal_local: no coordinates in the manifest, so whole sites are balanced by group (sites are distinct from the
Ann Arbor/Detroit places per the user, but their distance to them is unchecked).
Writes <out> with the same columns; every other row keeps its fold.
"""
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
import numpy as np, pandas as pd
REV = "runs_main_all_datasets/direct_aq_dataset_gain/urbansas_whole_yfcc_binaural_v1_yfcc_nogeo_b0_21105_allnew_ref40_usotw4"
def hav(a, b, c, d):
a, b, c, d = map(np.radians, (a, b, c, d))
return 2 * 6371000 * np.arcsin(np.sqrt(np.sin((c - a) / 2) ** 2 + np.cos(a) * np.cos(c) * np.sin((d - b) / 2) ** 2))
def balance(sizes, counts, rng):
"""assign groups (largest first) to the fold with the fewest rows; counts is updated in place."""
out = {}
for g in sorted(sizes.index, key=lambda g: (-sizes[g], rng.random())):
f = int(np.argmin(counts)); out[g] = f; counts[f] += sizes[g]
return out
def main():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--folds", default=f"{REV}/cv_folds_combined_no_tau_indoor_manual_dark_360indoor.csv")
p.add_argument("--manifest", default=f"{REV}/metadata_manifest.csv")
p.add_argument("--out", default=f"{REV}/cv_folds_combined_no_tau_indoor_manual_dark_360indoor_allscored.csv")
p.add_argument("--sg-radius", type=float, default=2000.0, help="Lion City uses 2-km blocks")
p.add_argument("--seed", type=int, default=42)
a = p.parse_args()
rng = np.random.default_rng(a.seed)
fo = pd.read_csv(a.folds)
m = pd.read_csv(a.manifest, low_memory=False, usecols=["view_id", "lat", "lon"])
d = fo.merge(m, on="view_id", how="left")
k = int(fo.fold.max()) + 1
counts = np.bincount(fo.fold[fo.fold >= 0], minlength=k).astype(float)
neg = d.fold < 0
assign = {}
# singapore_field near Lion City
lc = d[(d.dataset == "lion_city_soundscapes") & (d.fold >= 0)]
sg = d[neg & (d.dataset == "singapore_field")].groupby("group")[["lat", "lon"]].first()
far = []
for g, r in sg.iterrows():
dist = hav(r.lat, r.lon, lc.lat.values, lc.lon.values); i = int(np.argmin(dist))
if dist[i] <= a.sg_radius:
assign[g] = int(lc.fold.iloc[i])
else:
far.append(g)
near_n = len(sg) - len(far)
for g in assign: counts[assign[g]] += (d.group[neg] == g).sum()
rest = d[neg & ~d.group.isin(assign)]
for ds in ["yfcc100m_street", "seasonal_local", "singapore_field"]:
sizes = rest[rest.dataset == ds].groupby("group").size()
assign.update(balance(sizes, counts, rng))
left = d[neg & ~d.group.isin(assign)]
if len(left):
raise SystemExit(f"unassigned fold -1 rows: {left.dataset.value_counts().to_dict()}")
fo.loc[fo.fold < 0, "fold"] = fo.loc[fo.fold < 0, "group"].map(assign).astype(int)
fo.to_csv(a.out, index=False)
print(f"singapore_field: {near_n} of {len(sg)} sites within {a.sg_radius:.0f} m of a Lion City site -> its fold")
print("rows per fold:", np.bincount(fo.fold, minlength=k).tolist())
print(f"Wrote {a.out}")
if __name__ == "__main__":
main()