update
This commit is contained in:
@@ -1,127 +0,0 @@
|
||||
'''
|
||||
Filename: iqa_correlation_analysis.py
|
||||
Path: /home/netoa/Desktop/ISR/scripts
|
||||
Created Date: Monday March 24th 2025
|
||||
Author: Andre Neto
|
||||
-----
|
||||
Last Modified: Tue Mar 25 2025
|
||||
Modified By: Andre Neto
|
||||
-----
|
||||
Copyright (c) 2025 Institute of Systems and Robotics
|
||||
'''
|
||||
|
||||
import os
|
||||
import pandas as pd
|
||||
import matplotlib.pyplot as plt
|
||||
import seaborn as sns
|
||||
import numpy as np
|
||||
from scipy.stats import pearsonr, spearmanr
|
||||
|
||||
# pylint: disable=line-too-long
|
||||
|
||||
def load_iqa_data(objective_path: str, subjective_path: str) -> pd.DataFrame:
|
||||
"""Load and merge objective and subjective IQA scores."""
|
||||
obj_df = pd.read_csv(objective_path)
|
||||
subj_df = pd.read_csv(subjective_path)[["file_name", "mos"]]
|
||||
merged_df = obj_df.merge(subj_df, on="file_name", how="inner")
|
||||
return merged_df
|
||||
|
||||
|
||||
def compute_iqa_correlations(df: pd.DataFrame) -> pd.DataFrame:
|
||||
"""Compute PLCC and SRCC for each IQA metric."""
|
||||
metrics = df.drop(columns=["file_name", "mos"])
|
||||
plcc, srcc = {}, {}
|
||||
for metric in metrics.columns:
|
||||
plcc[metric], _ = pearsonr(df[metric], df["mos"])
|
||||
srcc[metric], _ = spearmanr(df[metric], df["mos"])
|
||||
results_df = pd.DataFrame.from_dict(plcc, orient="index", columns=["PLCC"])
|
||||
results_df["SRCC"] = pd.Series(srcc)
|
||||
results_df = results_df.sort_values(by="PLCC", ascending=False)
|
||||
return results_df
|
||||
|
||||
|
||||
def plot_iqa_scatter(df: pd.DataFrame, output_dir: str, file_name: str = "metrics_scatter"):
|
||||
"""Scatter plots of MOS vs each IQA metric with smoothed regression line."""
|
||||
metrics = df.drop(columns=["file_name", "mos"])
|
||||
num_metrics = len(metrics.columns)
|
||||
cols = 5
|
||||
rows = -(-num_metrics // cols)
|
||||
|
||||
fig, axes = plt.subplots(rows, cols, figsize=(16, rows * 3))
|
||||
axes = axes.flatten()
|
||||
|
||||
for i, metric in enumerate(metrics.columns):
|
||||
sns.scatterplot(x=df[metric], y=df["mos"], alpha=0.5, ax=axes[i], color="#87CEEB") # Lighter blue
|
||||
x_sorted = df[metric].sort_values().values
|
||||
y_sorted = df.loc[df[metric].sort_values().index, "mos"].values
|
||||
z = np.polyfit(x_sorted, y_sorted, 3) # Fit a cubic curve
|
||||
p = np.poly1d(z)
|
||||
axes[i].plot(x_sorted, p(x_sorted), color="red", linewidth=2) # Red curve
|
||||
axes[i].set_title(metric)
|
||||
axes[i].set_xlabel("IQA Score")
|
||||
axes[i].set_ylabel("MOS")
|
||||
|
||||
for j in range(num_metrics, len(axes)):
|
||||
fig.delaxes(axes[j])
|
||||
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
plt.tight_layout()
|
||||
plt.savefig(os.path.join(output_dir, f"{file_name}.png"), dpi=300)
|
||||
plt.savefig(os.path.join(output_dir, f"{file_name}.eps"), dpi=300)
|
||||
plt.close()
|
||||
|
||||
|
||||
def plot_iqa_bar(results_df: pd.DataFrame, output_dir: str, file_name: str = "metrics_bar"):
|
||||
"""Bar chart ranking IQA metrics based on PLCC and SRCC."""
|
||||
sorted_df = results_df.sort_values(by="PLCC", ascending=True)
|
||||
|
||||
plt.figure(figsize=(12, 8))
|
||||
plt.barh(sorted_df.index, sorted_df["PLCC"], color="steelblue", label="PLCC")
|
||||
plt.barh(sorted_df.index, sorted_df["SRCC"], color="orange", alpha=0.7, label="SRCC")
|
||||
plt.xlabel("Correlation Coefficient")
|
||||
plt.ylabel("IQA Metric")
|
||||
plt.title("Ranking of IQA Metrics (PLCC & SRCC)")
|
||||
plt.legend()
|
||||
plt.grid(axis="x", linestyle="--", alpha=0.7)
|
||||
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
plt.tight_layout()
|
||||
plt.savefig(os.path.join(output_dir, f"{file_name}.png"), dpi=300)
|
||||
plt.savefig(os.path.join(output_dir, f"{file_name}.eps"), dpi=300)
|
||||
plt.close()
|
||||
|
||||
|
||||
def save_iqa_results(results_df: pd.DataFrame, output_path: str):
|
||||
"""Save correlation scores to CSV."""
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
results_df.to_csv(output_path, index_label="metric")
|
||||
|
||||
|
||||
def main():
|
||||
"""Run full IQA correlation analysis pipeline."""
|
||||
# Input paths
|
||||
objective_path = "results/sheets/iqa_objective.csv"
|
||||
subjective_path = "results/sheets/iqa_subjective.csv"
|
||||
|
||||
# Output directory
|
||||
output_dir = "results/fr_metrics"
|
||||
csv_path = os.path.join(output_dir, "metrics_plcc_srcc.csv")
|
||||
|
||||
# Load and merge datasets
|
||||
merged_df = load_iqa_data(objective_path, subjective_path)
|
||||
|
||||
# Compute correlation rankings
|
||||
results_df = compute_iqa_correlations(merged_df)
|
||||
|
||||
# Generate visualizations
|
||||
plot_iqa_scatter(merged_df, output_dir, "metrics_scatter")
|
||||
plot_iqa_bar(results_df, output_dir, "metrics_bar")
|
||||
|
||||
# Save results
|
||||
save_iqa_results(results_df, csv_path)
|
||||
|
||||
print("IQA Correlation Analysis Complete. Results saved to disk.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -38,7 +38,6 @@ from metrics.objective.full_reference import color
|
||||
from metrics.objective.full_reference import frequency
|
||||
from metrics.objective.full_reference import gradient
|
||||
from metrics.objective.full_reference import information
|
||||
from metrics.objective.full_reference import models
|
||||
from metrics.objective.full_reference import perceptual
|
||||
from metrics.objective.full_reference import pixel
|
||||
from metrics.objective.full_reference import region
|
||||
@@ -87,7 +86,6 @@ def compute(ref_dir, dist_dir, out_file):
|
||||
frequency_results = frequency.compute_all(ref_img_path, dist_img_path)
|
||||
gradient_results = gradient.compute_all(ref_img_path, dist_img_path)
|
||||
information_results = information.compute_all(ref_img_path, dist_img_path)
|
||||
models_results = models.compute_all(ref_img_path, dist_img_path)
|
||||
perceptual_results = perceptual.compute_all(ref_img_path, dist_img_path)
|
||||
pixel_results = pixel.compute_all(ref_img_path, dist_img_path)
|
||||
region_results = region.compute_all(ref_img_path, dist_img_path)
|
||||
@@ -100,7 +98,6 @@ def compute(ref_dir, dist_dir, out_file):
|
||||
**frequency_results,
|
||||
**gradient_results,
|
||||
**information_results,
|
||||
**models_results,
|
||||
**perceptual_results,
|
||||
**pixel_results,
|
||||
**region_results,
|
||||
@@ -128,9 +125,9 @@ def compute(ref_dir, dist_dir, out_file):
|
||||
|
||||
def main():
|
||||
'''main function'''
|
||||
#reference_dir = 'images/reference/'
|
||||
#distorted_dir = 'images/distorted/'
|
||||
#output_file = 'results/sheets/iqa_objective.csv'
|
||||
reference_dir = 'data/reference/'
|
||||
distorted_dir = 'data/distorted/'
|
||||
output_file = 'results/iqa_objective.csv'
|
||||
|
||||
# If you want to start fresh, uncomment the following line to clear the file
|
||||
# open(output_file, 'w', encoding='utf-8').close()
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
'''
|
||||
Filename: evaluation.py
|
||||
Path: /home/netoa/Desktop/ISR/scripts
|
||||
Created Date: Monday March 24th 2025
|
||||
Author: Andre Neto
|
||||
-----
|
||||
Last Modified: Tue Mar 25 2025
|
||||
Modified By: Andre Neto
|
||||
-----
|
||||
Copyright (c) 2025 Institute of Systems and Robotics
|
||||
'''
|
||||
|
||||
from sklearn.model_selection import cross_val_predict, KFold
|
||||
from sklearn.metrics import mean_squared_error, mean_absolute_error
|
||||
from scipy.stats import pearsonr, spearmanr
|
||||
|
||||
|
||||
def evaluate_model_cv(model, x, y, cv=5):
|
||||
"""Evaluate model with cross-validation and return metrics."""
|
||||
kf = KFold(n_splits=cv, shuffle=True, random_state=42)
|
||||
y_pred = cross_val_predict(model, x, y, cv=kf)
|
||||
|
||||
plcc, _ = pearsonr(y, y_pred)
|
||||
srcc, _ = spearmanr(y, y_pred)
|
||||
mse = mean_squared_error(y, y_pred)
|
||||
mae = mean_absolute_error(y, y_pred)
|
||||
|
||||
return {
|
||||
"PLCC": round(plcc, 4),
|
||||
"SRCC": round(srcc, 4),
|
||||
"MSE": round(mse, 4),
|
||||
"MAE": round(mae, 4)
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
'''
|
||||
Filename: models.py
|
||||
Path: /home/netoa/Desktop/ISR/scripts
|
||||
Created Date: Monday March 24th 2025
|
||||
Author: Andre Neto
|
||||
-----
|
||||
Last Modified: Tue Mar 25 2025
|
||||
Modified By: Andre Neto
|
||||
-----
|
||||
Copyright (c) 2025 Institute of Systems and Robotics
|
||||
'''
|
||||
|
||||
from sklearn.linear_model import LinearRegression, Ridge
|
||||
from sklearn.ensemble import RandomForestRegressor
|
||||
from sklearn.svm import SVR
|
||||
|
||||
|
||||
def get_models():
|
||||
"""Return dictionary of regression models for fusion pipeline."""
|
||||
|
||||
models = {
|
||||
"LinearRegression": LinearRegression(),
|
||||
"Ridge": Ridge(alpha=1.0),
|
||||
"RandomForest": RandomForestRegressor(n_estimators=200, max_depth=None, random_state=42),
|
||||
"SVR": SVR(kernel="rbf")
|
||||
}
|
||||
|
||||
# Optional: XGBoost
|
||||
try:
|
||||
from xgboost import XGBRegressor
|
||||
models["XGBoost"] = XGBRegressor(
|
||||
n_estimators=200,
|
||||
max_depth=None,
|
||||
learning_rate=0.05,
|
||||
reg_alpha=0.1,
|
||||
reg_lambda=0.1,
|
||||
subsample=0.8,
|
||||
colsample_bytree=0.8,
|
||||
random_state=42
|
||||
)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
# Optional: LightGBM
|
||||
try:
|
||||
from lightgbm import LGBMRegressor
|
||||
models["LightGBM"] = LGBMRegressor(
|
||||
n_estimators=200,
|
||||
max_depth=None,
|
||||
learning_rate=0.05,
|
||||
reg_alpha=0.1,
|
||||
reg_lambda=0.1,
|
||||
subsample=0.8,
|
||||
colsample_bytree=0.8,
|
||||
random_state=42
|
||||
)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
return models
|
||||
@@ -1,37 +0,0 @@
|
||||
'''
|
||||
Filename: plotting.py
|
||||
Path: /home/netoa/Desktop/ISR/scripts
|
||||
Created Date: Monday March 24th 2025
|
||||
Author: Andre Neto
|
||||
-----
|
||||
Last Modified: Tue Mar 25 2025
|
||||
Modified By: Andre Neto
|
||||
-----
|
||||
Copyright (c) 2025 Institute of Systems and Robotics
|
||||
'''
|
||||
|
||||
import os
|
||||
import matplotlib.pyplot as plt
|
||||
import seaborn as sns
|
||||
import numpy as np
|
||||
|
||||
def plot_fusion_result(y_true, y_pred, model_name, output_dir):
|
||||
"""Scatter plot: MOS vs predicted fused score."""
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
plt.figure(figsize=(6, 6))
|
||||
sns.scatterplot(x=y_pred, y=y_true, alpha=0.6, color="blue")
|
||||
z = np.polyfit(y_pred, y_true, 1)
|
||||
p = np.poly1d(z)
|
||||
plt.plot(y_pred, p(y_pred), color="red", linewidth=2)
|
||||
|
||||
plt.xlabel("Predicted Fused Score")
|
||||
plt.ylabel("MOS")
|
||||
plt.title(f"MOS vs Predicted ({model_name})")
|
||||
plt.grid(True, linestyle="--", alpha=0.5)
|
||||
plt.tight_layout()
|
||||
|
||||
plt.savefig(os.path.join(output_dir, f"fusion_plot_{model_name}.png"), dpi=300)
|
||||
plt.savefig(os.path.join(output_dir, f"fusion_plot_{model_name}.eps"), dpi=300)
|
||||
|
||||
plt.close()
|
||||
@@ -1,20 +0,0 @@
|
||||
'''
|
||||
Filename: utils.py
|
||||
Path: /home/netoa/Desktop/ISR/scripts
|
||||
Created Date: Monday March 24th 2025
|
||||
Author: Andre Neto
|
||||
-----
|
||||
Last Modified: Tue Mar 25 2025
|
||||
Modified By: Andre Neto
|
||||
-----
|
||||
Copyright (c) 2025 Institute of Systems and Robotics
|
||||
'''
|
||||
|
||||
import os
|
||||
import pandas as pd
|
||||
|
||||
def save_fused_scores(predictions, filenames, output_path):
|
||||
"""Save fused quality scores with associated filenames to CSV."""
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
df = pd.DataFrame({"file_name": filenames, "fused_score": predictions})
|
||||
df.to_csv(output_path, index=False)
|
||||
@@ -0,0 +1,103 @@
|
||||
import os
|
||||
import pandas as pd
|
||||
import matplotlib.pyplot as plt
|
||||
import seaborn as sns
|
||||
import numpy as np
|
||||
from scipy.stats import pearsonr, spearmanr
|
||||
from statsmodels.nonparametric.smoothers_lowess import lowess
|
||||
|
||||
|
||||
def load_split_data(split: str) -> pd.DataFrame:
|
||||
print(f"loading IQA data for split: '{split}'")
|
||||
iqa_path = f"data/labeled/{split}/iqa.csv"
|
||||
mos_path = f"data/labeled/{split}/mos_debiased.csv"
|
||||
|
||||
print(f"- reading objective IQA from: {iqa_path}")
|
||||
iqa_df = pd.read_csv(iqa_path)
|
||||
|
||||
if "PIQE" in iqa_df.columns:
|
||||
iqa_df = iqa_df.drop(columns=["PIQE"])
|
||||
|
||||
print(f"- reading subjective MOS from: {mos_path}")
|
||||
mos_df = pd.read_csv(mos_path)
|
||||
|
||||
print("- merging on 'file_name'")
|
||||
merged_df = iqa_df.merge(mos_df, on="file_name", how="inner")
|
||||
print(f"- merged dataframe shape: {merged_df.shape}")
|
||||
return merged_df
|
||||
|
||||
|
||||
def compute_iqa_statistics(df: pd.DataFrame) -> pd.DataFrame:
|
||||
print("computing correlation and error metrics:")
|
||||
metrics = df.drop(columns=["file_name", "mos"])
|
||||
mos = df["mos"].values
|
||||
|
||||
results = []
|
||||
for metric in metrics.columns:
|
||||
print(f"- {metric}")
|
||||
values = df[metric].values
|
||||
plcc, _ = pearsonr(values, mos)
|
||||
srcc, _ = spearmanr(values, mos)
|
||||
mse = np.mean((values - mos) ** 2)
|
||||
mae = np.mean(np.abs(values - mos))
|
||||
avg = (plcc + srcc) / 2
|
||||
results.append((metric, plcc, srcc, mse, mae, avg))
|
||||
|
||||
results_df = pd.DataFrame(results, columns=["Metric", "PLCC", "SRCC", "MSE", "MAE", "PLSR_avg"])
|
||||
return results_df.sort_values(by="PLSR_avg", ascending=False)
|
||||
|
||||
|
||||
def plot_iqa_scatter(df: pd.DataFrame, metrics_df: pd.DataFrame, output_dir: str, file_name: str):
|
||||
print("plotting scatter plots ordered by PLCC+SRCC average")
|
||||
ranked_metrics = metrics_df["Metric"].tolist()
|
||||
cols = 5
|
||||
rows = -(-len(ranked_metrics) // cols)
|
||||
|
||||
fig, axes = plt.subplots(rows, cols, figsize=(16, rows * 3))
|
||||
axes = axes.flatten()
|
||||
|
||||
for i, metric in enumerate(ranked_metrics):
|
||||
sns.scatterplot(x=df[metric], y=df["mos"], ax=axes[i], alpha=0.7)
|
||||
|
||||
sorted_idx = df[metric].argsort()
|
||||
x_sorted = df[metric].iloc[sorted_idx].values
|
||||
y_sorted = df["mos"].iloc[sorted_idx].values
|
||||
smoothed = lowess(y_sorted, x_sorted, frac=0.3)
|
||||
|
||||
axes[i].plot(smoothed[:, 0], smoothed[:, 1], color="red", linewidth=3)
|
||||
axes[i].set_title(metric, fontsize=22)
|
||||
axes[i].set_xlabel("IQA Score")
|
||||
axes[i].set_ylabel("MOS")
|
||||
|
||||
for j in range(len(ranked_metrics), len(axes)):
|
||||
fig.delaxes(axes[j])
|
||||
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
plt.tight_layout()
|
||||
plt.savefig(os.path.join(output_dir, f"{file_name}.png"), dpi=300)
|
||||
plt.savefig(os.path.join(output_dir, f"{file_name}.pdf"), dpi=300)
|
||||
plt.close()
|
||||
print(f"- scatter plots saved to: {output_dir}")
|
||||
|
||||
|
||||
def save_iqa_results(results_df: pd.DataFrame, output_path: str):
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
results_df.drop(columns=["PLSR_avg"]).to_csv(output_path, index=False)
|
||||
print(f"- full correlation results saved to: {output_path}")
|
||||
|
||||
|
||||
def main(split: str = "train"):
|
||||
print(f"starting IQA correlation analysis for split: '{split}'")
|
||||
df = load_split_data(split)
|
||||
results = compute_iqa_statistics(df)
|
||||
|
||||
out_dir = f"results/iqa_correlation/{split}"
|
||||
plot_iqa_scatter(df, results, out_dir, "scatter_ranked")
|
||||
save_iqa_results(results, os.path.join(out_dir, "correlation_results.csv"))
|
||||
print("IQA correlation analysis complete.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
split = sys.argv[1] if len(sys.argv) > 1 else "train"
|
||||
main(split)
|
||||
@@ -1,80 +0,0 @@
|
||||
'''
|
||||
Filename: evaluation.py
|
||||
Path: /home/netoa/Desktop/ISR/scripts/nr_fusion
|
||||
Created Date: Monday March 24th 2025
|
||||
Author: Andre Neto
|
||||
-----
|
||||
Last Modified: Tue Mar 25 2025
|
||||
Modified By: Andre Neto
|
||||
-----
|
||||
Copyright (c) 2025 Institute of Systems and Robotics
|
||||
'''
|
||||
|
||||
import os
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
from sklearn.metrics import mean_squared_error, mean_absolute_error
|
||||
from scipy.stats import pearsonr, spearmanr
|
||||
|
||||
|
||||
def evaluate_and_plot(y_true, y_pred, output_dir, show_trend=True):
|
||||
"""
|
||||
Compute evaluation metrics and generate scatter plot.
|
||||
|
||||
Args:
|
||||
y_true (array-like): Ground truth pseudo-MOS values.
|
||||
y_pred (array-like): Predicted pseudo-MOS values.
|
||||
output_dir (str): Directory to save plots.
|
||||
show_trend (bool): Whether to include a fitted trendline.
|
||||
"""
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
# Plot
|
||||
plt.figure(figsize=(7, 7))
|
||||
plt.scatter(y_true, y_pred, alpha=0.6, color="darkorange", s=20)
|
||||
|
||||
# Diagonal reference
|
||||
min_val = min(min(y_true), min(y_pred))
|
||||
max_val = max(max(y_true), max(y_pred))
|
||||
plt.plot([min_val, max_val], [min_val, max_val], '--', color="gray", alpha=0.7)
|
||||
|
||||
# Optional trendline
|
||||
if show_trend:
|
||||
z = np.polyfit(y_true, y_pred, 1)
|
||||
p = np.poly1d(z)
|
||||
plt.plot(y_true, p(y_true), color="blue", linewidth=1.5, label="Trendline")
|
||||
plt.legend()
|
||||
|
||||
plt.xlabel("Fusion_RF (pseudo-MOS)")
|
||||
plt.ylabel("NR Prediction")
|
||||
plt.title("NR IQA Prediction vs. Fusion_RF")
|
||||
plt.grid(True, linestyle="--", alpha=0.4)
|
||||
plt.tight_layout()
|
||||
plt.savefig(os.path.join(output_dir, "nr_vs_fusion_rf.png"), dpi=300)
|
||||
plt.savefig(os.path.join(output_dir, "nr_vs_fusion_rf.eps"), dpi=300)
|
||||
|
||||
plt.close()
|
||||
|
||||
|
||||
def compute_correlation_scores(y_true, y_pred):
|
||||
"""
|
||||
Compute correlation scores between ground truth and predicted values.
|
||||
|
||||
Args:
|
||||
y_true (array-like): Ground truth pseudo-MOS scores.
|
||||
y_pred (array-like): Predicted scores from NR IQA model.
|
||||
|
||||
Returns:
|
||||
dict: Dictionary with PLCC and SRCC scores.
|
||||
"""
|
||||
|
||||
# Compute metrics
|
||||
mse = mean_squared_error(y_true, y_pred)
|
||||
mae = mean_absolute_error(y_true, y_pred)
|
||||
plcc, _ = pearsonr(y_true, y_pred)
|
||||
srcc, _ = spearmanr(y_true, y_pred)
|
||||
|
||||
return {"PLCC": plcc,
|
||||
"SRCC": srcc,
|
||||
"MSE": mse,
|
||||
"MAE": mae}
|
||||
@@ -1,115 +0,0 @@
|
||||
"""
|
||||
Feature extraction for No-Reference IQA using deep facial feature embeddings.
|
||||
"""
|
||||
|
||||
import os
|
||||
import numpy as np
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from torchvision import models
|
||||
from torchvision import transforms
|
||||
from PIL import Image
|
||||
from tqdm import tqdm
|
||||
from facenet_pytorch import InceptionResnetV1
|
||||
|
||||
|
||||
def extract_features(df, image_dir, encoder="resnet"):
|
||||
""" Extract deep features from distorted images using a selected encoder. """
|
||||
|
||||
if encoder == "resnet":
|
||||
return extract_resnet_features(df, image_dir)
|
||||
elif encoder == "facenet":
|
||||
return extract_facenet_features(df, image_dir)
|
||||
else:
|
||||
raise ValueError(f"Invalid encoder: {encoder}.")
|
||||
|
||||
|
||||
def extract_facenet_features(df, image_dir):
|
||||
""" Extract deep features from distorted images using a face embedding network (FaceNet). """
|
||||
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
model = InceptionResnetV1(pretrained='vggface2').eval().to(device)
|
||||
|
||||
preprocess = transforms.Compose([
|
||||
transforms.Resize((160, 160)),
|
||||
transforms.ToTensor(),
|
||||
transforms.Normalize([0.5], [0.5])
|
||||
])
|
||||
|
||||
features = []
|
||||
labels = []
|
||||
filenames = []
|
||||
|
||||
for _, row in tqdm(df.iterrows(), total=len(df), desc="Extracting FaceNet features"):
|
||||
fname = row["file_name"]
|
||||
img_path = os.path.join(image_dir, f'{fname}.jpg')
|
||||
if not os.path.exists(img_path):
|
||||
print(f"[WARN] File not found: {img_path}")
|
||||
continue
|
||||
|
||||
try:
|
||||
img = Image.open(img_path).convert("RGB")
|
||||
input_tensor = preprocess(img).unsqueeze(0).to(device)
|
||||
with torch.no_grad():
|
||||
embedding = model(input_tensor).cpu().numpy().flatten()
|
||||
|
||||
if np.isnan(embedding).any():
|
||||
raise ValueError("Embedding contains NaN")
|
||||
|
||||
features.append(embedding)
|
||||
labels.append(row["fusion_rf"])
|
||||
filenames.append(fname)
|
||||
except (FileNotFoundError, ValueError, OSError) as e:
|
||||
print(f"[WARN] Skipping {fname}: {e}")
|
||||
|
||||
if len(features) == 0:
|
||||
raise RuntimeError("No features extracted. Check image paths or model setup.")
|
||||
|
||||
x = np.array(features)
|
||||
y = np.array(labels)
|
||||
return x, y, filenames
|
||||
|
||||
|
||||
def extract_resnet_features(df, image_dir):
|
||||
""" Extract ResNet features from distorted images. """
|
||||
|
||||
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
model = models.resnet18(pretrained=True)
|
||||
model.fc = nn.Identity() # Remove final classification layer
|
||||
model.eval().to(device)
|
||||
|
||||
preprocess = transforms.Compose([
|
||||
transforms.Resize((224, 224)),
|
||||
transforms.ToTensor(),
|
||||
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
|
||||
])
|
||||
|
||||
features, labels, filenames = [], [], []
|
||||
|
||||
for _, row in tqdm(df.iterrows(), total=len(df), desc="Extracting ResNet features"):
|
||||
fname = row["file_name"]
|
||||
img_path = os.path.join(image_dir, f'{fname}.jpg')
|
||||
if not os.path.exists(img_path):
|
||||
print(f"[WARN] File not found: {img_path}")
|
||||
continue
|
||||
|
||||
try:
|
||||
img = Image.open(img_path).convert("RGB")
|
||||
input_tensor = preprocess(img).unsqueeze(0).to(device)
|
||||
with torch.no_grad():
|
||||
embedding = model(input_tensor).cpu().numpy().flatten()
|
||||
|
||||
if np.isnan(embedding).any():
|
||||
raise ValueError("Embedding contains NaN")
|
||||
|
||||
features.append(embedding)
|
||||
labels.append(row["fusion_rf"])
|
||||
filenames.append(fname)
|
||||
except (FileNotFoundError, ValueError, OSError) as e:
|
||||
print(f"[WARN] Skipping {fname}: {e}")
|
||||
|
||||
if len(features) == 0:
|
||||
raise RuntimeError("No features extracted. Check image paths or model setup.")
|
||||
|
||||
return np.array(features), np.array(labels), filenames
|
||||
@@ -1,40 +0,0 @@
|
||||
'''
|
||||
Filename: models.py
|
||||
Path: /home/netoa/Desktop/ISR/scripts/nr_fusion
|
||||
Created Date: Monday March 24th 2025
|
||||
Author: Andre Neto
|
||||
-----
|
||||
Last Modified: Mon Mar 24 2025
|
||||
Modified By: Andre Neto
|
||||
-----
|
||||
Copyright (c) 2025 Institute of Systems and Robotics
|
||||
'''
|
||||
|
||||
|
||||
from sklearn.ensemble import RandomForestRegressor
|
||||
from sklearn.model_selection import cross_val_predict
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
|
||||
|
||||
def train_regressor(x, y):
|
||||
"""
|
||||
Train and cross-validate a RandomForest regressor.
|
||||
|
||||
Args:
|
||||
X (np.ndarray): Feature matrix.
|
||||
y (np.ndarray): Target values (pseudo-MOS).
|
||||
|
||||
Returns:
|
||||
y_pred (np.ndarray): Cross-validated predictions.
|
||||
model (Regressor): Trained RandomForest model.
|
||||
scaler (StandardScaler): Feature normalizer.
|
||||
"""
|
||||
scaler = StandardScaler()
|
||||
x_scaled = scaler.fit_transform(x)
|
||||
|
||||
model = RandomForestRegressor(n_estimators=100, random_state=42)
|
||||
y_pred = cross_val_predict(model, x_scaled, y, cv=5)
|
||||
|
||||
model.fit(x_scaled, y)
|
||||
|
||||
return y_pred, model, scaler
|
||||
@@ -1,184 +0,0 @@
|
||||
"""
|
||||
Fusion Pipeline Script
|
||||
|
||||
This module runs a full regression-based fusion process:
|
||||
1. Selects top-k IQA metrics based on PLCC.
|
||||
2. Normalizes the selected features.
|
||||
3. Trains multiple regression models (linear and nonlinear).
|
||||
4. Evaluates each model using cross-validation.
|
||||
5. Saves predicted fused scores and visualization plots.
|
||||
6. Applies trained model to all available images and saves full prediction CSV.
|
||||
"""
|
||||
|
||||
import os
|
||||
import pandas as pd
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
from sklearn.preprocessing import StandardScaler
|
||||
from sklearn.ensemble import RandomForestRegressor
|
||||
from scipy.stats import pearsonr, spearmanr
|
||||
|
||||
from fr_fusion.models import get_models
|
||||
from fr_fusion.evaluation import evaluate_model_cv
|
||||
from fr_fusion.plotting import plot_fusion_result
|
||||
from fr_fusion.utils import save_fused_scores
|
||||
|
||||
def plot_rf_feature_importance(top_metrics, x_scaled, y, output_dir):
|
||||
"""Plot feature importances from Random Forest regressor."""
|
||||
|
||||
|
||||
rf = RandomForestRegressor(n_estimators=100, random_state=42)
|
||||
rf.fit(x_scaled, y)
|
||||
importances = rf.feature_importances_
|
||||
|
||||
feature_importance_df = pd.DataFrame({
|
||||
"Metric": top_metrics,
|
||||
"Importance": importances
|
||||
}).sort_values(by="Importance", ascending=False)
|
||||
|
||||
plt.figure(figsize=(8, 5))
|
||||
plt.barh(feature_importance_df["Metric"], feature_importance_df["Importance"], color="darkgreen")
|
||||
plt.xlabel("Feature Importance")
|
||||
plt.ylabel("FR-IQA Metrics")
|
||||
plt.title("Random Forest Feature Importances")
|
||||
plt.gca().invert_yaxis()
|
||||
plt.grid(axis="x", linestyle="--", alpha=0.6)
|
||||
plt.tight_layout()
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
plt.savefig(os.path.join(output_dir, "ffr_rf_feature_importance.png"), dpi=300)
|
||||
plt.savefig(os.path.join(output_dir, "ffr_rf_feature_importance.eps"), dpi=300)
|
||||
plt.close()
|
||||
|
||||
|
||||
|
||||
def plot_model_comparison(score_dict, output_dir):
|
||||
"""Generate individual subplots for each metric to compare models."""
|
||||
df = pd.DataFrame(score_dict).T
|
||||
|
||||
_, axes = plt.subplots(2, 2, figsize=(14, 10))
|
||||
axes = axes.flatten()
|
||||
|
||||
metrics = ["PLCC", "SRCC", "MSE", "MAE"]
|
||||
colors = ["steelblue", "darkorange", "indianred", "seagreen"]
|
||||
|
||||
for i, metric in enumerate(metrics):
|
||||
df[metric].sort_values(ascending=metric in ["MSE", "MAE"]).plot.bar(
|
||||
ax=axes[i], color=colors[i])
|
||||
axes[i].set_title(f"{metric} Comparison Across Models")
|
||||
axes[i].set_ylabel(metric)
|
||||
axes[i].set_xlabel("Model")
|
||||
axes[i].tick_params(axis='x', rotation=45)
|
||||
axes[i].grid(axis="y", linestyle="--", alpha=0.5)
|
||||
|
||||
best_idx = df[metric].idxmax() if metric in ["PLCC", "SRCC"] else df[metric].idxmin()
|
||||
axes[i].annotate("Best", xy=(list(df.index).index(best_idx), df[metric][best_idx]),
|
||||
xytext=(0, 5), textcoords="offset points",
|
||||
ha='center', va='bottom', fontsize=9, color='green', weight='bold')
|
||||
|
||||
plt.tight_layout()
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
plt.savefig(os.path.join(output_dir, "model_comparison.png"), dpi=300)
|
||||
plt.savefig(os.path.join(output_dir, "model_comparison.eps"), dpi=300)
|
||||
|
||||
plt.close()
|
||||
|
||||
def run_fusion_pipeline(merged_df: pd.DataFrame, results_df: pd.DataFrame, top_k: int = 5,
|
||||
output_dir: str = "results/ffr_metric") -> None:
|
||||
"""
|
||||
Run fusion pipeline with different regressors using top-k ranked IQA metrics.
|
||||
"""
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
# 1. Select top-k metrics by PLCC
|
||||
selected_metrics = results_df.head(top_k).index.tolist()
|
||||
x = merged_df[selected_metrics]
|
||||
y = merged_df["mos"]
|
||||
filenames = merged_df["file_name"]
|
||||
|
||||
# 2. Normalize features
|
||||
scaler = StandardScaler()
|
||||
x_scaled = pd.DataFrame(scaler.fit_transform(x), columns=x.columns)
|
||||
|
||||
# 3. Train and evaluate models
|
||||
models = get_models()
|
||||
score_summary = {}
|
||||
|
||||
for name, model in models.items():
|
||||
print(f"\nRunning model: {name}")
|
||||
scores = evaluate_model_cv(model, x_scaled, y, cv=5)
|
||||
print(f"Scores: {scores}")
|
||||
score_summary[name] = scores
|
||||
|
||||
model.fit(x_scaled, y)
|
||||
y_pred = model.predict(x_scaled)
|
||||
|
||||
score_path = os.path.join(output_dir, f"fused_scores_{name}.csv")
|
||||
save_fused_scores(y_pred, filenames, score_path)
|
||||
plot_fusion_result(y, y_pred, name, output_dir)
|
||||
|
||||
# If RandomForest, apply to all available data
|
||||
if name == "RandomForest":
|
||||
print("\nApplying LinearRegression to full objective dataset...")
|
||||
full_df = pd.read_csv("results/sheets/iqa_objective.csv")
|
||||
if not all(metric in full_df.columns for metric in selected_metrics):
|
||||
print("Some metrics missing in full objective data. Skipping.")
|
||||
continue
|
||||
|
||||
x_all = full_df[selected_metrics]
|
||||
x_all_scaled = scaler.transform(x_all)
|
||||
y_all_pred = model.predict(x_all_scaled)
|
||||
|
||||
full_df["fusion_rf"] = y_all_pred
|
||||
fusion_df = full_df[["file_name", "fusion_rf"]]
|
||||
fusion_df.to_csv(os.path.join(output_dir, "fusion_scores_all.csv"), index=False)
|
||||
print(f"Saved full fusion scores to {output_dir}/fusion_scores_all.csv")
|
||||
|
||||
# 4. Generate comparison plot
|
||||
plot_model_comparison(score_summary, output_dir)
|
||||
|
||||
# 5. Save all model scores to CSV
|
||||
score_summary_df = pd.DataFrame(score_summary)
|
||||
score_summary_df.index.name = "Model"
|
||||
score_summary_df.to_csv(os.path.join(output_dir, "model_scores.csv"))
|
||||
print(f"\nSaved model evaluation scores to {output_dir}/model_scores.csv")
|
||||
|
||||
# 6. Plot Random Forest feature importances using top-5 metrics
|
||||
plot_rf_feature_importance(selected_metrics, x_scaled, y, output_dir)
|
||||
|
||||
print("\nFusion pipeline completed.")
|
||||
|
||||
|
||||
def compute_ranking(merged_df):
|
||||
""" Compute PLCC and SRCC rankings for each IQA metric. """
|
||||
|
||||
metrics = merged_df.drop(columns=["file_name", "mos"])
|
||||
plcc, srcc = {}, {}
|
||||
for metric in metrics.columns:
|
||||
plcc[metric], _ = pearsonr(merged_df[metric], merged_df["mos"])
|
||||
srcc[metric], _ = spearmanr(merged_df[metric], merged_df["mos"])
|
||||
|
||||
results_df = pd.DataFrame.from_dict(plcc, orient="index", columns=["PLCC"])
|
||||
results_df["SRCC"] = pd.Series(srcc)
|
||||
results_df = results_df.sort_values(by="PLCC", ascending=False)
|
||||
return results_df
|
||||
|
||||
def main():
|
||||
""" Main function to run the fusion pipeline with top-k ranked IQA metrics. """
|
||||
# Input paths
|
||||
objective_path = "results/sheets/iqa_objective.csv"
|
||||
subjective_path = "results/sheets/iqa_subjective.csv"
|
||||
|
||||
# Load and merge data
|
||||
obj_df = pd.read_csv(objective_path)
|
||||
subj_df = pd.read_csv(subjective_path)[["file_name", "mos"]]
|
||||
merged_df = obj_df.merge(subj_df, on="file_name", how="inner")
|
||||
|
||||
# Compute PLCC/SRCC rankings
|
||||
results_df = compute_ranking(merged_df)
|
||||
|
||||
# Run fusion
|
||||
run_fusion_pipeline(merged_df, results_df, top_k=5)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,595 @@
|
||||
'''
|
||||
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()
|
||||
@@ -0,0 +1,416 @@
|
||||
'''
|
||||
Filename: pipeline_norefernce.py
|
||||
Path: /home/netoa/Desktop/ISR/scripts
|
||||
Created Date: Friday May 16th 2025
|
||||
Author: Andre Neto
|
||||
-----
|
||||
Last Modified: Fri May 23 2025
|
||||
Modified By: Andre Neto
|
||||
-----
|
||||
Copyright (c) 2025 Institute of Systems and Robotics
|
||||
'''
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.optim as optim
|
||||
from tqdm import tqdm
|
||||
import pandas as pd
|
||||
from torch.utils.data import Dataset, DataLoader
|
||||
from torchvision import transforms
|
||||
from PIL import Image
|
||||
|
||||
from sklearn.metrics import mean_squared_error, mean_absolute_error
|
||||
from scipy.stats import pearsonr, spearmanr
|
||||
|
||||
from torchinfo import summary
|
||||
import torchvision.models as models
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import seaborn as sns
|
||||
|
||||
# pylint: disable=line-too-long
|
||||
|
||||
|
||||
class NoReferenceModel:
|
||||
"""
|
||||
A class for training a no-reference image quality assessment (NR-IQA) model
|
||||
using pseudo mean opinion scores (MOS) and evaluating it on a test set.
|
||||
"""
|
||||
|
||||
|
||||
def __init__(self, pseudo_mos_csv, k, train_dirs, test_dir, output_dir):
|
||||
"""
|
||||
Initialize the NR-IQA model with paths to training and evaluation data.
|
||||
|
||||
Args:
|
||||
pseudo_mos_csv (str or Path): Path to the CSV file containing pseudo-MOS labels.
|
||||
train_dirs (List[str or Path]): List of directories with images for training.
|
||||
test_dir (str or Path): Directory containing the test images and mos.csv.
|
||||
output_dir (str or Path): Path to save model cp, pred, and evaluation results.
|
||||
"""
|
||||
|
||||
self.pseudo_mos_csv = Path(pseudo_mos_csv)
|
||||
self.train_dirs = [Path(d) for d in train_dirs]
|
||||
self.test_dir = Path(test_dir)
|
||||
self.output_dir = Path(output_dir)
|
||||
self.output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||
|
||||
self.batch_size = 16
|
||||
self.num_workers = 4
|
||||
self.train_loader = None
|
||||
self.test_loader = None
|
||||
self.test_mos = None
|
||||
self.model = None
|
||||
|
||||
|
||||
def load_data(self):
|
||||
"""
|
||||
Load and preprocess the training and testing data.
|
||||
|
||||
This method:
|
||||
- Loads image paths and scores (both pseudo and real) from training directories
|
||||
- Loads test images and their real MOS scores
|
||||
- Applies transformations (resize, normalization)
|
||||
- Constructs PyTorch DataLoaders for both sets
|
||||
"""
|
||||
print("Loading training and testing data...")
|
||||
|
||||
transform = transforms.Compose([
|
||||
transforms.Resize((224, 224)),
|
||||
transforms.ToTensor(),
|
||||
transforms.Normalize(mean=[0.485, 0.456, 0.406],
|
||||
std=[0.229, 0.224, 0.225])
|
||||
])
|
||||
|
||||
# Load pseudo-MOS CSV
|
||||
df_pseudo = pd.read_csv(self.pseudo_mos_csv)
|
||||
pseudo_dict = dict(zip(df_pseudo["file_name"], df_pseudo["pseudo_mos"]))
|
||||
|
||||
# Load true MOS if available (from labeled/train)
|
||||
labeled_train_mos_path = Path("data/labeled/train/mos_debiased.csv")
|
||||
if labeled_train_mos_path.exists():
|
||||
df_true = pd.read_csv(labeled_train_mos_path)
|
||||
pseudo_dict.update(dict(zip(df_true["file_name"], df_true["mos"])))
|
||||
print(f"- Loaded {len(df_true)} true MOS entries from labeled/train")
|
||||
|
||||
# Combine training images from all dirs
|
||||
train_samples = []
|
||||
for train_dir in self.train_dirs:
|
||||
for image_path in Path(train_dir).glob("*.jpg"):
|
||||
fname = image_path.name
|
||||
if fname in pseudo_dict:
|
||||
train_samples.append((image_path, pseudo_dict[fname]))
|
||||
|
||||
self.train_loader = DataLoader(
|
||||
MOSDataset(train_samples, transform),
|
||||
batch_size=self.batch_size,
|
||||
shuffle=True,
|
||||
num_workers=self.num_workers
|
||||
)
|
||||
|
||||
# Load test MOS
|
||||
df_test = pd.read_csv(self.test_dir / "mos_debiased.csv")
|
||||
test_dict = dict(zip(df_test["file_name"], df_test["mos"]))
|
||||
|
||||
test_samples = []
|
||||
for image_path in (self.test_dir).glob("*.jpg"):
|
||||
fname = image_path.name
|
||||
if fname in test_dict:
|
||||
test_samples.append((image_path, test_dict[fname]))
|
||||
|
||||
self.test_mos = [s[1] for s in test_samples]
|
||||
self.test_loader = DataLoader(
|
||||
MOSDataset(test_samples, transform),
|
||||
batch_size=self.batch_size,
|
||||
shuffle=False,
|
||||
num_workers=self.num_workers
|
||||
)
|
||||
|
||||
print(f"- Loaded {len(train_samples)} total training samples (pseudo + real)")
|
||||
print(f"- Loaded {len(test_samples)} test samples")
|
||||
print(f"Files in mos_debiased: {len(df_test)}")
|
||||
print(f"Matching image files: {len(test_samples)}")
|
||||
|
||||
|
||||
def build_model(self):
|
||||
"""
|
||||
Build and initialize the CNN-based NR-IQA model.
|
||||
|
||||
The model consists of:
|
||||
- A ResNet18 backbone pretrained on ImageNet
|
||||
- A fully connected regression head (MLP) that predicts a continuous MOS value
|
||||
|
||||
All layers are trainable (fine-tuning enabled).
|
||||
The model is moved to the appropriate device (GPU or CPU).
|
||||
"""
|
||||
print("Building ResNet18-based NR-IQA model...")
|
||||
|
||||
# Load pretrained ResNet18
|
||||
resnet = models.resnet18(pretrained=True)
|
||||
|
||||
# Replace the final layer with an MLP regressor
|
||||
resnet.fc = nn.Sequential(
|
||||
nn.Linear(512, 256),
|
||||
nn.ReLU(),
|
||||
nn.Dropout(0.4),
|
||||
nn.Linear(256, 1)
|
||||
)
|
||||
|
||||
self.model = resnet.to(self.device)
|
||||
|
||||
# Print model summary
|
||||
print("Model summary:")
|
||||
summary(self.model, input_size=(1, 3, 1350, 1350), device=str(self.device))
|
||||
|
||||
print(f"- Model ready on device: {self.device}")
|
||||
|
||||
|
||||
def load_model(self):
|
||||
"""
|
||||
Loads the saved model weights into a new instance of the model.
|
||||
Assumes the model architecture is the same as the one used during training.
|
||||
"""
|
||||
print("Loading model from checkpoint...")
|
||||
|
||||
self.build_model() # Rebuild architecture
|
||||
model_path = self.output_dir / "model.pth"
|
||||
self.model.load_state_dict(torch.load(model_path, map_location=self.device))
|
||||
self.model.eval()
|
||||
print(f"Model loaded from: {model_path}")
|
||||
|
||||
|
||||
def train(self, n_epochs=30, lr=1e-4):
|
||||
"""
|
||||
Train the NR-IQA model using the combined training dataset.
|
||||
|
||||
This method performs standard supervised training using MSE loss and Adam optimizer.
|
||||
After training, the final model is saved to disk, along with a CSV containing the
|
||||
training loss per epoch.
|
||||
|
||||
Args:
|
||||
n_epochs (int): Number of training epochs.
|
||||
lr (float): Learning rate for the optimizer.
|
||||
"""
|
||||
print("Starting training...")
|
||||
|
||||
self.model.train()
|
||||
|
||||
criterion = nn.MSELoss()
|
||||
optimizer = optim.Adam(self.model.parameters(), lr=lr)
|
||||
|
||||
history = []
|
||||
|
||||
for epoch in range(n_epochs):
|
||||
running_loss = 0.0
|
||||
for images, targets, _ in tqdm(self.train_loader, desc=f"Epoch {epoch+1}/{n_epochs}"):
|
||||
images = images.to(self.device)
|
||||
targets = targets.to(self.device).unsqueeze(1)
|
||||
|
||||
optimizer.zero_grad()
|
||||
outputs = self.model(images)
|
||||
loss = criterion(outputs, targets)
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
|
||||
running_loss += loss.item() * images.size(0)
|
||||
|
||||
epoch_loss = running_loss / len(self.train_loader.dataset)
|
||||
history.append({"epoch": epoch+1, "loss": epoch_loss})
|
||||
print(f"Epoch {epoch+1}/{n_epochs} - Loss: {epoch_loss:.4f}")
|
||||
|
||||
# Save model and training loss history
|
||||
model_path = self.output_dir / "model.pth"
|
||||
torch.save(self.model.state_dict(), model_path)
|
||||
print(f"Model saved to: {model_path}")
|
||||
|
||||
loss_df = pd.DataFrame(history)
|
||||
loss_df.to_csv(self.output_dir / "train_loss.csv", index=False)
|
||||
print(f"Training loss saved to: {self.output_dir / 'train_loss.csv'}")
|
||||
|
||||
|
||||
def plot_predictions(self, pred_df: pd.DataFrame, output_path: Path):
|
||||
"""
|
||||
Generates and saves a scatter plot of predicted vs real MOS.
|
||||
"""
|
||||
|
||||
plt.rcParams.update({"font.size": 16})
|
||||
|
||||
plt.figure(figsize=(7, 5))
|
||||
|
||||
plt.xlim(0, 100)
|
||||
plt.ylim(0, 100)
|
||||
sns.scatterplot(x="mos", y="predicted", data=pred_df, alpha=0.7)
|
||||
sns.regplot(x="mos", y="predicted", data=pred_df, scatter=False, color="red", label="Linear fit")
|
||||
|
||||
# Ideal 1:1 trend line
|
||||
plt.plot([0, 100], [0, 100], 'k--', label="y = x", color="gray")
|
||||
|
||||
# MOS test set
|
||||
# NR train set
|
||||
plt.title("pMOS-FRLL Predictions vs NR train set")
|
||||
|
||||
# Ground-truth MOS
|
||||
# Pseudo-MOS & Ground-truth MOS
|
||||
plt.xlabel("Pseudo-MOS & Ground-truth MOS")
|
||||
plt.ylabel("Predicted MOS")
|
||||
plt.legend()
|
||||
plt.grid(True)
|
||||
plt.tight_layout()
|
||||
|
||||
plot_file = output_path / "predictions_train.pdf"
|
||||
|
||||
plt.savefig(plot_file, dpi=300)
|
||||
plt.close()
|
||||
print(f"- Prediction plot saved to: {plot_file}")
|
||||
|
||||
|
||||
def evaluate(self):
|
||||
"""
|
||||
Evaluate the trained model on the labeled/test set with real MOS values.
|
||||
|
||||
This method:
|
||||
- Performs inference on the test set
|
||||
- Computes PLCC, SRCC, MSE, and MAE between predicted and real MOS
|
||||
- Saves predictions and metrics to disk
|
||||
"""
|
||||
print("Evaluating model on test set...")
|
||||
|
||||
self.model.eval()
|
||||
preds = []
|
||||
fnames = []
|
||||
|
||||
with torch.no_grad():
|
||||
for images, _, filenames in self.test_loader:
|
||||
images = images.to(self.device)
|
||||
outputs = self.model(images).squeeze(1).cpu().numpy()
|
||||
preds.extend(outputs)
|
||||
fnames.extend(filenames)
|
||||
|
||||
y_true = np.array(self.test_mos)
|
||||
y_pred = np.array(preds)
|
||||
|
||||
# Compute metrics
|
||||
plcc, _ = pearsonr(y_true, y_pred)
|
||||
srcc, _ = spearmanr(y_true, y_pred)
|
||||
mse = mean_squared_error(y_true, y_pred)
|
||||
mae = mean_absolute_error(y_true, y_pred)
|
||||
|
||||
print(f" PLCC = {plcc:.4f} | SRCC = {srcc:.4f} | MSE = {mse:.4f} | MAE = {mae:.4f}")
|
||||
|
||||
# Save predictions
|
||||
pred_df = pd.DataFrame({
|
||||
"file_name": fnames,
|
||||
"predicted": y_pred,
|
||||
"mos": y_true
|
||||
})
|
||||
pred_path = self.output_dir / "predictions.csv"
|
||||
pred_df.to_csv(pred_path, index=False)
|
||||
print(f"- Predictions saved to: {pred_path}")
|
||||
|
||||
# Save metrics
|
||||
metrics_df = pd.DataFrame([{
|
||||
"PLCC": plcc,
|
||||
"SRCC": srcc,
|
||||
"MSE": mse,
|
||||
"MAE": mae
|
||||
}])
|
||||
metrics_df.to_csv(self.output_dir / "metrics.csv", index=False)
|
||||
print(f"- Metrics saved to: {self.output_dir / 'metrics.csv'}")
|
||||
|
||||
# Plot results
|
||||
self.plot_predictions(pred_df, self.output_dir)
|
||||
|
||||
|
||||
def run(self, n_epochs=30, lr=1e-4):
|
||||
"""
|
||||
Execute the full NR-IQA training and evaluation pipeline.
|
||||
|
||||
This method performs:
|
||||
1. Loading of training and test data (MOS and pseudo-MOS)
|
||||
2. Building the CNN regression model (ResNet18 + MLP)
|
||||
3. Training on the combined labeled/distorted set
|
||||
4. Evaluation on the disjoint labeled/test set
|
||||
5. Saving predictions and evaluation metrics
|
||||
"""
|
||||
self.load_data()
|
||||
self.build_model()
|
||||
self.train(n_epochs=n_epochs, lr=lr)
|
||||
self.evaluate()
|
||||
|
||||
|
||||
|
||||
class MOSDataset(Dataset):
|
||||
"""
|
||||
PyTorch Dataset for IQA images with pseudo or real MOS labels.
|
||||
|
||||
This dataset supports loading from multiple sources (distorted, labeled/train),
|
||||
and makes no distinction between pseudo and real scores. It simply associates
|
||||
each image with its corresponding score and applies the required transformation.
|
||||
|
||||
Attributes:
|
||||
samples (List[Tuple[Path, float]]): List of image paths paired with MOS/pseudo-MOS scores.
|
||||
transform (Callable): Transformation function to apply to the image.
|
||||
"""
|
||||
|
||||
|
||||
def __init__(self, samples, transform=None):
|
||||
"""
|
||||
Initialize the dataset with image-score pairs.
|
||||
|
||||
Args:
|
||||
samples (List[Tuple[Path, float]]): List of (image_path, score).
|
||||
transform (Callable, optional): Transformations to apply to the image.
|
||||
"""
|
||||
self.samples = samples
|
||||
self.transform = transform
|
||||
|
||||
|
||||
def __len__(self):
|
||||
"""Return the number of samples in the dataset."""
|
||||
return len(self.samples)
|
||||
|
||||
|
||||
def __getitem__(self, idx):
|
||||
"""
|
||||
Load image and corresponding score at index idx.
|
||||
|
||||
Returns:
|
||||
Tuple[Tensor, Tensor, str]: image tensor, score tensor, file name
|
||||
"""
|
||||
path, score = self.samples[idx]
|
||||
image = Image.open(path).convert("RGB")
|
||||
if self.transform:
|
||||
image = self.transform(image)
|
||||
return image, torch.tensor(score, dtype=torch.float32), path.name
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
k = 6
|
||||
|
||||
model = NoReferenceModel(
|
||||
pseudo_mos_csv=f"results/pipeline_fusion/k{k}/pseudo_mos.csv",
|
||||
k = k,
|
||||
train_dirs=["data/labeled/train", "data/distorted"],
|
||||
test_dir="data/labeled/train",
|
||||
output_dir=f"results/pipeline_noreference/k{k}"
|
||||
)
|
||||
|
||||
model.load_data()
|
||||
model_file = model.output_dir / "model.pth"
|
||||
|
||||
if model_file.exists():
|
||||
print("Model already trained, loading from checkpoint.")
|
||||
model.load_model()
|
||||
model.evaluate()
|
||||
else:
|
||||
print("Training model from scratch...")
|
||||
model.build_model()
|
||||
model.train(n_epochs=30, lr=1e-4)
|
||||
model.evaluate()
|
||||
@@ -1,74 +0,0 @@
|
||||
"""
|
||||
Pseudo-MOS Learning Script: No-Reference IQA Regression from Fused Full-Reference Scores
|
||||
|
||||
This script trains a no-reference IQA regressor using pseudo-MOS (fusion_rf scores)
|
||||
generated by a full-reference fusion model.
|
||||
|
||||
Steps:
|
||||
1. Load distorted image paths and corresponding fusion scores.
|
||||
2. Extract deep features using selected encoder.
|
||||
3. Train regression models to predict fusion_rf scores.
|
||||
4. Evaluate using cross-validation.
|
||||
5. Save predictions and comparison plots.
|
||||
"""
|
||||
|
||||
import os
|
||||
import pandas as pd
|
||||
|
||||
from nr_fusion.features import extract_features
|
||||
from nr_fusion.models import train_regressor
|
||||
from nr_fusion.evaluation import evaluate_and_plot, compute_correlation_scores
|
||||
|
||||
def main(encoder: str):
|
||||
"""Run no-reference IQA regression using selected encoder."""
|
||||
# Paths
|
||||
image_dir = "images/distorted"
|
||||
scores_csv = "results/ffr_metric/fusion_scores_all.csv"
|
||||
output_dir = f"results/nr_metric/{encoder}"
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
pred_csv = os.path.join(output_dir, "nr_predictions.csv")
|
||||
|
||||
# Load fusion scores
|
||||
df = pd.read_csv(scores_csv)
|
||||
if "fusion_rf" not in df.columns:
|
||||
raise ValueError("Column 'fusion_rf' not found in CSV. Run fusion first.")
|
||||
|
||||
# Check if predictions already exist
|
||||
if os.path.exists(pred_csv):
|
||||
print("Predictions already exist. Loading...")
|
||||
pred_df = pd.read_csv(pred_csv)
|
||||
y = pred_df["pseudo_mos"].values
|
||||
y_pred = pred_df["predicted"].values
|
||||
else:
|
||||
# Feature extraction
|
||||
x, y, filenames = extract_features(df, image_dir)
|
||||
|
||||
# Train + cross-validate + predict
|
||||
y_pred, _, _ = train_regressor(x, y)
|
||||
|
||||
# Save predictions
|
||||
pred_df = pd.DataFrame({
|
||||
"file_name": filenames,
|
||||
"pseudo_mos": y,
|
||||
"predicted": y_pred
|
||||
})
|
||||
pred_df.to_csv(os.path.join(output_dir, "nr_predictions.csv"), index=False)
|
||||
|
||||
# Plot results
|
||||
evaluate_and_plot(y, y_pred, output_dir, show_trend=True)
|
||||
|
||||
correlation_scores = compute_correlation_scores(y, y_pred)
|
||||
print("Correlation scores:", correlation_scores)
|
||||
with open(os.path.join(output_dir, "correlation_scores.txt"), "w", encoding="utf-8") as f:
|
||||
for k, v in correlation_scores.items():
|
||||
f.write(f"{k}: {v:.4f}\n")
|
||||
|
||||
print(f"Pseudo-MOS training with {encoder} completed. Predictions saved.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
# "resnet"
|
||||
# "facenet"
|
||||
|
||||
main(encoder="resnet")
|
||||
Reference in New Issue
Block a user