#!/usr/bin/env python3 """80% range per photo: fixed width vs photo-dependent width, on the same 10-fold CV as compare_methods.py. Point prediction: --method (final model: ours_krr_siglip_pe with --point krr_rbf). Ranges, all fitted on the training side of each fold only: fixed pred + 10th / 90th percentile of the out-of-fold training residuals (current method; same width for every photo, per AQ) scaled a second ridge on the same features predicts log|residual| per AQ (fitted on out-of-fold training residuals, lambda by grouped CV); the range is pred + s(x) * the 10th / 90th percentile of residual / s(x) on the training side (s also out-of-fold there), so it stays calibrated on average but widens or narrows per photo Baseline "dataset": the 10th-90th percentile of the dataset's own training targets, the same for every photo of that dataset (what a range can say without looking at the photo). Metrics as used in the literature: point accuracy per AQ: Spearman, Pearson, R2 and MAPE (Zhao et al. 2023, CEUS), MSE / RMSE (ARAUS, Ooi et al.), MAE 80% prediction intervals: PICP (coverage), MPIW (mean width), PINAW (MPIW / target range), Winkler score (= interval score; width + 10 x miss distance, lower is better); PICP also at 50% / 90%, per dataset and in terciles of the predicted spread; Spearman(width, |error|). """ 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 contextlib import io import json import sys from pathlib import Path import numpy as np import pandas as pd from scipy.stats import spearmanr sys.path.insert(0, str(Path(__file__).resolve().parent)) from compare_methods import AQ, features_for, training_frame # noqa: E402 from aq_data import ridge_anchor # noqa: E402 ALPHA = 0.2 LEVELS = (0.5, 0.8, 0.9) def parse_args(): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) p.add_argument("--manifest", type=Path, required=True) p.add_argument("--cache", type=Path, required=True) p.add_argument("--folds", type=Path, required=True, help="fold table (e.g. /cv_folds_final_allscored.csv)") 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("--method", default="ours_krr_siglip_pe", help="point model from compare_methods.METHODS") p.add_argument("--point", choices=("ridge", "krr_rbf"), default="ridge", help="point model: ridge (default) or kernel ridge with an RBF kernel (compare_methods ours_krr_rbf_pe); " "the range's training-side residuals then come from a grouped 5-fold kernel-ridge fit") p.add_argument("--krr-widths", type=float, nargs="+", default=[0.5], help="krr_rbf: RBF width grid (0.5 x median squared distance was chosen in every fold of the CV)") p.add_argument("--krr-lambdas", type=float, nargs="+", default=[0.3, 1, 3, 10]) p.add_argument("--obj-weights", type=float, nargs="+", default=[0.0, 0.05, 0.1, 0.2, 0.35], help="krr_rbf_obj methods (e.g. abl_siglip_pe_seg19): grid of the object block's share of the RBF distance") p.add_argument("--device", default="cuda") p.add_argument("--train-exclude-views", type=Path, nargs="*", default=[], help="CSV(s) with a view_id column: these pairs never train (they are still scored)") p.add_argument("--report-exclude-datasets", nargs="*", default=[], help="leave these training_dataset values out of the reported metrics (they still train and are " "predicted), e.g. the new datasets of a combined revision, to report on the original datasets") p.add_argument("--calibrate-on", choices=("train", "all_cosine", "all_cosine_capped"), default="train", help="residuals that set the range quantiles: train = out-of-fold residuals of the training pairs; " "all_cosine = also the training-side pairs with cosine >= the training rule that are left out of " "training (--train-exclude-views; predicted by the fold model, never trained on); " "all_cosine_capped = the same, at most as many left-out pairs per dataset as it has training pairs") p.add_argument("--spread", choices=("ridge", "krr"), default="ridge", help="model of the per-photo spread (log |out-of-fold residual|): linear ridge (final model) or kernel ridge") p.add_argument("--spread-krr-lambdas", type=float, nargs="+", default=[1, 3, 10, 30, 100, 300], help="--spread krr: lambda grid (inner grouped 5-fold CV); the log-residual target is noisy") p.add_argument("--save-predictions", action="store_true", help="write point predictions and ranges per scored pair") p.add_argument("--output-dir", type=Path, required=True) return p.parse_args() def quiet_krr(Xtr, Ytr, groups, Xev, args): """Kernel ridge (RBF): out-of-fold predictions on the training side (grouped 5-fold, each inner fit choosing its own lambda) and a full training-side fit for the evaluation rows. Y is already standardized.""" from sklearn.model_selection import GroupKFold from compare_methods import krr_fit_predict oof = np.zeros_like(Ytr) for a, b in GroupKFold(5).split(Xtr, groups=groups): oof[b] = krr_fit_predict(args.krr_kind, Xtr[a], Ytr[a], groups[a], Xtr[b], args) return oof, krr_fit_predict(args.krr_kind, Xtr, Ytr, groups, Xev, args) def quiet_ridge(X, Y, n, groups, lambdas): test = np.array(["__test__"] * (len(X) - n), dtype=object) with contextlib.redirect_stdout(io.StringIO()): out, _ = ridge_anchor(X, np.vstack([Y, np.zeros((len(X) - n, Y.shape[1]))]), np.arange(n), np.concatenate([groups, test]), lambdas, 5, 42) return out[:n].astype(np.float64), out[n:].astype(np.float64) # out-of-fold on train, full fit on test def main(): args = parse_args() f, Y = training_frame(args) ref = pd.read_csv(args.folds) known = dict(zip(ref.view_id.astype(str), ref.fold.astype(int))) by_group = ref[ref.fold >= 0].drop_duplicates("group").set_index("group").fold.astype(int).to_dict() vid = f.view_id.astype(str) scored = vid.isin(known).to_numpy() fold = np.array([known[v] if v in known else by_group.get(g, -1) for v, g in zip(vid, f.group)]) keys, groups, ds = f.view_path.astype(str).tolist(), f.group.to_numpy(), f.training_dataset.astype(str).to_numpy() trainable = f.trainable.to_numpy() cos_ok = pd.to_numeric(f.image_audio_cosine, errors="coerce").ge(args.min_train_pair_cosine).to_numpy() left_out = cos_ok & ~trainable # trainable by the cosine rule but excluded from training rng = np.random.default_rng(0) folds = sorted(k for k in set(fold) if k >= 0) ev_all = np.flatnonzero(scored & (fold >= 0)) need = np.union1d(ev_all, np.flatnonzero(trainable & ((fold >= 0) | ~scored))) if args.calibrate_on != "train": need = np.union1d(need, np.flatnonzero(left_out & (fold >= 0))) X, kind = features_for(args.method, keys, need) args.krr_kind = "krr_rbf_obj" if kind == "krr_rbf_obj" else "krr_rbf" P = np.full_like(Y, np.nan) methods = ("dataset", "fixed", "scaled") # dataset = no-information baseline (training targets of the dataset) lo = {m: {lev: np.full_like(Y, np.nan) for lev in LEVELS} for m in methods} hi = {m: {lev: np.full_like(Y, np.nan) for lev in LEVELS} for m in methods} spread = np.full_like(Y, np.nan) for k in folds: tr = np.flatnonzero((fold != k) & trainable) ev = np.flatnonzero((fold == k) & scored) cal = np.flatnonzero((fold != k) & (fold >= 0) & left_out) if args.calibrate_on != "train" else np.array([], int) if args.calibrate_on == "all_cosine_capped" and len(cal): keep = [] for d in np.unique(ds[cal]): rows, cap = cal[ds[cal] == d], int((ds[tr] == d).sum()) keep.append(rows if len(rows) <= cap else rng.choice(rows, cap, replace=False)) cal = np.sort(np.concatenate(keep)) n_ev = len(ev) ev_cal = np.concatenate([ev, cal]) mu, sd = Y[tr].mean(0), Y[tr].std(0) + 1e-9 Ys = (Y[tr] - mu) / sd Xk = np.vstack([X[tr], X[ev_cal]]) if args.point == "krr_rbf": oof, pred = quiet_krr(X[tr], Ys, groups[tr], X[ev_cal], args) else: oof, pred = quiet_ridge(Xk, Ys, len(tr), groups[tr], args.lambdas) # identical to compare_methods ridge pred_cal, pred = pred[n_ev:], pred[:n_ev] r = Ys - oof if args.spread == "krr": # nonlinear spread model: kernel ridge (RBF) on log|residual| Lr = np.log(np.abs(r) + 0.05) lm, ls = Lr.mean(0), Lr.std(0) + 1e-9 point_lams, args.krr_lambdas = args.krr_lambdas, args.spread_krr_lambdas s_oof, s_ev = (np.exp(a * ls + lm) for a in quiet_krr(X[tr], (Lr - lm) / ls, groups[tr], X[ev_cal], args)) args.krr_lambdas = point_lams else: z = np.hstack([np.zeros((len(r), 2)), np.log(np.abs(r) + 0.05)]) # ridge_anchor scores lambda on columns 2: s_oof, s_ev = (np.exp(a[:, 2:]) for a in quiet_ridge(Xk, z, len(tr), groups[tr], args.scale_lambdas)) s_cal, s_ev = s_ev[n_ev:], s_ev[:n_ev] u = r / s_oof if len(cal): u = np.vstack([u, ((Y[cal] - mu) / sd - pred_cal) / s_cal]) for lev in LEVELS: qlo, qhi = (1 - lev) / 2, 1 - (1 - lev) / 2 q = np.quantile(r, [qlo, qhi], axis=0) lo["fixed"][lev][ev], hi["fixed"][lev][ev] = (pred + q[0]) * sd + mu, (pred + q[1]) * sd + mu qs = np.quantile(u, [qlo, qhi], axis=0) lo["scaled"][lev][ev], hi["scaled"][lev][ev] = (pred + qs[0] * s_ev) * sd + mu, (pred + qs[1] * s_ev) * sd + mu # baseline: the dataset's own training targets (same range for every photo of that dataset) allq = np.quantile(Y[tr], [qlo, qhi], axis=0) for d in np.unique(ds[ev]): rows, src = ev[ds[ev] == d], Y[tr][ds[tr] == d] bq = np.quantile(src, [qlo, qhi], axis=0) if len(src) >= 30 else allq lo["dataset"][lev][rows], hi["dataset"][lev][rows] = bq[0], bq[1] P[ev], spread[ev] = pred * sd + mu, s_ev print(f"fold {k}: {len(tr)} train, {len(ev)} scored" + (f", {len(cal)} left-out pairs added to calibration" if len(cal) else ""), flush=True) if args.save_predictions: args.output_dir.mkdir(parents=True, exist_ok=True) sv = f.loc[ev_all, ["view_id", "training_dataset", "group"]].copy() for k, a_ in enumerate(AQ): sv[f"target_{a_}"], sv[f"pred_{a_}"] = Y[ev_all, k], P[ev_all, k] sv[f"lo_{a_}"], sv[f"hi_{a_}"] = lo["scaled"][0.8][ev_all, k], hi["scaled"][0.8][ev_all, k] sv.to_csv(args.output_dir / "range_predictions.csv", index=False) i = ev_all[~np.isin(ds[ev_all], args.report_exclude_datasets)] if args.report_exclude_datasets else ev_all if args.report_exclude_datasets: print(f"reporting on {len(i)} of {len(ev_all)} scored pairs (left out: {args.report_exclude_datasets})") y, p = Y[i], P[i] err = np.abs(y - p) terc = np.stack([pd.qcut(spread[i][:, a], 3, labels=False) for a in range(len(AQ))], 1) lev = 0.8 # the main range (must be in LEVELS) target_range = y.max(0) - y.min(0) # per AQ, for PINAW res = {"point": {}, "ranges": {}} # ---- point accuracy, metrics used in the literature (Zhao et al. 2023: R2, MAPE; ARAUS: MSE) ---- for j, a in enumerate(AQ): e = p[:, j] - y[:, j] res["point"][a] = {"spearman": float(spearmanr(p[:, j], y[:, j]).statistic), "pearson": float(np.corrcoef(p[:, j], y[:, j])[0, 1]), "r2": float(1 - np.sum(e ** 2) / np.sum((y[:, j] - y[:, j].mean()) ** 2)), "mse": float(np.mean(e ** 2)), "rmse": float(np.sqrt(np.mean(e ** 2))), "mae": float(np.mean(np.abs(e))), "mape": float(100 * np.mean(np.abs(e) / np.abs(y[:, j]).clip(1e-6)))} # ---- prediction intervals: PICP, MPIW, PINAW, Winkler score (Winkler 1972; Gneiting & Raftery 2007) ---- for m in methods: L, H = lo[m][lev][i], hi[m][lev][i] inside = (y >= L) & (y <= H) width = H - L winkler = width + (2 / (1 - lev)) * (np.clip(L - y, 0, None) + np.clip(y - H, 0, None)) res["ranges"][m] = { "PICP": float(inside.mean()), "MPIW": float(width.mean()), "PINAW": float((width / target_range).mean()), "winkler": float(winkler.mean()), "PICP_by_level": {f"{int(round(l * 100))}%": float(((y >= lo[m][l][i]) & (y <= hi[m][l][i])).mean()) for l in LEVELS}, "PICP_by_spread_tercile": [float(inside[terc == t].mean()) for t in range(3)], "PICP_by_dataset": {d: float(inside[ds[i] == d].mean()) for d in np.unique(ds[i]) if (ds[i] == d).sum() >= 30}, "by_aq": {a: {"PICP": float(inside[:, j].mean()), "MPIW": float(width[:, j].mean()), "PINAW": float(width[:, j].mean() / target_range[j]), "winkler": float(winkler[:, j].mean()), "width_vs_abs_error_spearman": float(spearmanr(width[:, j], err[:, j]).statistic) if width[:, j].std() > 0 else float("nan")} for j, a in enumerate(AQ)}, } args.output_dir.mkdir(parents=True, exist_ok=True) (args.output_dir / "compare_ranges.json").write_text(json.dumps(res, indent=2)) from compare_methods import krr_fit_predict as _k if _k.chosen: # kernel settings picked by every inner fit (point and spread) (args.output_dir / "krr_chosen.json").write_text(json.dumps(_k.chosen, indent=1)) ow = [c["obj_weight"] for c in _k.chosen if "obj_weight" in c] if ow: print("object-block share chosen by the inner CV:", {w: ow.count(w) for w in sorted(set(ow))}) out = f.loc[i, ["view_id", "view_path", "training_dataset", "group"]].copy() for j, a in enumerate(AQ): out[f"pred_{a}"], out[f"target_{a}"] = p[:, j], y[:, j] for m in methods: out[f"{m}_lo_{a}"], out[f"{m}_hi_{a}"] = lo[m][lev][i, j], hi[m][lev][i, j] out.to_csv(args.output_dir / "compare_ranges_predictions.csv", index=False) print(f"\n10-fold CV, {len(i)} scored pairs, point model {args.method}") print(f"\nPoint accuracy per AQ") print(f"{'AQ':11s} {'Spearman':>8s} {'Pearson':>7s} {'R2':>6s} {'MSE':>6s} {'RMSE':>6s} {'MAE':>6s} {'MAPE%':>6s}") for a, r_ in res["point"].items(): print(f"{a:11s} {r_['spearman']:8.3f} {r_['pearson']:7.3f} {r_['r2']:6.3f} {r_['mse']:6.3f} {r_['rmse']:6.3f} " f"{r_['mae']:6.3f} {r_['mape']:6.1f}") mean = {k: np.mean([r_[k] for r_ in res["point"].values()]) for k in ("spearman", "pearson", "r2", "mse", "rmse", "mae", "mape")} print(f"{'mean':11s} {mean['spearman']:8.3f} {mean['pearson']:7.3f} {mean['r2']:6.3f} {mean['mse']:6.3f} {mean['rmse']:6.3f} " f"{mean['mae']:6.3f} {mean['mape']:6.1f}") print(f"\n80% prediction intervals (PICP target 0.80; MPIW in AQ points; PINAW = MPIW / target range; Winkler: lower is better)") print(" dataset = no-information reference: the 10th-90th percentile of the dataset's training targets") print(f"{'interval':8s} {'PICP':>6s} {'MPIW':>6s} {'PINAW':>6s} {'Winkler':>7s} PICP at 50/80/90% PICP easy/mid/hard PICP datasets") for m, r_ in res["ranges"].items(): dc = list(r_["PICP_by_dataset"].values()) print(f"{m:8s} {r_['PICP']:6.3f} {r_['MPIW']:6.3f} {r_['PINAW']:6.3f} {r_['winkler']:7.3f} " + " / ".join(f"{v:.2f}" for v in r_["PICP_by_level"].values()) + " " + " / ".join(f"{c:.2f}" for c in r_["PICP_by_spread_tercile"]) + f" {min(dc):.2f}-{max(dc):.2f}") print(f"\n{'AQ':11s} " + " | ".join(f"{m}: PICP MPIW PINAW Winkler" for m in ("scaled", "fixed", "dataset"))) for a in AQ: print(f"{a:11s} " + " | ".join( f"{res['ranges'][m]['by_aq'][a]['PICP']:.3f} {res['ranges'][m]['by_aq'][a]['MPIW']:.3f} " f"{res['ranges'][m]['by_aq'][a]['PINAW']:.3f} {res['ranges'][m]['by_aq'][a]['winkler']:.3f}" for m in ("scaled", "fixed", "dataset"))) print(f"\nWrote {args.output_dir / 'compare_ranges.json'}") if __name__ == "__main__": main()