''' Filename: pipeline_fusion.py Path: /home/netoa/Desktop/ISR/scripts Created Date: Wednesday April 16th 2025 Author: Andre Neto ----- Last Modified: Wed May 28 2025 Modified By: Andre Neto ----- Copyright (c) 2025 Institute of Systems and Robotics ''' from pathlib import Path import multiprocessing as mp import shap import joblib import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.linear_model import ( Ridge, LinearRegression, ElasticNet, BayesianRidge ) from sklearn.ensemble import ( RandomForestRegressor, GradientBoostingRegressor, ExtraTreesRegressor, HistGradientBoostingRegressor ) from sklearn.svm import SVR from sklearn.model_selection import cross_val_predict, KFold, GridSearchCV from sklearn.preprocessing import StandardScaler from sklearn.metrics import mean_squared_error, mean_absolute_error from scipy.stats import pearsonr, spearmanr from scipy.linalg import svd from xgboost import XGBRegressor from lightgbm import LGBMRegressor from catboost import CatBoostRegressor mp.set_start_method("spawn", force=True) # pylint: disable=line-too-long class FusionRegressor: """ A class for fusing full-reference IQA metrics using supervised regression models. It allows selecting the top-k most correlated metrics, comparing different regressors, and generating pseudo-MOS scores for unlabeled data. """ def __init__(self, iqa_train_csv, mos_train_csv, iqa_distorted_csv, output_dir): """ Initialize paths and internal structures. Args: iqa_train_csv (str): Path to FR-IQA metrics for the training set (e.g., data/labeled/train/iqa.csv) mos_train_csv (str): Path to MOS scores for the training set (e.g., data/labeled/train/mos.csv) iqa_distorted_csv (str): Path to FR-IQA metrics for unlabeled data (e.g., data/distorted/iqa.csv) output_dir (str): Output directory to save models, scores, and pseudo-MOS """ self.iqa_train_csv = iqa_train_csv self.mos_train_csv = mos_train_csv self.iqa_distorted_csv = iqa_distorted_csv self.output_dir = Path(output_dir) self.train_df = None # Merged IQA + MOS for training self.distorted_df = None # IQA metrics for unlabeled distorted images self.ranking_df = None # PLCC-based ranking of metrics self.total_k = None # Total number of available FR metrics self.best_model_info = {} # Stores best model, k, top_k, and metrics self.model_defs = { "Linear": LinearRegression(), "Ridge": Ridge(alpha=1.0), "ElasticNet": ElasticNet(alpha=1.0, l1_ratio=0.5), "BayesianRidge": BayesianRidge(), "SVR": SVR(kernel="rbf", C=1.0, gamma="scale"), "RandomForest": RandomForestRegressor(n_estimators=100, max_depth=None, random_state=42), "ExtraTrees": ExtraTreesRegressor(n_estimators=100, random_state=42), "GradientBoosting": GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, random_state=42), "HistGradientBoosting": HistGradientBoostingRegressor(max_iter=100, random_state=42), "XGBoost": XGBRegressor(n_estimators=100, learning_rate=0.1, random_state=42, verbosity=0, use_label_encoder=False), "LightGBM": LGBMRegressor(n_estimators=100, learning_rate=0.1, random_state=42, verbosity=-1), "CatBoost": CatBoostRegressor(iterations=100, learning_rate=0.1, verbose=0, random_state=42) } self.search_spaces = { "Linear": {}, "Ridge": { "alpha": [0.01, 0.1, 1.0, 10.0, 100.0] }, "ElasticNet": { "alpha": [0.01, 0.1, 1.0, 10.0], "l1_ratio": [0.1, 0.3, 0.5, 0.7, 0.9], "max_iter": [5000] }, "BayesianRidge": { "alpha_1": [1e-6, 1e-5, 1e-4], "alpha_2": [1e-6, 1e-5, 1e-4], "lambda_1": [1e-6, 1e-5, 1e-4], "lambda_2": [1e-6, 1e-5, 1e-4] }, "SVR": { "C": [0.1, 1, 10, 100], "gamma": ["scale", "auto"], "epsilon": [0.01, 0.1, 0.5] }, "RandomForest": { "n_estimators": [100, 300, 500], "max_depth": [None, 10, 20, 30], "min_samples_split": [2, 5, 10], "min_samples_leaf": [1, 2, 4] }, "ExtraTrees": { "n_estimators": [100, 300, 500], "max_depth": [None, 10, 20, 30], "min_samples_split": [2, 5], "min_samples_leaf": [1, 2] }, "GradientBoosting": { "n_estimators": [100, 200, 300], "learning_rate": [0.01, 0.05, 0.1], "max_depth": [3, 4, 5], "subsample": [0.7, 0.9, 1.0] }, "HistGradientBoosting": { "max_iter": [100, 200], "learning_rate": [0.01, 0.05, 0.1], "max_depth": [None, 6, 10], "l2_regularization": [0.0, 0.1, 1.0] }, "XGBoost": { "n_estimators": [100, 250, 500], "learning_rate": [0.01, 0.05, 0.1], "max_depth": [3, 6, 9], "subsample": [0.6, 0.8, 1.0], "colsample_bytree": [0.6, 0.8, 1.0] }, "LightGBM": { "n_estimators": [100, 250, 500], "learning_rate": [0.01, 0.05, 0.1], "num_leaves": [31, 63, 127], "max_depth": [-1, 10, 20], "min_child_samples": [5, 10, 20] }, "CatBoost": { "iterations": [100, 250, 500], "learning_rate": [0.01, 0.05, 0.1], "depth": [4, 6, 8], "l2_leaf_reg": [1, 3, 5] } } def load(self): """ Load the training IQA data, MOS labels, and distorted IQA data. Also computes the PLCC-based ranking of FR metrics internally. """ print("Loading data...") print(f"- Reading IQA metrics from: {self.iqa_train_csv}") iqa_df = pd.read_csv(self.iqa_train_csv) print(f"- Reading MOS scores from: {self.mos_train_csv}") mos_df = pd.read_csv(self.mos_train_csv) print("- Merging IQA and MOS by 'file_name'") self.train_df = iqa_df.merge(mos_df, on="file_name", how="inner") print(f"- Reading distorted IQA metrics from: {self.iqa_distorted_csv}") self.distorted_df = pd.read_csv(self.iqa_distorted_csv) print(f"- Loaded {self.train_df.shape[0]} training samples and {self.distorted_df.shape[0]} distorted samples.") # Compute ranking of FR metrics based on PLCC self.compute_fr_ranking() self.total_k = len(self.ranking_df) def compute_fr_ranking(self): """ Compute a combined PLCC and SRCC ranking of FR metrics. Saves the result in self.ranking_df and as CSV to disk. """ print("Computing PLCC + SRCC ranking of FR metrics...") metrics_df = self.train_df.drop(columns=["file_name", "mos"]) mos = self.train_df["mos"] plcc_scores = {} srcc_scores = {} for metric in metrics_df.columns: plcc, _ = pearsonr(metrics_df[metric], mos) srcc, _ = spearmanr(metrics_df[metric], mos) plcc_scores[metric] = plcc srcc_scores[metric] = srcc self.ranking_df = pd.DataFrame({ "PLCC": pd.Series(plcc_scores), "SRCC": pd.Series(srcc_scores) }) self.ranking_df["Score"] = 0.5 * (self.ranking_df["PLCC"] + self.ranking_df["SRCC"]) self.ranking_df = self.ranking_df.sort_values(by="Score", ascending=False) # Save to disk output_path = Path("results/pipeline_fusion/ranking.csv") output_path.parent.mkdir(parents=True, exist_ok=True) self.ranking_df.to_csv(output_path, index_label="metric") print(f"- Ranking saved to: {output_path}") def select_top_k_features(self, k): """ Select the top-k FR metrics based on the internal ranking, extract x and y from the training set, and save the selected metric names to disk. Args: k (int): Number of top metrics to select Returns: x (DataFrame): Top-k feature matrix y (Series): Ground truth MOS top_k (List[str]): List of top-k metric names """ if self.ranking_df is None or self.train_df is None: raise RuntimeError("Data not loaded. Please run .load() first.") if k > len(self.ranking_df): raise ValueError(f"Requested k={k} exceeds available metrics ({len(self.ranking_df)})") # Extract top-k metric names top_k = self.ranking_df.head(k).index.tolist() print(f"\nSelected top-{k} metrics:") for i, name in enumerate(top_k, 1): print(f" {i:>2}. {name}") # Extract features and labels x = self.train_df[top_k] y = self.train_df["mos"] # Save top-k metric names to file output_path = Path(f"results/pipeline_fusion/top_k_metrics_k{k}.txt") output_path.parent.mkdir(parents=True, exist_ok=True) with open(output_path, "w", encoding="utf-8") as f: for metric in top_k: f.write(metric + "\n") print(f"- Top-{k} metric names saved to: {output_path}") return x, y, top_k def normalize_features(self, x, k): """ Normalize the feature matrix x using StandardScaler. Saves the scaler and normalized data to disk. Args: x (DataFrame): Feature matrix to normalize k (int): Number of selected features (for naming output) Returns: x_scaled (DataFrame): Normalized feature matrix scaler (StandardScaler): Fitted scaler object """ print("Normalizing features...") scaler = StandardScaler() x_scaled_array = scaler.fit_transform(x) x_scaled = pd.DataFrame(x_scaled_array, columns=x.columns, index=x.index) # Save the scaler scaler_path = Path(f"results/pipeline_fusion/k{k}/scaler.pkl") scaler_path.parent.mkdir(parents=True, exist_ok=True) joblib.dump(scaler, scaler_path) # Save the normalized feature matrix norm_csv_path = scaler_path.parent / "x_scaled.csv" x_scaled.to_csv(norm_csv_path, index=False) print(f"- Scaler saved to: {scaler_path}") print(f"- Normalized features saved to: {norm_csv_path}") return x_scaled, scaler def compute_best_k(self, threshold=0.95, save_plot=True): """ Suggest the optimal number of FR metrics (k) using SVD energy and the Picard criterion for regression stability. Args: threshold (float): Energy threshold (e.g., 0.95 for 95% variance retained) save_plot (bool): Whether to show diagnostic plots Returns: int: Suggested number of top-k metrics for the given threshold """ print("Computing optimal k using SVD and Picard criterion...") # Prepare output paths analysis_dir = Path("results/pipeline_fusion/analysis") analysis_dir.mkdir(parents=True, exist_ok=True) # Extract features and target x = self.train_df.drop(columns=["file_name", "mos"]) y = self.train_df["mos"].values y_centered = y - np.mean(y) # Normalize features scaler = StandardScaler() x_scaled = scaler.fit_transform(x) # SVD decomposition u, s, _ = svd(x_scaled, full_matrices=False) uy = np.dot(u.T, y_centered) # Compute cumulative energy energy = np.cumsum(s**2) / np.sum(s**2) k_energy = np.argmax(energy >= threshold) + 1 # Save energy and singular value info energy_df = pd.DataFrame({ "index": np.arange(1, len(energy) + 1), "energy": energy, "sigma": s, "abs_Uty": np.abs(uy) }) energy_df.to_csv(analysis_dir / "svd_energy.csv", index=False) print(f"- Energy and singular value info saved to: {analysis_dir / 'svd_energy.csv'}") # Plot 1: Cumulative energy with multiple thresholds if save_plot: # Diretório de saída analysis_dir.mkdir(parents=True, exist_ok=True) plt.rcParams.update({"font.size": 16}) # Gráfico 1: Variância Explicada plt.figure(figsize=(7, 5)) # metade do total para subfigura plt.plot(range(1, len(energy) + 1), energy, marker="o", label="Explained variance") threshold_levels = { "68%": 0.68, "95%": 0.95, "99.7%": 0.997 } for label, t in threshold_levels.items(): k_t = np.argmax(energy >= t) + 1 plt.axhline(y=t, color="red", linestyle="--", linewidth=1, alpha=0.5) plt.axvline(x=k_t, color="green" if t == threshold else "gray", 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() # Gráfico 2: Critério de Picard plt.figure(figsize=(7, 5)) # mesmo tamanho da subfigura anterior plt.plot(s, label=r"Singular values $\sigma_i$") plt.plot(np.abs(uy), label=r"Response projection $|U^\top y|$") plt.yscale("log") plt.xlabel("Number of metrics (k)") plt.ylabel("Magnitude (log scale)") plt.title("Picard Criterion") plt.grid(True) plt.legend() plt.tight_layout() plt.savefig(analysis_dir / "picard.pdf", format="pdf") plt.close() print(f"- Diagnostic plots saved to: {analysis_dir}") print(f"Suggested k = {k_energy} (explains {threshold*100:.1f}% of variance)") return k_energy def compute_best_models(self, x_scaled, y, k, top_k): """ Evaluate and compare multiple regressors using the selected top-k features. Uses GridSearchCV when parameter grid is defined in self.search_spaces. Saves models, predictions, evaluation scores, and SHAP (tree models). """ print(f"\nEvaluating models using top-{k} metrics...") best_score = -np.inf for model_name, base_model in self.model_defs.items(): print(f"\n- Training model: {model_name}") # Decide if using grid search param_grid = self.search_spaces.get(model_name) if param_grid: print(" → Using GridSearchCV for hyperparameter tuning.") model = GridSearchCV( estimator=base_model, param_grid=param_grid, scoring="neg_mean_squared_error", cv=KFold(n_splits=5, shuffle=True, random_state=42), n_jobs=-1 ) else: print(" → Using default parameters (no search).") model = base_model # Cross-validated predictions try: y_pred = cross_val_predict(model, x_scaled, y, cv=KFold(n_splits=5, shuffle=True, random_state=42), n_jobs=-1) except (ValueError, RuntimeError) as e: print(f" [ERROR] Cross-val failed for {model_name}: {e}") continue plcc, _ = pearsonr(y, y_pred) srcc, _ = spearmanr(y, y_pred) mse = mean_squared_error(y, y_pred) mae = mean_absolute_error(y, y_pred) combined_score = 0.5 * (plcc + srcc) print(f" PLCC = {plcc:.4f} | SRCC = {srcc:.4f} | MSE = {mse:.4f} | MAE = {mae:.4f}") # Fit final model on full data try: model.fit(x_scaled, y) if isinstance(model, GridSearchCV): best_model = model.best_estimator_ best_params = model.best_params_ print(f" ✓ Best hyperparameters: {best_params}") else: best_model = model best_params = None except (ValueError, RuntimeError) as e: print(f" [ERROR] Final fit failed for {model_name}: {e}") continue # Save results model_dir = Path(f"results/pipeline_fusion/k{k}/{model_name.lower()}") model_dir.mkdir(parents=True, exist_ok=True) # Save predictions pd.DataFrame({"true": y, "pred": y_pred}).to_csv(model_dir / "predictions.csv", index=False) # Save scores score_data = { "PLCC": plcc, "SRCC": srcc, "MSE": mse, "MAE": mae, } if best_params: score_data.update(best_params) pd.DataFrame([score_data]).to_csv(model_dir / "scores.csv", index=False) # Save model joblib.dump(best_model, model_dir / "model.pkl") # Save top-k metrics with open(model_dir / "top_k_metrics.txt", "w", encoding="utf-8") as f: for metric in top_k: f.write(metric + "\n") # Save GridSearch diagnostics if isinstance(model, GridSearchCV): pd.DataFrame(model.cv_results_).to_csv(model_dir / "grid_search_results.csv", index=False) # Track best model by combined score if combined_score > best_score: best_score = combined_score self.best_model_info = { "model_name": model_name, "model": best_model, "top_k": top_k, "k": k, "score": combined_score } # SHAP (apenas para modelos de árvore) if model_name.lower() in ["randomforest", "extratrees", "gradientboosting", "xgboost", "lightgbm", "catboost"]: try: explainer = shap.Explainer(best_model, x_scaled) shap_values = explainer(x_scaled) shap.summary_plot(shap_values, features=x_scaled, feature_names=top_k, show=False) plt.tight_layout() plt.savefig(model_dir / "shap_summary.png", dpi=300) plt.close() print(" SHAP summary plot saved.") except (shap.common.exceptions.ShapError, ValueError) as e: print(f" [Warning] SHAP failed: {e}") def predict_on_distorted(self, scaler): """ Apply the best trained model to the distorted set and generate pseudo-MOS scores. Saves the resulting pseudo_mos.csv file to disk. Args: scaler (StandardScaler): Fitted scaler from the training data """ print("\nGenerating pseudo-MOS for distorted data...") if self.best_model_info is None or not self.best_model_info: raise RuntimeError("No best model found. Please run compute_best_models() first.") model = self.best_model_info["model"] top_k = self.best_model_info["top_k"] k = self.best_model_info["k"] # Extract top-k features from distorted set x_distorted = self.distorted_df[top_k] x_distorted_scaled = scaler.transform(x_distorted) # Predict pseudo-MOS pseudo_mos = model.predict(x_distorted_scaled) # Combine with file names result_df = self.distorted_df[["file_name"]].copy() result_df["pseudo_mos"] = pseudo_mos # Save results output_path = Path(f"results/pipeline_fusion/k{k}/pseudo_mos.csv") result_df.to_csv(output_path, index=False) print(f"- Pseudo-MOS predictions saved to: {output_path}") def run(self, k=None, threshold=0.95): """ Execute the full fusion pipeline: ranking, selection, training, and pseudo-MOS generation. This method performs the following steps: 1. Loads the training and distorted IQA data 2. Computes PLCC+SRCC-based ranking of full-reference metrics 3. Determines the optimal number of features (k) via SVD + Picard, unless k is manually provided 4. Selects the top-k metrics and normalizes the feature matrix 5. Trains and evaluates multiple regression models on the training data 6. Identifies the best model based on PLCC 7. Applies the best model to distorted data and saves pseudo-MOS scores """ print("Running the fusion pipeline...") print("=========================================") self.load() k = k or self.compute_best_k(threshold=threshold) x, y, top_k = self.select_top_k_features(k) x_scaled, scaler = self.normalize_features(x, k) self.compute_best_models(x_scaled, y, k, top_k) self.predict_on_distorted(scaler) print("Fusion pipeline completed successfully.") print("=========================================") print("Best model info:") print(f"- Model name: {self.best_model_info['model_name']}") print(f"- k: {self.best_model_info['k']}") print(f"- Top-k metrics: {self.best_model_info['top_k']}") print("=========================================") if __name__ == "__main__": reg = FusionRegressor( iqa_train_csv="data/labeled/train/iqa.csv", mos_train_csv="data/labeled/train/mos_debiased.csv", iqa_distorted_csv="data/distorted/iqa.csv", output_dir="results/pipeline_fusion" ) reg.load() reg.compute_best_k()