831 lines
36 KiB
Python
831 lines
36 KiB
Python
#!/usr/bin/env python3
|
||
# -*- coding: utf-8 -*-
|
||
"""
|
||
Filename: pipeline_fusion.py
|
||
Author: Andre Neto
|
||
Last Modified: Sun Aug 31 2025
|
||
|
||
Purpose
|
||
Fuse FR-IQA metrics into a regressor that predicts MOS. Supports biased and
|
||
unbias MOS tracks, Optuna tuning, k selection, and pseudo-MOS generation.
|
||
|
||
Key features
|
||
- Handles label type via --label-type: biased or unbias.
|
||
Accepts either:
|
||
a) one CSV with columns ["file_name", "mos"] for biased and/or
|
||
["file_name", "mos_unbias"] for unbias, or
|
||
b) two files passed with --mos-train and --mos-train-unbias.
|
||
- Auto-scales labels to 0–100 if they look like 0–1.
|
||
- Computes FR-metric ranking by PLCC and SRCC; saves ranking.csv.
|
||
- Suggests k using SVD cumulative variance + Picard criterion; saves plots.
|
||
- Per-k training with Optuna; saves per-model trials, scores, predictions,
|
||
SHAP plots, and pickled models. Writes per-k model_leaderboard.csv.
|
||
- Pseudo-MOS inference for distorted set from best model or a chosen folder.
|
||
- Clean directory layout split by label type:
|
||
<out>/<label_type>/
|
||
ranking.csv
|
||
analysis/{variance.pdf,picard.pdf,svd_energy.csv}
|
||
k{K}/
|
||
scaler.pkl
|
||
x_scaled.csv
|
||
model_leaderboard.csv
|
||
<model_name>/
|
||
optuna_study.db
|
||
optuna_trials.csv
|
||
param_importance.json
|
||
predictions.csv
|
||
scores.csv
|
||
model.pkl
|
||
top_k_metrics.txt
|
||
shap_summary.png
|
||
pseudo_mos.csv
|
||
debug_features_head.csv
|
||
|
||
Minimal deps
|
||
pip install numpy pandas scikit-learn scipy matplotlib shap optuna joblib
|
||
pip install xgboost lightgbm catboost
|
||
|
||
Examples
|
||
|
||
# Compute suggested k using biased labels
|
||
python scripts/pipeline_fusion.py compute-k \
|
||
--iqa-train data/labeled/train/iqa.csv \
|
||
--mos-train data/labeled/train/mos.csv \
|
||
--iqa-distorted data/distorted/iqa.csv \
|
||
--out results/pipeline_fusion --label-type unbias
|
||
|
||
# Tune models for k=6 using unbias labels in a single CSV
|
||
python scripts/pipeline_fusion.py best-models --k 6 \
|
||
--iqa-train data/labeled/train/iqa.csv \
|
||
--mos-train data/labeled/train/mos_debiased.csv \
|
||
--iqa-distorted data/distorted/iqa.csv \
|
||
--out results/pipeline_fusion --label-type unbias --n-trials 100
|
||
|
||
# Generate pseudo-MOS for distorted set from the top model
|
||
python scripts/pipeline_fusion.py pseudo-mos --k 6 \
|
||
--iqa-train data/labeled/train/iqa.csv \
|
||
--mos-train data/labeled/train/mos_debiased.csv \
|
||
--iqa-distorted data/distorted/iqa.csv \
|
||
--out results/pipeline_fusion --label-type unbias
|
||
|
||
# End-to-end run with Optuna for biased labels
|
||
python scripts/pipeline_fusion.py all \
|
||
--iqa-train data/labeled/train/iqa.csv \
|
||
--mos-train data/labeled/train/mos.csv \
|
||
--iqa-distorted data/distorted/iqa.csv \
|
||
--out results/pipeline_fusion --label-type biased \
|
||
--threshold 0.95 --n-trials 150
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import json
|
||
import multiprocessing as mp
|
||
from pathlib import Path
|
||
import sys
|
||
import warnings
|
||
|
||
import joblib
|
||
import numpy as np
|
||
import pandas as pd
|
||
|
||
import matplotlib
|
||
matplotlib.use("Agg")
|
||
import matplotlib.pyplot as plt
|
||
import shap
|
||
|
||
from scipy.linalg import svd
|
||
from scipy.stats import pearsonr, spearmanr
|
||
|
||
from sklearn.base import clone
|
||
from sklearn.ensemble import (
|
||
RandomForestRegressor, GradientBoostingRegressor,
|
||
ExtraTreesRegressor, HistGradientBoostingRegressor
|
||
)
|
||
from sklearn.linear_model import Ridge, LinearRegression, ElasticNet, BayesianRidge
|
||
from sklearn.metrics import mean_absolute_error, mean_squared_error
|
||
from sklearn.model_selection import KFold
|
||
from sklearn.preprocessing import StandardScaler
|
||
from sklearn.svm import SVR
|
||
|
||
from xgboost import XGBRegressor
|
||
from lightgbm import LGBMRegressor
|
||
from catboost import CatBoostRegressor
|
||
|
||
import optuna
|
||
from optuna.samplers import TPESampler
|
||
from optuna.pruners import SuccessiveHalvingPruner
|
||
|
||
mp.set_start_method("spawn", force=True)
|
||
|
||
# ----------------------- Utils -----------------------
|
||
|
||
def ensure_dir(p: Path): p.mkdir(parents=True, exist_ok=True)
|
||
|
||
def autoscale_0_1_to_0_100(series: pd.Series) -> pd.Series:
|
||
vmin, vmax = float(series.min()), float(series.max())
|
||
if 0.0 <= vmin <= vmax <= 1.5:
|
||
return series.astype(float) * 100.0
|
||
return series.astype(float)
|
||
|
||
def plcc_srcc(y_true: np.ndarray, y_pred: np.ndarray) -> tuple[float,float]:
|
||
with warnings.catch_warnings():
|
||
warnings.simplefilter("ignore")
|
||
plcc = pearsonr(y_true, y_pred)[0]
|
||
srcc = spearmanr(y_true, y_pred)[0]
|
||
if not np.isfinite(plcc): plcc = 0.0
|
||
if not np.isfinite(srcc): srcc = 0.0
|
||
return float(plcc), float(srcc)
|
||
|
||
# ----------------------- Data loader -----------------------
|
||
|
||
def read_iqa(iqa_csv: Path) -> pd.DataFrame:
|
||
df = pd.read_csv(iqa_csv)
|
||
if "file_name" not in df.columns:
|
||
raise ValueError("IQA CSV must have a 'file_name' column")
|
||
return df
|
||
|
||
def read_mos(mos_csv_biased: Path | None,
|
||
mos_csv_unbias: Path | None,
|
||
label_type: str) -> pd.DataFrame:
|
||
"""
|
||
Accepts either:
|
||
- one CSV in mos_csv_biased with columns:
|
||
file_name + one or both of {mos, mos_unbias}
|
||
- or two CSVs: mos_csv_biased and mos_csv_unbias with column {file_name, mos}
|
||
Returns df with 'file_name' and 'mos' according to label_type.
|
||
"""
|
||
if mos_csv_biased is None and mos_csv_unbias is None:
|
||
raise ValueError("Provide --mos-train and/or --mos-train-unbias")
|
||
|
||
if mos_csv_unbias is None:
|
||
df = pd.read_csv(mos_csv_biased)
|
||
if "file_name" not in df.columns:
|
||
raise ValueError("MOS CSV must have 'file_name'")
|
||
# pick column by label type
|
||
candidates = ["mos_unbias","unbias_mos","mos_u","mos_unbiased"] if label_type == "unbias" else ["mos_biased","mos"]
|
||
col = next((c for c in candidates if c in df.columns), None)
|
||
if col is None:
|
||
raise ValueError(f"Could not find label column for {label_type}. "
|
||
f"Expected one of {candidates} in {mos_csv_biased}")
|
||
out = df[["file_name", col]].rename(columns={col: "mos"}).copy()
|
||
out["mos"] = autoscale_0_1_to_0_100(out["mos"])
|
||
return out
|
||
|
||
# two separate files
|
||
if label_type == "biased":
|
||
df = pd.read_csv(mos_csv_biased)
|
||
if not {"file_name","mos"} <= set(df.columns):
|
||
raise ValueError("Biased MOS CSV must have columns: file_name, mos")
|
||
df = df[["file_name","mos"]].copy()
|
||
df["mos"] = autoscale_0_1_to_0_100(df["mos"])
|
||
return df
|
||
else:
|
||
df = pd.read_csv(mos_csv_unbias)
|
||
if "file_name" not in df.columns:
|
||
raise ValueError("unbias MOS CSV must include 'file_name'")
|
||
col = next((c for c in ["mos_unbias","unbias_mos","mos"] if c in df.columns), None)
|
||
if col is None:
|
||
raise ValueError("unbias MOS CSV must have one of: mos_unbias, unbias_mos, mos")
|
||
df = df[["file_name", col]].rename(columns={col: "mos"}).copy()
|
||
df["mos"] = autoscale_0_1_to_0_100(df["mos"])
|
||
return df
|
||
|
||
# ----------------------- Fusion class -----------------------
|
||
|
||
class FusionRegressor:
|
||
"""
|
||
Fuse FR-IQA metrics using supervised regressors.
|
||
Supports biased or unbias MOS via label_type.
|
||
"""
|
||
|
||
def __init__(self,
|
||
iqa_train_csv: str,
|
||
mos_train_csv: str | None,
|
||
mos_train_unbias_csv: str | None,
|
||
iqa_distorted_csv: str,
|
||
output_dir: str,
|
||
label_type: str = "biased",
|
||
seed: int = 42):
|
||
self.iqa_train_csv = Path(iqa_train_csv)
|
||
self.mos_train_csv = Path(mos_train_csv) if mos_train_csv else None
|
||
self.mos_train_unbias_csv = Path(mos_train_unbias_csv) if mos_train_unbias_csv else None
|
||
self.iqa_distorted_csv = Path(iqa_distorted_csv)
|
||
self.output_dir_root = Path(output_dir)
|
||
self.label_type = label_type # "biased" or "unbias"
|
||
self.seed = seed
|
||
|
||
# Resolved output dir includes label type
|
||
self.output_dir = self.output_dir_root / self.label_type
|
||
|
||
self.train_df: pd.DataFrame | None = None
|
||
self.distorted_df: pd.DataFrame | None = None
|
||
self.ranking_df: pd.DataFrame | None = None
|
||
self.total_k: int | None = None
|
||
self.best_model_info = {}
|
||
|
||
# Base model zoo
|
||
self.model_defs = {
|
||
"Linear": LinearRegression(),
|
||
"Ridge": Ridge(alpha=1.0),
|
||
"ElasticNet": ElasticNet(alpha=1.0, l1_ratio=0.5, max_iter=5000),
|
||
"BayesianRidge": BayesianRidge(),
|
||
|
||
"SVR": SVR(kernel="rbf", C=1.0, gamma="scale"),
|
||
|
||
"RandomForest": RandomForestRegressor(n_estimators=200, random_state=self.seed, n_jobs=-1),
|
||
"ExtraTrees": ExtraTreesRegressor(n_estimators=200, random_state=self.seed, n_jobs=-1),
|
||
"GradientBoosting": GradientBoostingRegressor(n_estimators=200, learning_rate=0.05, random_state=self.seed),
|
||
"HistGradientBoosting": HistGradientBoostingRegressor(max_iter=200, random_state=self.seed),
|
||
|
||
"XGBoost": XGBRegressor(n_estimators=300, learning_rate=0.05, random_state=self.seed, verbosity=0, use_label_encoder=False, n_jobs=-1),
|
||
"LightGBM": LGBMRegressor(n_estimators=300, learning_rate=0.05, random_state=self.seed, verbosity=-1, n_jobs=-1),
|
||
"CatBoost": CatBoostRegressor(iterations=500, learning_rate=0.05, verbose=0, random_state=self.seed)
|
||
}
|
||
|
||
# Optuna search spaces
|
||
self.optuna_spaces = {
|
||
"Linear": lambda tr: {},
|
||
"Ridge": lambda tr: {"alpha": tr.suggest_float("alpha", 1e-3, 1e3, log=True)},
|
||
"ElasticNet": lambda tr: {
|
||
"alpha": tr.suggest_float("alpha", 1e-3, 1e1, log=True),
|
||
"l1_ratio": tr.suggest_float("l1_ratio", 0.05, 0.95),
|
||
"max_iter": 5000
|
||
},
|
||
"BayesianRidge": lambda tr: {
|
||
"alpha_1": tr.suggest_float("alpha_1", 1e-7, 1e-3, log=True),
|
||
"alpha_2": tr.suggest_float("alpha_2", 1e-7, 1e-3, log=True),
|
||
"lambda_1": tr.suggest_float("lambda_1", 1e-7, 1e-3, log=True),
|
||
"lambda_2": tr.suggest_float("lambda_2", 1e-7, 1e-3, log=True)
|
||
},
|
||
"SVR": lambda tr: {
|
||
"C": tr.suggest_float("C", 1e-2, 1e3, log=True),
|
||
"gamma": tr.suggest_categorical("gamma", ["scale", "auto"]),
|
||
"epsilon": tr.suggest_float("epsilon", 1e-3, 1.0, log=True),
|
||
"kernel": "rbf"
|
||
},
|
||
"RandomForest": lambda tr: {
|
||
"n_estimators": tr.suggest_int("n_estimators", 100, 800, step=50),
|
||
"max_depth": tr.suggest_categorical("max_depth", [None, 8, 12, 16, 20, 30]),
|
||
"min_samples_split": tr.suggest_int("min_samples_split", 2, 10),
|
||
"min_samples_leaf": tr.suggest_int("min_samples_leaf", 1, 4),
|
||
"random_state": self.seed,
|
||
"n_jobs": -1
|
||
},
|
||
"ExtraTrees": lambda tr: {
|
||
"n_estimators": tr.suggest_int("n_estimators", 100, 800, step=50),
|
||
"max_depth": tr.suggest_categorical("max_depth", [None, 8, 12, 16, 20, 30]),
|
||
"min_samples_split": tr.suggest_int("min_samples_split", 2, 10),
|
||
"min_samples_leaf": tr.suggest_int("min_samples_leaf", 1, 4),
|
||
"random_state": self.seed,
|
||
"n_jobs": -1
|
||
},
|
||
"GradientBoosting": lambda tr: {
|
||
"n_estimators": tr.suggest_int("n_estimators", 100, 800, step=50),
|
||
"learning_rate": tr.suggest_float("learning_rate", 1e-3, 0.2, log=True),
|
||
"max_depth": tr.suggest_int("max_depth", 2, 6),
|
||
"subsample": tr.suggest_float("subsample", 0.6, 1.0),
|
||
"loss": tr.suggest_categorical("loss", ["squared_error", "absolute_error", "huber"])
|
||
},
|
||
"HistGradientBoosting": lambda tr: {
|
||
"max_iter": tr.suggest_int("max_iter", 100, 800, step=50),
|
||
"learning_rate": tr.suggest_float("learning_rate", 1e-3, 0.2, log=True),
|
||
"max_depth": tr.suggest_categorical("max_depth", [None, 6, 10]),
|
||
"l2_regularization": tr.suggest_float("l2_regularization", 1e-6, 1.0, log=True)
|
||
},
|
||
"XGBoost": lambda tr: {
|
||
"n_estimators": tr.suggest_int("n_estimators", 100, 1200, step=50),
|
||
"learning_rate": tr.suggest_float("learning_rate", 1e-3, 0.3, log=True),
|
||
"max_depth": tr.suggest_int("max_depth", 2, 12),
|
||
"subsample": tr.suggest_float("subsample", 0.5, 1.0),
|
||
"colsample_bytree": tr.suggest_float("colsample_bytree", 0.5, 1.0),
|
||
"reg_alpha": tr.suggest_float("reg_alpha", 1e-9, 1.0, log=True),
|
||
"reg_lambda": tr.suggest_float("reg_lambda", 1e-9, 1.0, log=True),
|
||
"random_state": self.seed,
|
||
"verbosity": 0,
|
||
"use_label_encoder": False,
|
||
"n_jobs": -1
|
||
},
|
||
"LightGBM": lambda tr: {
|
||
"n_estimators": tr.suggest_int("n_estimators", 100, 1200, step=50),
|
||
"learning_rate": tr.suggest_float("learning_rate", 1e-3, 0.3, log=True),
|
||
"num_leaves": tr.suggest_int("num_leaves", 15, 255),
|
||
"min_child_samples": tr.suggest_int("min_child_samples", 5, 80),
|
||
"subsample": tr.suggest_float("subsample", 0.6, 1.0),
|
||
"colsample_bytree": tr.suggest_float("colsample_bytree", 0.6, 1.0),
|
||
"random_state": self.seed,
|
||
"verbosity": -1,
|
||
"n_jobs": -1
|
||
},
|
||
"CatBoost": lambda tr: {
|
||
"iterations": tr.suggest_int("iterations", 200, 3000, step=100),
|
||
"learning_rate": tr.suggest_float("learning_rate", 1e-3, 0.3, log=True),
|
||
"depth": tr.suggest_int("depth", 4, 10),
|
||
"l2_leaf_reg": tr.suggest_float("l2_leaf_reg", 1.0, 10.0),
|
||
"random_state": self.seed,
|
||
"verbose": 0
|
||
}
|
||
}
|
||
|
||
# ------------ IO + ranking ------------
|
||
|
||
def load(self):
|
||
print(f"[load] IQA: {self.iqa_train_csv}")
|
||
iqa_df = read_iqa(self.iqa_train_csv)
|
||
|
||
print(f"[load] MOS ({self.label_type}) from: "
|
||
f"{self.mos_train_csv or self.iqa_train_csv} "
|
||
f"{'(with mos_unbias column)' if self.mos_train_unbias_csv is None else ''}")
|
||
mos_df = read_mos(self.mos_train_csv, self.mos_train_unbias_csv, self.label_type)
|
||
|
||
print("[load] merge on file_name")
|
||
self.train_df = iqa_df.merge(mos_df, on="file_name", how="inner")
|
||
|
||
print(f"[load] distorted IQA: {self.iqa_distorted_csv}")
|
||
self.distorted_df = read_iqa(self.iqa_distorted_csv)
|
||
|
||
print(f"[load] train samples: {self.train_df.shape[0]} | distorted samples: {self.distorted_df.shape[0]}")
|
||
|
||
self.compute_fr_ranking()
|
||
self.total_k = len(self.ranking_df)
|
||
|
||
def compute_fr_ranking(self):
|
||
print("[rank] computing PLCC+SRCC per metric")
|
||
|
||
feats = self.train_df.drop(columns=["file_name","mos"])
|
||
y = self.train_df["mos"].values.astype(float)
|
||
|
||
rows = []
|
||
for col in feats.columns:
|
||
x = feats[col].values
|
||
p, s = plcc_srcc(y, x)
|
||
rows.append((col, p, s, 0.5*(p+s)))
|
||
df = pd.DataFrame(rows, columns=["metric","PLCC","SRCC","Score"])
|
||
df = df.sort_values(["Score","PLCC","SRCC","metric"], ascending=[False,False,False,True], kind="mergesort")
|
||
|
||
ensure_dir(self.output_dir)
|
||
df[["metric","Score","PLCC","SRCC"]].to_csv(self.output_dir/"ranking.csv", index=False)
|
||
self.ranking_df = df.set_index("metric")[["Score","PLCC","SRCC"]]
|
||
print(f"[rank] saved → {self.output_dir/'ranking.csv'}")
|
||
|
||
# ------------ feature prep ------------
|
||
|
||
def select_top_k_features(self, k: int) -> tuple[pd.DataFrame, np.ndarray, list[str]]:
|
||
if self.ranking_df is None or self.train_df is None:
|
||
raise RuntimeError("Call .load() first")
|
||
if k > len(self.ranking_df):
|
||
raise ValueError(f"k={k} > available metrics={len(self.ranking_df)}")
|
||
|
||
top_k = list(self.ranking_df.head(k).index)
|
||
print(f"[top-k] using k={k} metrics")
|
||
for i,n in enumerate(top_k,1): print(f" {i:>2}. {n}")
|
||
|
||
X = self.train_df[top_k].copy()
|
||
y = self.train_df["mos"].values.astype(float)
|
||
|
||
k_dir = self.output_dir/f"k{k}"
|
||
ensure_dir(k_dir)
|
||
with open(k_dir/"top_k_metrics.txt","w",encoding="utf-8") as f:
|
||
for n in top_k: f.write(n+"\n")
|
||
|
||
print(f"[top-k] list → {k_dir/'top_k_metrics.txt'}")
|
||
return X, y, top_k
|
||
|
||
def normalize_features(self, X: pd.DataFrame, k: int) -> tuple[pd.DataFrame, StandardScaler]:
|
||
print("[scale] StandardScaler fit")
|
||
scaler = StandardScaler()
|
||
Xs = pd.DataFrame(scaler.fit_transform(X), columns=X.columns, index=X.index)
|
||
|
||
k_dir = self.output_dir/f"k{k}"
|
||
ensure_dir(k_dir)
|
||
joblib.dump(scaler, k_dir/"scaler.pkl")
|
||
Xs.to_csv(k_dir/"x_scaled.csv", index=False)
|
||
print(f"[scale] scaler → {k_dir/'scaler.pkl'} | x_scaled → {k_dir/'x_scaled.csv'}")
|
||
return Xs, scaler
|
||
|
||
# ------------ evaluation ------------
|
||
|
||
def _cv_score(self, est, X: pd.DataFrame, y: np.ndarray, n_splits=5):
|
||
kf = KFold(n_splits=n_splits, shuffle=True, random_state=self.seed)
|
||
y_pred = np.zeros_like(y, dtype=float)
|
||
|
||
for tr, te in kf.split(X, y):
|
||
m = clone(est)
|
||
m.fit(X.iloc[tr], y[tr])
|
||
y_pred[te] = m.predict(X.iloc[te])
|
||
|
||
p, s = plcc_srcc(y, y_pred)
|
||
mse = mean_squared_error(y, y_pred)
|
||
mae = mean_absolute_error(y, y_pred)
|
||
return 0.5*(p+s), {"PLCC":p,"SRCC":s,"MSE":mse,"MAE":mae}, y_pred
|
||
|
||
def _fit_predict_one_fold(self, name, est_fold, Xtr, ytr, Xte, yte, early_rounds=100):
|
||
if name == "XGBoost":
|
||
est_fold.fit(Xtr, ytr, eval_set=[(Xte,yte)], verbose=False, early_stopping_rounds=early_rounds)
|
||
return est_fold.predict(Xte, ntree_limit=getattr(est_fold,"best_ntree_limit",None))
|
||
if name == "LightGBM":
|
||
try:
|
||
est_fold.fit(Xtr, ytr, eval_set=[(Xte,yte)], eval_metric="l2", verbose=-1)
|
||
return est_fold.predict(Xte, num_iteration=getattr(est_fold,"best_iteration_",None))
|
||
except Exception:
|
||
est_fold.fit(Xtr, ytr); return est_fold.predict(Xte)
|
||
if name == "CatBoost":
|
||
try:
|
||
est_fold.fit(Xtr, ytr, eval_set=(Xte,yte), use_best_model=True, verbose=False)
|
||
return est_fold.predict(Xte)
|
||
except Exception:
|
||
est_fold.fit(Xtr, ytr); return est_fold.predict(Xte)
|
||
est_fold.fit(Xtr, ytr)
|
||
return est_fold.predict(Xte)
|
||
|
||
def _optimize_with_optuna(self, model_name, base_model, X, y, model_dir, n_trials=150, timeout=None, n_splits=5):
|
||
space = self.optuna_spaces.get(model_name)
|
||
if space is None:
|
||
est = clone(base_model)
|
||
score, metrics, y_pred = self._cv_score(est, X, y, n_splits=n_splits)
|
||
est.fit(X, y)
|
||
return est, {}, metrics, y_pred, score
|
||
|
||
sampler = TPESampler(seed=self.seed, multivariate=True, group=True, n_startup_trials=30)
|
||
pruner = SuccessiveHalvingPruner(reduction_factor=2)
|
||
|
||
def objective(trial):
|
||
params = space(trial)
|
||
est = clone(base_model).set_params(**params)
|
||
|
||
kf = KFold(n_splits=n_splits, shuffle=True, random_state=self.seed)
|
||
y_pred = np.zeros_like(y, dtype=float)
|
||
filled = np.zeros_like(y, dtype=bool)
|
||
|
||
for i, (tr, te) in enumerate(kf.split(X, y), 1):
|
||
yp = self._fit_predict_one_fold(model_name, clone(est), X.iloc[tr], y[tr], X.iloc[te], y[te], early_rounds=100)
|
||
y_pred[te] = yp
|
||
filled[te] = True
|
||
p, s = plcc_srcc(y[filled], y_pred[filled])
|
||
trial.report(0.5*(p+s), step=i)
|
||
if trial.should_prune():
|
||
raise optuna.TrialPruned()
|
||
|
||
p, s = plcc_srcc(y, y_pred)
|
||
return 0.5*(p+s)
|
||
|
||
ensure_dir(model_dir)
|
||
storage = f"sqlite:///{model_dir/'optuna_study.db'}"
|
||
study = optuna.create_study(direction="maximize", study_name=f"{model_name}_kfold",
|
||
storage=storage, load_if_exists=True, sampler=sampler, pruner=pruner)
|
||
study.optimize(objective, n_trials=n_trials, timeout=timeout, show_progress_bar=False, gc_after_trial=True)
|
||
|
||
# persist trials
|
||
try:
|
||
study.trials_dataframe().to_csv(model_dir/"optuna_trials.csv", index=False)
|
||
try:
|
||
imps = optuna.importance.get_param_importances(study)
|
||
with open(model_dir/"param_importance.json","w",encoding="utf-8") as f:
|
||
json.dump({k: float(v) for k,v in imps.items()}, f, indent=2)
|
||
except Exception:
|
||
pass
|
||
except Exception:
|
||
pass
|
||
|
||
best_params = study.best_trial.params
|
||
est = clone(base_model).set_params(**best_params)
|
||
score, metrics, y_pred = self._cv_score(est, X, y, n_splits=n_splits)
|
||
est.fit(X, y)
|
||
|
||
pd.DataFrame([{"combined":score, **metrics, **best_params}]).to_csv(model_dir/"optuna_best.csv", index=False)
|
||
return est, best_params, metrics, y_pred, score
|
||
|
||
def compute_best_models(self, X_scaled, y, k, top_k, n_trials=150, timeout=None, n_splits=5, use_optuna=True):
|
||
print(f"[models] tuning on k={k} features for label_type={self.label_type}")
|
||
|
||
trials_map = {
|
||
"Linear": 100, "Ridge": 150, "ElasticNet": 150, "BayesianRidge": 100,
|
||
"SVR": 300, "RandomForest": 300, "ExtraTrees": 300,
|
||
"GradientBoosting": 300, "HistGradientBoosting": 300,
|
||
"XGBoost": 600, "LightGBM": 600, "CatBoost": 600
|
||
}
|
||
|
||
best_score = -np.inf
|
||
leaderboard_rows = []
|
||
|
||
for name, base in self.model_defs.items():
|
||
print(f"- {name}")
|
||
mdir = self.output_dir/f"k{k}"/name.lower()
|
||
ensure_dir(mdir)
|
||
|
||
try:
|
||
if use_optuna:
|
||
trials = trials_map.get(name, n_trials)
|
||
model, params, metrics, y_pred, comb = self._optimize_with_optuna(
|
||
name, base, X_scaled, y, mdir, n_trials=trials, timeout=timeout, n_splits=n_splits)
|
||
else:
|
||
model = clone(base)
|
||
comb, metrics, y_pred = self._cv_score(model, X_scaled, y, n_splits=n_splits)
|
||
model.fit(X_scaled, y)
|
||
params = {}
|
||
|
||
p, s, mse, mae = metrics["PLCC"], metrics["SRCC"], metrics["MSE"], metrics["MAE"]
|
||
print(f" PLCC={p:.4f} SRCC={s:.4f} MSE={mse:.4f} MAE={mae:.4f}")
|
||
|
||
# artifacts
|
||
pd.DataFrame({"true":y, "pred":y_pred}).to_csv(mdir/"predictions.csv", index=False)
|
||
row = {"model":name, "k":k, "PLCC":p, "SRCC":s, "MSE":mse, "MAE":mae, "combined":comb,
|
||
"params": json.dumps(params, ensure_ascii=False) if params else "{}", "model_dir": str(mdir)}
|
||
pd.DataFrame([row]).to_csv(mdir/"scores.csv", index=False)
|
||
joblib.dump(model, mdir/"model.pkl")
|
||
with open(mdir/"top_k_metrics.txt","w",encoding="utf-8") as f:
|
||
for m in top_k: f.write(m+"\n")
|
||
|
||
# SHAP
|
||
if name.lower() in ["randomforest","extratrees","gradientboosting","histgradientboosting","xgboost","lightgbm","catboost"]:
|
||
try:
|
||
explainer = shap.Explainer(model, X_scaled)
|
||
sv = explainer(X_scaled)
|
||
shap.summary_plot(sv, features=X_scaled, feature_names=top_k, show=False)
|
||
plt.tight_layout(); plt.savefig(mdir/"shap_summary.png", dpi=300); plt.close()
|
||
except Exception as e:
|
||
print(f" [warn] SHAP failed: {e}")
|
||
|
||
leaderboard_rows.append(row)
|
||
if comb > best_score:
|
||
best_score = comb
|
||
self.best_model_info = {"model_name":name, "model":model, "top_k":top_k, "k":k, "score":comb}
|
||
|
||
except optuna.exceptions.OptunaError as e:
|
||
print(f" [error] Optuna: {e}")
|
||
except Exception as e:
|
||
print(f" [error] {name}: {e}")
|
||
|
||
# per-k leaderboard
|
||
k_dir = self.output_dir/f"k{k}"
|
||
if leaderboard_rows:
|
||
df = pd.DataFrame(leaderboard_rows).sort_values("combined", ascending=False)
|
||
df.to_csv(k_dir/"model_leaderboard.csv", index=False)
|
||
print(f"[models] leaderboard → {k_dir/'model_leaderboard.csv'}")
|
||
|
||
# ------------ inference ------------
|
||
|
||
@staticmethod
|
||
def _verify_and_align_features(model, X_scaled: pd.DataFrame, scaler: StandardScaler) -> pd.DataFrame:
|
||
if hasattr(scaler, "n_features_in_"):
|
||
exp = int(getattr(scaler, "n_features_in_"))
|
||
if X_scaled.shape[1] != exp:
|
||
raise ValueError(f"Scaler expects {exp} features but got {X_scaled.shape[1]}")
|
||
|
||
expected = None
|
||
if hasattr(model, "feature_names_in_"):
|
||
try:
|
||
fin = list(getattr(model, "feature_names_in_"))
|
||
if len(fin) > 0:
|
||
expected = fin
|
||
except Exception:
|
||
pass
|
||
if expected is None and model.__class__.__name__.lower() == "catboostregressor":
|
||
names = getattr(model, "feature_names_", None)
|
||
if names and len(names) > 0:
|
||
expected = list(names)
|
||
|
||
if expected is not None:
|
||
got = list(X_scaled.columns)
|
||
if set(expected) != set(got):
|
||
missing = [c for c in expected if c not in got]
|
||
extra = [c for c in got if c not in expected]
|
||
raise ValueError(f"Feature name mismatch. Missing={missing} Extra={extra}")
|
||
if got != expected:
|
||
X_scaled = X_scaled[expected]
|
||
elif hasattr(model, "n_features_in_"):
|
||
try:
|
||
nfi = int(getattr(model, "n_features_in_"))
|
||
if nfi > 0 and nfi != X_scaled.shape[1]:
|
||
raise ValueError(f"Model expects {nfi} features but got {X_scaled.shape[1]}")
|
||
except Exception:
|
||
pass
|
||
return X_scaled
|
||
|
||
def predict_on_distorted(self, scaler: StandardScaler):
|
||
if not self.best_model_info:
|
||
raise RuntimeError("No best model in memory. Train first or use predict_on_distorted_from_disk.")
|
||
|
||
model = self.best_model_info["model"]
|
||
top_k = list(self.best_model_info["top_k"])
|
||
k = int(self.best_model_info["k"])
|
||
|
||
missing = [m for m in top_k if m not in self.distorted_df.columns]
|
||
if missing:
|
||
raise ValueError(f"Missing metrics in distorted CSV: {missing}")
|
||
|
||
X = self.distorted_df[top_k].apply(pd.to_numeric, errors="coerce")
|
||
if X.isnull().any().any():
|
||
bad = X.columns[X.isnull().any()].tolist()
|
||
raise ValueError(f"Non numeric values in distorted metrics: {bad}")
|
||
|
||
const_cols = [c for c in top_k if X[c].nunique(dropna=False) <= 1]
|
||
if len(const_cols) == len(top_k):
|
||
raise ValueError("All selected metrics are constant in distorted CSV")
|
||
if const_cols:
|
||
print(f"[warn] constant metrics: {const_cols}")
|
||
|
||
X_scaled = pd.DataFrame(scaler.transform(X), columns=top_k, index=X.index)
|
||
X_scaled = self._verify_and_align_features(model, X_scaled, scaler)
|
||
|
||
preds = model.predict(X_scaled)
|
||
|
||
k_dir = self.output_dir/f"k{k}"
|
||
ensure_dir(k_dir)
|
||
X.iloc[:20].to_csv(k_dir/"debug_features_head.csv", index=False)
|
||
out_csv = k_dir/"pseudo_mos.csv"
|
||
self.distorted_df[["file_name"]].assign(pseudo_mos=preds).to_csv(out_csv, index=False)
|
||
print(f"[predict] pseudo-MOS → {out_csv}")
|
||
|
||
def predict_on_distorted_from_disk(self, k: int, model_dir: str | None = None):
|
||
if self.distorted_df is None:
|
||
self.load()
|
||
|
||
k_dir = self.output_dir/f"k{int(k)}"
|
||
if model_dir is None:
|
||
lb = k_dir/"model_leaderboard.csv"
|
||
if not lb.exists(): raise FileNotFoundError(f"Missing leaderboard at {lb}")
|
||
model_dir = Path(pd.read_csv(lb).iloc[0]["model_dir"])
|
||
else:
|
||
model_dir = Path(model_dir)
|
||
|
||
model = joblib.load(model_dir/"model.pkl")
|
||
scaler = joblib.load(k_dir/"scaler.pkl")
|
||
|
||
topk_txt = model_dir/"top_k_metrics.txt"
|
||
if not topk_txt.exists(): topk_txt = self.output_dir/f"top_k_metrics_k{k}.txt"
|
||
with open(topk_txt,"r",encoding="utf-8") as f:
|
||
top_k = [ln.strip() for ln in f if ln.strip()]
|
||
|
||
missing = [m for m in top_k if m not in self.distorted_df.columns]
|
||
if missing:
|
||
raise ValueError(f"Missing metrics in distorted CSV: {missing}")
|
||
|
||
X = self.distorted_df[top_k].apply(pd.to_numeric, errors="coerce")
|
||
if X.isnull().any().any():
|
||
bad = X.columns[X.isnull().any()].tolist()
|
||
raise ValueError(f"Non numeric values in distorted metrics: {bad}")
|
||
|
||
X_scaled = pd.DataFrame(scaler.transform(X), columns=top_k, index=X.index)
|
||
X_scaled = self._verify_and_align_features(model, X_scaled, scaler)
|
||
|
||
preds = model.predict(X_scaled)
|
||
X.iloc[:20].to_csv(k_dir/"debug_features_head.csv", index=False)
|
||
out_csv = k_dir/"pseudo_mos.csv"
|
||
self.distorted_df[["file_name"]].assign(pseudo_mos=preds).to_csv(out_csv, index=False)
|
||
print(f"[predict] pseudo-MOS → {out_csv}")
|
||
|
||
# ------------ orchestration ------------
|
||
|
||
def compute_best_k(self, threshold=0.95, save_plot=True) -> int:
|
||
print("[k] SVD + Picard")
|
||
|
||
analysis_dir = self.output_dir/"analysis"
|
||
ensure_dir(analysis_dir)
|
||
|
||
X = self.train_df.drop(columns=["file_name","mos"]).copy().astype(float)
|
||
y = self.train_df["mos"].values.astype(float)
|
||
y0 = y - y.mean()
|
||
|
||
scaler = StandardScaler()
|
||
Xs = scaler.fit_transform(X)
|
||
U, s, _ = svd(Xs, full_matrices=False)
|
||
uy = (U.T @ y0)
|
||
|
||
energy = np.cumsum(s**2) / np.sum(s**2)
|
||
k_energy = int(np.argmax(energy >= threshold) + 1)
|
||
|
||
pd.DataFrame({"index": np.arange(1,len(energy)+1),
|
||
"energy": energy, "sigma": s, "abs_Uty": np.abs(uy)}).to_csv(analysis_dir/"svd_energy.csv", index=False)
|
||
|
||
if save_plot:
|
||
plt.rcParams.update({"font.size": 16})
|
||
|
||
plt.figure(figsize=(7,5))
|
||
plt.plot(range(1,len(energy)+1), energy, marker="o", label="Explained variance")
|
||
for label,t in {"68%":0.68,"95%":0.95,"99.7%":0.997}.items():
|
||
k_t = int(np.argmax(energy>=t)+1)
|
||
plt.axhline(y=t, linestyle="--", linewidth=1, alpha=0.5)
|
||
plt.axvline(x=k_t, linestyle=":", linewidth=1.5, label=f"{label}: k = {k_t}")
|
||
plt.title("Cumulative Explained Variance (SVD)")
|
||
plt.xlabel("Number of metrics (k)"); plt.ylabel("Explained variance")
|
||
plt.grid(True); plt.legend(); plt.tight_layout()
|
||
plt.savefig(analysis_dir/"variance.pdf", format="pdf"); plt.close()
|
||
|
||
plt.figure(figsize=(7,5))
|
||
plt.plot(s, label=r"Singular values sigma_i")
|
||
plt.plot(np.abs(uy), label=r"|U^T y|")
|
||
plt.yscale("log"); plt.xlabel("Number of metrics (k)"); plt.ylabel("Magnitude (log)")
|
||
plt.title("Picard Criterion"); plt.grid(True); plt.legend(); plt.tight_layout()
|
||
plt.savefig(analysis_dir/"picard.pdf", format="pdf"); plt.close()
|
||
|
||
print(f"[k] suggested k = {k_energy} at {threshold*100:.1f}% variance")
|
||
return k_energy
|
||
|
||
def run(self, k=None, threshold=0.95, n_trials=150, timeout=None, n_splits=5, use_optuna=True):
|
||
print("=========================================")
|
||
print(f"Running fusion for label_type={self.label_type}")
|
||
self.load()
|
||
k = int(k or self.compute_best_k(threshold=threshold))
|
||
X, y, top_k = self.select_top_k_features(k)
|
||
Xs, scaler = self.normalize_features(X, k)
|
||
self.compute_best_models(Xs, y, k, top_k, n_trials=n_trials, timeout=timeout, n_splits=n_splits, use_optuna=use_optuna)
|
||
self.predict_on_distorted(scaler)
|
||
print("=========================================")
|
||
print("Best model:")
|
||
print(f" model : {self.best_model_info['model_name']}")
|
||
print(f" k : {self.best_model_info['k']}")
|
||
print(f" top_k : {self.best_model_info['top_k']}")
|
||
print(f" combined: {self.best_model_info['score']:.4f}")
|
||
print("=========================================")
|
||
|
||
# ----------------------- CLI -----------------------
|
||
|
||
def build_cli() -> argparse.ArgumentParser:
|
||
p = argparse.ArgumentParser(description="Fuse FR-IQA metrics into MOS regressors with Optuna and pseudo-MOS generation")
|
||
sub = p.add_subparsers(dest="cmd", required=True)
|
||
|
||
def add_common_io(sp):
|
||
sp.add_argument("--iqa-train", required=True, help="Path to labeled train FR-IQA CSV")
|
||
sp.add_argument("--mos-train", default=None, help="CSV with biased MOS or mixed columns (mos, mos_unbias)")
|
||
sp.add_argument("--mos-train-unbias", default=None, help="CSV with unbias MOS if separate; optional")
|
||
sp.add_argument("--iqa-distorted", required=True, help="Path to distorted FR-IQA CSV")
|
||
sp.add_argument("--out", required=True, help="Output root directory")
|
||
sp.add_argument("--label-type", choices=["biased","unbias"], default="biased", help="Which MOS track to use")
|
||
|
||
# compute-k
|
||
sp_k = sub.add_parser("compute-k", help="Suggest k via SVD+Picard")
|
||
add_common_io(sp_k)
|
||
sp_k.add_argument("--threshold", type=float, default=0.95)
|
||
|
||
# best-models
|
||
sp_bm = sub.add_parser("best-models", help="Train and score models for a fixed k")
|
||
add_common_io(sp_bm)
|
||
sp_bm.add_argument("--k", type=int, required=True)
|
||
sp_bm.add_argument("--n-trials", type=int, default=150)
|
||
sp_bm.add_argument("--timeout", type=int, default=None)
|
||
sp_bm.add_argument("--n-splits", type=int, default=5)
|
||
sp_bm.add_argument("--no-optuna", action="store_true")
|
||
|
||
# pseudo-mos
|
||
sp_pm = sub.add_parser("pseudo-mos", help="Predict pseudo-MOS with saved artifacts")
|
||
add_common_io(sp_pm)
|
||
sp_pm.add_argument("--k", type=int, required=True)
|
||
sp_pm.add_argument("--model-dir", type=str, default=None)
|
||
|
||
# all
|
||
sp_all = sub.add_parser("all", help="End-to-end: compute k (if needed), train models, predict pseudo-MOS")
|
||
add_common_io(sp_all)
|
||
sp_all.add_argument("--k", type=int, default=None)
|
||
sp_all.add_argument("--threshold", type=float, default=0.95)
|
||
sp_all.add_argument("--n-trials", type=int, default=150)
|
||
sp_all.add_argument("--timeout", type=int, default=None)
|
||
sp_all.add_argument("--n-splits", type=int, default=5)
|
||
sp_all.add_argument("--no-optuna", action="store_true")
|
||
|
||
return p
|
||
|
||
# ----------------------- Main -----------------------
|
||
|
||
def main(argv=None):
|
||
args = build_cli().parse_args(argv)
|
||
|
||
reg = FusionRegressor(
|
||
iqa_train_csv=args.iqa_train,
|
||
mos_train_csv=args.mos_train,
|
||
mos_train_unbias_csv=getattr(args, "mos_train_unbias", None),
|
||
iqa_distorted_csv=args.iqa_distorted,
|
||
output_dir=args.out,
|
||
label_type=args.label_type
|
||
)
|
||
|
||
if args.cmd == "compute-k":
|
||
reg.load()
|
||
k = reg.compute_best_k(threshold=args.threshold)
|
||
print(f"Suggested k: {k}")
|
||
|
||
elif args.cmd == "best-models":
|
||
reg.load()
|
||
X, y, top_k = reg.select_top_k_features(args.k)
|
||
Xs, _ = reg.normalize_features(X, args.k)
|
||
reg.compute_best_models(Xs, y, args.k, top_k,
|
||
n_trials=args.n_trials, timeout=args.timeout,
|
||
n_splits=args.n_splits, use_optuna=not args.no_optuna)
|
||
print("Done. See:", reg.output_dir/f"k{args.k}")
|
||
|
||
elif args.cmd == "pseudo-mos":
|
||
reg.load()
|
||
reg.predict_on_distorted_from_disk(k=args.k, model_dir=args.model_dir)
|
||
|
||
elif args.cmd == "all":
|
||
reg.run(k=args.k, threshold=args.threshold,
|
||
n_trials=args.n_trials, timeout=args.timeout,
|
||
n_splits=args.n_splits, use_optuna=not args.no_optuna)
|
||
|
||
else:
|
||
raise RuntimeError("Unknown command")
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|