Files
iqa-study/scripts/full_ref_analysis.py
T
2025-08-24 21:00:10 +01:00

104 lines
3.6 KiB
Python

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, _ = np.abs(pearsonr(values, mos))
srcc, _ = np.abs(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 = 4
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}8x5.png"), dpi=300, bbox_inches='tight', pad_inches=0)
plt.savefig(os.path.join(output_dir, f"{file_name}8x5.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)