Download scripts/model/train_test/make_cv_folds.py from xiaohaoy/ViewingSoundPAQ: direct link, hf CLI and curl.
- Browser
- Download file 3.49 kB
-
https://huggingface.co/xiaohaoy/ViewingSoundPAQ/resolve/main/scripts/model/train_test/make_cv_folds.py
- Command line
-
hf download hf://xiaohaoy/ViewingSoundPAQ/scripts/model/train_test/make_cv_folds.py
-
curl -L -o make_cv_folds.py https://huggingface.co/xiaohaoy/ViewingSoundPAQ/resolve/main/scripts/model/train_test/make_cv_folds.py
3.49 kB
| #!/usr/bin/env python3 | |
| """10-fold grouped CV assignment of a training revision (the fold table every later revision extends). | |
| Every train/val/test pair with a direct-AQ target is assigned a fold by group (dataset | split_group), balanced per | |
| dataset: groups are placed largest first into the fold with the fewest rows of that dataset, then the fewest rows | |
| overall. Datasets with no val/test rows (e.g. Singapore field) get fold -1 (training only). trainable_pair marks | |
| pairs with ImageBind image-audio cosine >= 0.2. | |
| python scripts/model/train_test/make_cv_folds.py --manifest <rev>/metadata_manifest.csv --output <rev>/cv_folds.csv | |
| """ | |
| from __future__ import annotations | |
| 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 | |
| from dataset_labels import DEFAULT_EXCLUDED, apply_aliases | |
| def assign_cv_folds(frame, folds, seed, group_column="split_group"): | |
| """Deterministic group-wise folds, balanced per dataset. Returns fold (-1 = always training) and group key.""" | |
| orig = frame.original_training_dataset.astype(str) | |
| train_only = sorted(set(orig) - set(orig[frame.split.isin(["val", "test"])])) | |
| key = (orig + "|" + frame[group_column].astype(str)).to_numpy() | |
| rng = np.random.default_rng(seed) | |
| load, fold_of = np.zeros(folds), {} | |
| for d in sorted(set(orig) - set(train_only)): | |
| sizes = pd.Series(key[(orig == d).to_numpy()]).value_counts() | |
| names = sizes.index.to_numpy()[rng.permutation(len(sizes))] | |
| names = sorted(names, key=lambda g: -sizes[g]) # largest groups first, random order among ties | |
| per = np.zeros(folds) | |
| for g in names: | |
| k = int(np.lexsort((load, per))[0]) # fewest rows of this dataset, then fewest overall | |
| per[k] += sizes[g]; load[k] += sizes[g]; fold_of[g] = k | |
| return np.array([fold_of.get(g, -1) for g in key]), key | |
| def main(): | |
| p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| p.add_argument("--manifest", type=Path, required=True) | |
| p.add_argument("--output", type=Path, required=True) | |
| p.add_argument("--folds", type=int, default=10) | |
| p.add_argument("--seed", type=int, default=0) | |
| p.add_argument("--min-train-pair-cosine", type=float, default=0.2) | |
| a = p.parse_args() | |
| f = pd.read_csv(a.manifest, low_memory=False) | |
| f = f[f.direct_aq_target_status.eq("ok") & ~f.training_dataset.astype(str).str.casefold().isin(DEFAULT_EXCLUDED) | |
| & f.split.isin(["train", "val", "test"])] | |
| f = apply_aliases(f.reset_index(drop=True)) | |
| fold, key = assign_cv_folds(f, a.folds, a.seed) | |
| trainable = pd.to_numeric(f.image_audio_cosine, errors="coerce").ge(a.min_train_pair_cosine).to_numpy() | |
| a.output.parent.mkdir(parents=True, exist_ok=True) | |
| pd.DataFrame({"view_id": f.view_id, "view_path": f.view_path, "dataset": f.original_training_dataset, "split": f.split, | |
| "group": key, "fold": fold, "trainable_pair": trainable}).to_csv(a.output, index=False) | |
| print(f"{len(f)} pairs, {len(np.unique(key))} groups, {int((fold < 0).sum())} training-only; wrote {a.output}") | |
| if __name__ == "__main__": | |
| main() | |