Initial clean commit
This commit is contained in:
@@ -0,0 +1,184 @@
|
||||
"""
|
||||
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()
|
||||
Reference in New Issue
Block a user