Download scripts/model/inference/predict_photo_aq.py from xiaohaoy/ViewingSoundPAQ: direct link, hf CLI and curl.
- Browser
- Download file 17 kB
-
https://huggingface.co/xiaohaoy/ViewingSoundPAQ/resolve/main/scripts/model/inference/predict_photo_aq.py
- Command line
-
hf download hf://xiaohaoy/ViewingSoundPAQ/scripts/model/inference/predict_photo_aq.py
-
curl -L -o predict_photo_aq.py https://huggingface.co/xiaohaoy/ViewingSoundPAQ/resolve/main/scripts/model/inference/predict_photo_aq.py
17 kB
| #!/usr/bin/env python3 | |
| """Predict the 8 PAQ affective qualities and a photo-dependent 80% range for new photos with the final model, optionally | |
| scoring them against human ratings. | |
| Final model: kernel ridge (RBF) on two frozen encoders, SigLIP 2 giant (pooled + mean token, 3,072-d) and Perception | |
| Encoder PE-Core bigG/14 448 px (1,280-d), with a kernel ridge spread model for the 80% range (range = prediction + | |
| s(x) x the 10th / 90th percentile of out-of-fold residual / s(x)). Without --krr: linear ridge on the same features. | |
| Use the shipped model (--model models/final/model_siglip_krr_pe.npz), or fit it from a training revision (--manifest, | |
| --cache, --train-exclude-views): every train/val/test pair with image-audio cosine >= 0.2 that is not excluded trains; | |
| gamma = 1 / (0.5 x median squared distance between standardized training photos), lambda by grouped 5-fold CV | |
| (groups = dataset | split_group). The saved model holds the standardized training features (~300 MB), which kernel | |
| prediction needs. | |
| Outputs in --output-dir: | |
| model_siglip_<krr|ridge>_pe.npz the fitted model (reused on later runs unless --refit) | |
| predictions_siglip.csv image, 8 AQ predictions, lower/upper | |
| evaluation_siglip.json if --ratings is given: Spearman / Pearson per AQ and on the ISO 12913-3 axes | |
| Ratings CSVs: first column = image file name; AQ columns named Pleasant, Eventful, ... (any case). Scales may | |
| differ from the model's (only correlations are reported). | |
| """ | |
| 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 | |
| import json | |
| import re | |
| import time | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| from scipy.stats import pearsonr, spearmanr | |
| from aq_data import AQ, load_extra, load_targets, ridge_anchor, training_pairs # noqa: E402 | |
| def parse_args(): | |
| p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| p.add_argument("--manifest", type=Path, default=None, help="training manifest (needed only to fit the model)") | |
| p.add_argument("--cache", type=Path, default=None, help="target cache of the training revision (needed only to fit the model)") | |
| p.add_argument("--siglip-features", type=Path, default=Path("runs_main_all_datasets/backbone_compare/features_siglip2_giant_384.npz")) | |
| p.add_argument("--pe-features", type=Path, default=Path("runs_main_all_datasets/backbone_compare/features_pe_core_bigg14_448.npz"), | |
| help="Perception Encoder (PE-Core bigG/14, 448 px) features of the training pairs (extract_backbone_features.py).") | |
| p.add_argument("--images", type=Path, nargs="+", required=True, help="Image folders (searched recursively) or files.") | |
| p.add_argument("--ratings", type=Path, nargs="*", default=[], help="Human-rating CSVs to score against.") | |
| p.add_argument("--output-dir", type=Path, required=True) | |
| p.add_argument("--model", type=Path, default=None, | |
| help="fitted model to use (e.g. models/final/model_siglip_krr_pe.npz); default: the model file in --output-dir") | |
| p.add_argument("--min-train-pair-cosine", type=float, default=0.2) | |
| p.add_argument("--lambdas", type=float, nargs="+", default=[1, 3, 10, 30, 100, 300]) | |
| p.add_argument("--scale-lambdas", type=float, nargs="+", default=[10, 30, 100, 300, 1000, 3000]) | |
| p.add_argument("--refit", action="store_true") | |
| p.add_argument("--train-exclude-views", type=Path, nargs="*", default=[], | |
| help="CSV(s) with a view_id column: these pairs never train (e.g. the combined revision's " | |
| "train_exclude_combined.csv: training subsets of the large added datasets)") | |
| p.add_argument("--krr", action="store_true", help="Kernel ridge (RBF) instead of linear ridge (see above).") | |
| p.add_argument("--krr-width", type=float, default=0.5, help="RBF gamma = 1 / (width x median squared distance)") | |
| p.add_argument("--krr-lambdas", type=float, nargs="+", default=[0.3, 1, 3, 10]) | |
| p.add_argument("--spread-krr-lambdas", type=float, nargs="+", default=[1, 3, 10, 30, 100, 300], | |
| help="--krr: lambda grid of the kernel ridge spread model (log-residual targets are noisy)") | |
| p.add_argument("--batch-size", type=int, default=32) | |
| p.add_argument("--device", default="cuda") | |
| return p.parse_args() | |
| def fit(args): | |
| f = training_pairs(args.manifest) | |
| f = f[pd.to_numeric(f.image_audio_cosine, errors="coerce").ge(args.min_train_pair_cosine)] | |
| if args.train_exclude_views: | |
| drop = set().union(*(set(pd.read_csv(x).view_id.astype(str)) for x in args.train_exclude_views)) | |
| n0 = len(f) | |
| f = f[~f.view_id.astype(str).isin(drop)] | |
| print(f"Training exclusions: {n0 - len(f)} pairs left out, {len(f)} train") | |
| f = f.reset_index(drop=True) | |
| aff = load_targets(f, args.cache)["aff"].astype(np.float64) | |
| keys = f.view_path.astype(str).tolist() | |
| X = np.hstack([load_extra(args.siglip_features, keys), load_extra(args.pe_features, keys)]).astype(np.float64) | |
| groups = (f.original_training_dataset.astype(str) + "|" + f.split_group.astype(str)).to_numpy() | |
| t_mean, t_std = aff.mean(0), aff.std(0).clip(1e-4) | |
| Y = (aff - t_mean) / t_std | |
| tr = np.arange(len(f)) | |
| if args.krr: | |
| base, ridge = krr_fit(X, Y, groups, args) | |
| else: | |
| base, ridge = ridge_anchor(X, Y, tr, groups, args.lambdas, 5, 42) # base = out-of-fold predictions | |
| oof = base[:, 2:] * t_std[2:] + t_mean[2:] | |
| resid = aff[:, 2:] - oof | |
| rho = [spearmanr(oof[:, k], aff[:, 2 + k]).statistic for k in range(8)] | |
| # photo-dependent spread: a model of log|standardized out-of-fold residual|; its own out-of-fold output calibrates. | |
| # With --krr the spread model is kernel ridge on the same kernel (adopted 2026-11-21: 10-fold CV Winkler | |
| # 1.662 -> 1.658 [-0.0068, -0.0012], width vs |error| 0.142 -> 0.152); otherwise a linear ridge. | |
| r = Y[:, 2:] - base[:, 2:] | |
| Lr = np.log(np.abs(r) + 0.05) | |
| if args.krr: | |
| lm, ls = Lr.mean(0), Lr.std(0) + 1e-9 | |
| point_lams, args.krr_lambdas = args.krr_lambdas, args.spread_krr_lambdas | |
| print("Spread model (kernel ridge on log |out-of-fold residual|):") | |
| s_oof, s_krr = krr_fit(X, np.hstack([np.zeros((len(r), 2)), (Lr - lm) / ls]), groups, args) | |
| args.krr_lambdas = point_lams | |
| s_base = s_oof[:, 2:] * ls + lm | |
| s_ridge = {"W": np.zeros((1, 1)), "lambda": s_krr["lambda"]} | |
| model_extra = {"kind": np.array("krr"), "A": ridge["A"], "alpha": ridge["alpha"], "gamma": ridge["gamma"], | |
| "spread_kind": np.array("krr"), "s_alpha": s_krr["alpha"][:, 2:], "s_lm": lm, "s_ls": ls} | |
| ridge["W"] = np.zeros((1, 1)) | |
| else: | |
| z = np.hstack([np.zeros((len(r), 2)), Lr]) # 2 dummy columns: ridge_anchor scores columns 2: (the 8 AQ) | |
| s_base, s_ridge = ridge_anchor(X, z, tr, groups, args.scale_lambdas, 5, 42) | |
| s_base, s_ridge["W"] = s_base[:, 2:], s_ridge["W"][:, 2:] | |
| model_extra = {"kind": np.array("ridge"), "spread_kind": np.array("ridge")} | |
| u = r / np.exp(s_base) | |
| model = {**model_extra, "mu": ridge["mu"], "sd": ridge["sd"], "W": ridge["W"], "lambda": ridge["lambda"], "t_mean": t_mean, "t_std": t_std, | |
| "q_lo": np.quantile(resid, 0.1, axis=0), "q_hi": np.quantile(resid, 0.9, axis=0), "train_pairs": len(f), | |
| "oof_spearman": np.array(rho), "s_W": s_ridge["W"], "s_lambda": s_ridge["lambda"], | |
| "qs_lo": np.quantile(u, 0.1, axis=0), "qs_hi": np.quantile(u, 0.9, axis=0)} | |
| print(f"Fitted on {len(f)} pairs ({f.training_dataset.nunique()} datasets), lambda {ridge['lambda']:g}; " | |
| f"out-of-fold Spearman (5 grouped folds) mean {np.mean(rho):.3f}: " + ", ".join(f"{a} {r:.2f}" for a, r in zip(AQ, rho))) | |
| return model | |
| def krr_fit(X, Y, groups, args): | |
| """Kernel ridge (RBF) on standardized features / sqrt(D): grouped 5-fold out-of-fold predictions (lambda chosen on | |
| them) and the full fit. Returns (oof, model dict) like ridge_anchor.""" | |
| import torch | |
| from sklearn.model_selection import GroupKFold | |
| dev = torch.device("cuda" if torch.cuda.is_available() and args.device != "cpu" else "cpu") | |
| mu, sd = X.mean(0), X.std(0) + 1e-9 | |
| A = ((X - mu) / sd / np.sqrt(X.shape[1])).astype(np.float32) | |
| At = torch.tensor(A, device=dev) | |
| Yt = torch.tensor(Y, dtype=torch.float32, device=dev) | |
| sq = At.pow(2).sum(1) | |
| Dm = (sq[:, None] + sq[None, :] - 2 * At @ At.T).clamp_min(0) | |
| sub = torch.randperm(len(At), generator=torch.Generator().manual_seed(0))[:2000].to(dev) | |
| gamma = 1.0 / (args.krr_width * float(Dm[sub][:, sub].median())) | |
| K = torch.exp(-gamma * Dm) | |
| del Dm | |
| lams = args.krr_lambdas | |
| oof = {lam: torch.zeros_like(Yt) for lam in lams} | |
| for tr, va in GroupKFold(5).split(X, groups=groups): | |
| tr_t, va_t = torch.as_tensor(tr, device=dev), torch.as_tensor(va, device=dev) | |
| e, V = torch.linalg.eigh(K[tr_t][:, tr_t]) | |
| Vy, KvV = V.T @ Yt[tr_t], K[va_t][:, tr_t] @ V | |
| for lam in lams: | |
| oof[lam][va_t] = KvV @ (Vy / (e.clamp_min(0) + lam)[:, None]) | |
| err = {lam: float((oof[lam][:, 2:] - Yt[:, 2:]).pow(2).mean()) for lam in lams} | |
| lam = min(err, key=err.get) | |
| alpha = torch.linalg.solve(K + lam * torch.eye(len(K), device=dev), Yt) | |
| print(f"Kernel ridge: gamma {gamma:.4g} (width {args.krr_width} x median squared distance), lambda {lam:g} " | |
| f"(grouped 5-fold MSE " + ", ".join(f"{k:g}: {v:.4f}" for k, v in err.items()) + ")") | |
| return oof[lam].cpu().numpy().astype(np.float64), {"mu": mu, "sd": sd, "A": A, "alpha": alpha.cpu().numpy(), | |
| "gamma": np.array(gamma), "lambda": lam} | |
| def iso(get): | |
| """ISO/TS 12913-3 ISOPleasant / ISOEventful from the 8 PAQ (any common scale).""" | |
| c, k = np.cos(np.pi / 4), 4 + np.sqrt(32) | |
| p = ((get("pleasant") - get("annoying")) + c * (get("calm") - get("chaotic")) + c * (get("vibrant") - get("monotonous"))) / k | |
| e = ((get("eventful") - get("uneventful")) + c * (get("chaotic") - get("calm")) + c * (get("vibrant") - get("monotonous"))) / k | |
| return p, e | |
| def predict(model, X): | |
| D = X.shape[1] | |
| if str(model.get("kind", "ridge")) == "krr": | |
| Q = ((X - model["mu"]) / model["sd"] / np.sqrt(D)).astype(np.float32) | |
| A = model["A"] | |
| d2 = np.clip((Q ** 2).sum(1)[:, None] + (A ** 2).sum(1)[None, :] - 2 * Q @ A.T, 0, None) | |
| Kq = np.exp(-float(model["gamma"]) * d2) | |
| P = (Kq @ model["alpha"])[:, 2:] * model["t_std"][2:] + model["t_mean"][2:] | |
| if str(model.get("spread_kind", "ridge")) == "krr": # kernel ridge spread on the same kernel | |
| s = np.exp((Kq @ model["s_alpha"]) * model["s_ls"] + model["s_lm"]) * model["t_std"][2:] | |
| return P, P + model["qs_lo"] * s, P + model["qs_hi"] * s | |
| Xs = np.hstack([(X - model["s_mu"]) / model["s_sd"] / np.sqrt(D), np.ones((len(X), 1))]) | |
| else: | |
| Xs = np.hstack([(X - model["mu"]) / model["sd"] / np.sqrt(D), np.ones((len(X), 1))]) | |
| P = (Xs @ model["W"])[:, 2:] * model["t_std"][2:] + model["t_mean"][2:] | |
| s = np.exp(Xs @ model["s_W"]) * model["t_std"][2:] # spread ridge (same features, same training rows) | |
| return P, P + model["qs_lo"] * s, P + model["qs_hi"] * s | |
| def fit_checked(args): | |
| if args.manifest is None or args.cache is None: | |
| raise SystemExit("No fitted model found: pass --model models/final/model_siglip_krr_pe.npz, or --manifest and --cache to fit it.") | |
| return fit(args) | |
| def main(): | |
| args = parse_args() | |
| args.output_dir.mkdir(parents=True, exist_ok=True) | |
| mpath = args.output_dir / ("model_siglip_" + ("krr" if args.krr else "ridge") + "_pe.npz") | |
| if args.model is not None: | |
| mpath = args.model | |
| if mpath.exists() and not args.refit: | |
| with np.load(mpath) as z: | |
| model = {k: z[k] for k in z.files} | |
| print(f"Loaded {mpath} (lambda {float(model['lambda']):g}, {int(model['train_pairs'])} training pairs)") | |
| if "s_W" not in model or (args.krr and str(model.get("spread_kind", "ridge")) != "krr"): | |
| print(" this saved model has an older spread model (before the kernel ridge spread, 2026-11-21): refitting") | |
| model = fit_checked(args) | |
| np.savez(mpath, **model) | |
| else: | |
| model = fit_checked(args) | |
| np.savez(mpath, **model) | |
| from PIL import Image | |
| Image.MAX_IMAGE_PIXELS = None | |
| from extract_backbone_features import Extractor, load_image | |
| exts = {".jpg", ".jpeg", ".png", ".bmp", ".webp"} | |
| paths = [] | |
| for root in args.images: | |
| paths += [root] if root.is_file() else sorted(q for q in root.rglob("*") if q.suffix.lower() in exts) | |
| print(f"{len(paths)} images") | |
| blocks = [] | |
| for name in ["siglip2_giant_384", "pe_core_bigg14_448"]: | |
| print(f"Features: {name}") | |
| extractor = Extractor(name, args.device) | |
| feats, begun = [], time.time() | |
| for i in range(0, len(paths), args.batch_size): | |
| feats.append(extractor([load_image(str(q)) for q in paths[i:i + args.batch_size]])) | |
| if (i // args.batch_size) % 10 == 0: | |
| print(f" {min(i + args.batch_size, len(paths))}/{len(paths)} {(i + args.batch_size) / (time.time() - begun):.1f} img/s", flush=True) | |
| blocks.append(np.concatenate(feats).astype(np.float64)) | |
| del extractor | |
| import torch | |
| if torch.cuda.is_available(): | |
| torch.cuda.empty_cache() | |
| X_new = np.concatenate(blocks, 1) # same order as training: [SigLIP 2, PE] | |
| P, L, U = predict(model, X_new) | |
| out = pd.DataFrame({"image": [str(q) for q in paths], "file": [q.name for q in paths], "folder": [q.parent.name for q in paths]}) | |
| for k, a in enumerate(AQ): | |
| out[f"predicted_{a}"], out[f"lower_{a}"], out[f"upper_{a}"] = P[:, k], L[:, k], U[:, k] | |
| tag = "siglip" | |
| out.to_csv(args.output_dir / f"predictions_{tag}.csv", index=False) | |
| print(f"Wrote {args.output_dir / f'predictions_{tag}.csv'}") | |
| if not args.ratings: | |
| return | |
| results, frames = {}, [] | |
| # Panorama views (<stem>_yawNNN.jpg) are averaged per panorama, as the ratings name the whole panorama. | |
| pano = out.assign(file=[re.sub(r"_yaw\d{3}$", "", Path(f).stem) + Path(f).suffix for f in out.file]) | |
| pano = pano.groupby("file", as_index=False)[[c for c in out.columns if c.startswith(("predicted_", "lower_", "upper_"))]].mean() | |
| for rp in args.ratings: | |
| r = pd.read_csv(rp) | |
| r = r.rename(columns={r.columns[0]: "file"}).rename(columns={c: c.strip().lower() for c in r.columns[1:]}) | |
| cols = ["file"] + [a for a in AQ if a in r.columns] | |
| m = out.merge(r[cols], on="file", how="inner") | |
| if m.empty: | |
| m = pano.merge(r[cols], on="file", how="inner") | |
| if m.empty: | |
| print(f"{rp}: no image matches a rating row; skipped") | |
| continue | |
| m["source"] = rp.stem | |
| frames.append(m) | |
| if not frames: | |
| return | |
| sets = {fr.source.iloc[0]: fr for fr in frames} | |
| if len(frames) > 1: | |
| sets["pooled"] = pd.concat(frames) | |
| print(f"\n{'set':12s} {'n':>5s} " + " ".join(f"{a[:8]:>8s}" for a in AQ) + " mean") | |
| for name, m in sets.items(): | |
| sp = [spearmanr(m[f"predicted_{a}"], m[a]).statistic if a in m else np.nan for a in AQ] | |
| pr = [pearsonr(m[f"predicted_{a}"], m[a]).statistic if a in m else np.nan for a in AQ] | |
| results[name] = {"n": int(len(m)), "spearman": dict(zip(AQ, sp)), "pearson": dict(zip(AQ, pr)), | |
| "mean_spearman": float(np.nanmean(sp)), "mean_pearson": float(np.nanmean(pr))} | |
| print(f"{name:12s} {len(m):5d} " + " ".join(f"{x:8.3f}" for x in sp) + f" {np.nanmean(sp):6.3f} (Spearman)") | |
| print(f"{'':12s} {'':5s} " + " ".join(f"{x:8.3f}" for x in pr) + f" {np.nanmean(pr):6.3f} (Pearson)") | |
| if all(a in m for a in AQ): | |
| hp, he = iso(lambda a: m[a]); mp, me = iso(lambda a: m[f"predicted_{a}"]) | |
| results[name]["iso_spearman"] = {"ISOPleasant": float(spearmanr(mp, hp).statistic), "ISOEventful": float(spearmanr(me, he).statistic)} | |
| print(f"{'':12s} {'':5s} ISO 12913-3 axes: ISOPleasant {results[name]['iso_spearman']['ISOPleasant']:.3f} " | |
| f"ISOEventful {results[name]['iso_spearman']['ISOEventful']:.3f}") | |
| matched = sum(len(fr) for fr in frames) | |
| print(f"({matched} rated images or panoramas scored)") | |
| (args.output_dir / f"evaluation_{tag}.json").write_text(json.dumps(results, indent=2)) | |
| print(f"Wrote {args.output_dir / f'evaluation_{tag}.json'}") | |
| if __name__ == "__main__": | |
| main() | |