xiaohaoy's picture
Initial release
16231ab verified
Raw History Blame Contribute Delete
6.06 kB
"""Training data shared by the CV, comparison and inference scripts: the pairs of a training revision, their
SoundAQNet targets (one direct-AQ target file per pair, cached in one npz) and the ridge helpers."""
from __future__ import annotations
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import numpy as np
import pandas as pd
from dataset_labels import DEFAULT_EXCLUDED, apply_aliases
AQ = ["pleasant", "eventful", "chaotic", "vibrant", "uneventful", "calm", "annoying", "monotonous"]
TARGETS = ("aff", "ev", "sc") # [ISOP, ISOE, 8 PAQ], 15 AudioSet events, 3 scenes (SoundAQNet, one 10-s clip)
def training_pairs(manifest):
"""Every train/val/test pair with a direct-AQ target (DEFAULT_EXCLUDED datasets dropped), dataset aliases applied."""
f = pd.read_csv(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"])]
return apply_aliases(f.reset_index(drop=True))
def _read_target(path):
with np.load(path, allow_pickle=False) as z:
return (z["affective_mean"].astype(np.float32), z["event_mean"].astype(np.float32),
z["scene_probabilities"].astype(np.float32))
def load_targets(frame, path: Path, workers: int = 8):
"""SoundAQNet targets of the frame's pairs, keyed by view_id|direct_aq_target_path. Rows missing from the cache
are read from their target files and the cache is rewritten (older caches with image-feature blocks are read too)."""
keys = (frame.view_id.astype(str) + "|" + frame.direct_aq_target_path.astype(str)).to_numpy()
store, arrays = {}, {}
if path.exists():
with np.load(path, allow_pickle=True) as z:
store = {k: i for i, k in enumerate(z["keys"])}
arrays = {n: z[n] for n in TARGETS}
missing = [i for i, k in enumerate(keys) if k not in store]
if missing:
print(f"Target cache: reading {len(missing)} of {len(keys)} target files ({path})", flush=True)
with ThreadPoolExecutor(workers) as ex:
out = list(ex.map(_read_target, [frame.direct_aq_target_path.iloc[i] for i in missing]))
new = {n: np.stack([o[j] for o in out]) for j, n in enumerate(TARGETS)}
all_keys = list(store) + [keys[i] for i in missing]
arrays = {n: np.concatenate([arrays[n], new[n]]) if arrays else new[n] for n in TARGETS}
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(path.stem + ".partial.npz")
np.savez(tmp, version=2, keys=np.array(all_keys, dtype=object), **arrays)
for attempt in range(10): # Windows: antivirus / indexer can hold the file briefly
try:
tmp.replace(path); break
except PermissionError:
if attempt == 9:
raise
time.sleep(1.0)
store = {k: i for i, k in enumerate(all_keys)}
index = np.array([store[k] for k in keys])
return {n: arrays[n][index] for n in TARGETS}
def load_extra(path: Path, view_paths):
z = np.load(path, allow_pickle=True)
store = {str(k): i for i, k in enumerate(z["keys"])}
missing = [v for v in view_paths if v not in store]
if missing:
raise ValueError(f"{path}: {len(missing)} views have no feature (e.g. {missing[0]}). "
"Run extract_backbone_features.py on the same manifest/splits first.")
return z["features"][[store[v] for v in view_paths]].astype(np.float32)
def ridge_fit(X, Y, lam):
A = np.hstack([X, np.ones((len(X), 1))])
return np.linalg.solve(A.T @ A + lam * np.eye(A.shape[1]), A.T @ Y)
def ridge_predict(X, W):
return np.hstack([X, np.ones((len(X), 1))]) @ W
def dataset_cap_weights(datasets, cap):
"""Per-pair weights so that each dataset's total weight is min(its pairs, cap); mean weight 1."""
counts = pd.Series(datasets).value_counts()
w = np.array([min(counts[d], cap) / counts[d] for d in datasets], np.float64)
return w * len(w) / w.sum()
def ridge_anchor(Xraw, Y, train_idx, groups, lambdas, folds, seed, weights=None):
"""Standardize on train; lambda by grouped CV on train (out-of-fold MSE on the 8 PAQ);
train rows get out-of-fold predictions, other rows the full-train fit.
weights (optional, aligned with train_idx): weighted least squares + ridge; the lambda CV uses the weighted MSE."""
mu, sd = Xraw[train_idx].mean(0), Xraw[train_idx].std(0) + 1e-6
X = np.hstack([(Xraw - mu) / sd / np.sqrt(Xraw.shape[1]), np.ones((len(Xraw), 1))]).astype(np.float64)
w = np.ones(len(train_idx)) if weights is None else np.asarray(weights, np.float64)
rw = np.sqrt(w)[:, None]
uniq = np.unique(groups[train_idx])
fold_of = dict(zip(np.random.default_rng(seed).permutation(uniq), np.arange(len(uniq)) % folds))
fold = np.array([fold_of[g] for g in groups[train_idx]])
eye = np.eye(X.shape[1])
oof = {lam: np.zeros((len(train_idx), Y.shape[1])) for lam in lambdas}
def gram(rows): # rows: boolean mask over train_idx
Xw = X[train_idx[rows]] * rw[rows]
return Xw.T @ Xw, Xw.T @ (Y[train_idx[rows]] * rw[rows])
for k in range(folds):
hold = fold == k
G, R = gram(~hold)
for lam in lambdas:
oof[lam][hold] = X[train_idx[hold]] @ np.linalg.solve(G + lam * eye, R)
cv = {lam: float(np.sum(w[:, None] * (oof[lam][:, 2:] - Y[train_idx, 2:]) ** 2) / (w.sum() * (Y.shape[1] - 2)))
for lam in lambdas}
lam = min(cv, key=cv.get)
G, R = gram(np.ones(len(train_idx), bool))
W = np.linalg.solve(G + lam * eye, R)
base = X @ W
base[train_idx] = oof[lam]
print(f"Ridge anchor: {Xraw.shape[1]} features, lambda {lam:g} by grouped CV on train "
f"(out-of-fold MSE {', '.join(f'{k:g}: {v:.4f}' for k, v in cv.items())})")
return base.astype(np.float32), {"mu": mu, "sd": sd, "W": W, "lambda": lam, "cv_mse": cv}