Files

307 lines
11 KiB
Python

'''
Filename: mANOVA.py
Path: /home/netoa/Desktop/ISR/metrics/subjective
Created Date: Friday January 31st 2025
Author: Andre Neto
-----
Last Modified: Thu May 22 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 statsmodels.api as sm
import statsmodels.formula.api as smf
import seaborn as sns
# pylint: disable=line-too-long
class Debiasing:
"""
A pipeline to analyze and debias MOS using ANOVA-based modeling.
"""
def __init__(self, csv_path: str, output_path: str = None):
self.csv_path = csv_path
self.output_path = output_path or csv_path.replace(".csv", "_debiased.csv")
output_dir = os.path.dirname(self.output_path)
if output_dir and not os.path.exists(output_dir):
os.makedirs(output_dir, exist_ok=True)
self.df = None
self.model = None
def load_and_prepare_data(self):
"""
Carrega o CSV e prepara os dados com nomes de colunas padronizados e tipos corretos.
"""
self.df = pd.read_csv(self.csv_path)
self.df.rename(columns={
"gender": "Observer Gender",
"ethnicity": "Observer Ethnicity",
"age": "Observer Age",
"image_gender": "Image Gender",
"image_ethnicity": "Image Ethnicity",
"image_age": "Image Age",
"attractiveness": "Attractiveness",
"level": "Distortion Level",
"rating": "MOS"
}, inplace=True)
# Variáveis categóricas
cat_vars = ["Observer Gender", "Observer Ethnicity", "Image Gender", "Image Ethnicity"]
for var in cat_vars:
self.df[var] = self.df[var].astype("category")
# Variáveis numéricas. A idade do observador NÃO entra aqui: o tests.csv já a traz
# como grupo etário, para não haver idade em bruto num repositório público.
num_vars = ["Image Age", "Attractiveness", "Distortion Level"]
for var in num_vars:
self.df[var] = pd.to_numeric(self.df[var], errors='coerce')
# O grupo etário do observador vem feito do ficheiro, com os intervalos que aqui
# estavam: <18, 18-25, 26-35, 36-50, 51+. A ordem é fixada para o modelo sair igual.
self.df["Observer Age Group"] = pd.Categorical(
self.df["Observer Age"],
categories=["<18", "18-25", "26-35", "36-50", "51+"],
)
self.df["Image Age Group"] = pd.cut(
self.df["Image Age"],
bins=[0, 17, 25, 35, 50, 100],
labels=["<18", "18-25", "26-35", "36-50", "51+"],
include_lowest=True
).astype("category")
def run_anova_tests(self):
"""
Runs ANOVA tests on observer, image, and interaction variables.
"""
print("\nANOVA Results: Observer Demographics Impact on MOS")
model_obs = smf.ols("MOS ~ C(Q('Observer Gender')) + C(Q('Observer Ethnicity'))", data=self.df).fit()
print(sm.stats.anova_lm(model_obs, typ=2))
print("\nANOVA Results: Image Characteristics Impact on MOS")
model_img = smf.ols("MOS ~ C(Q('Image Gender')) + C(Q('Image Ethnicity')) + C(Q('Attractiveness'))", data=self.df).fit()
print(sm.stats.anova_lm(model_img, typ=2))
print("\nANOVA Results: Interaction Effects between Observer and Image Characteristics")
formula = """
MOS ~ C(Q('Observer Gender')) * C(Q('Image Gender'))
+ C(Q('Observer Ethnicity')) * C(Q('Image Ethnicity'))
+ C(Q('Attractiveness'))
+ C(Q('Observer Age Group')) * C(Q('Image Age Group'))
"""
model_inter = smf.ols(formula, data=self.df).fit()
print(sm.stats.anova_lm(model_inter, typ=3))
def residualize_mos(self):
"""
Removes demographic and perceptual bias from MOS using residuals.
"""
formula = """
MOS ~ C(Q('Observer Gender')) + C(Q('Observer Ethnicity')) + C(Q('Image Gender')) + C(Q('Image Ethnicity')) """
self.model = smf.ols(formula, data=self.df).fit()
mean_predicted = self.model.fittedvalues.mean()
self.df["MOS_debiased"] = self.model.resid + mean_predicted
def save_debiased_mos(self, output_path: str):
"""
Saves the debiased MOS to a new CSV file.
"""
self.df.to_csv(output_path, index=False)
print(f"Saved debiased MOS to {output_path}")
def plot_violinplots(self, categorical_vars, dependent_var="MOS"):
"""
Plots and saves violinplots of MOS vs. specified categorical variables.
"""
sns.set(style="whitegrid")
for var in categorical_vars:
plt.figure(figsize=(10, 5))
sns.violinplot(x=var, y=dependent_var, data=self.df, color="skyblue")
plt.xticks(rotation=45)
plt.title(f"{var} vs. {dependent_var}")
plt.xlabel(var)
plt.ylabel(dependent_var)
plt.tight_layout()
filename = f"{var.replace(' ', '_').lower()}_vs_{dependent_var.lower()}.png"
filepath = os.path.join(os.path.dirname(self.output_path), filename)
plt.savefig(filepath)
plt.close()
def plot_interaction(self):
"""
Saves a plot visualizing MOS by observer and image gender interaction.
"""
plt.figure(figsize=(10, 6))
sns.violinplot(x=self.df["Observer Gender"], y=self.df["MOS"], hue=self.df["Image Gender"], palette="coolwarm")
plt.xlabel("Observer Gender")
plt.ylabel("Mean Opinion Score (MOS)")
plt.title("MOS Ratings by Observer Gender and Image Gender")
plt.legend(title="Image Gender")
plt.tight_layout()
filepath = os.path.join(os.path.dirname(self.output_path), "observer_image_gender_interaction.png")
plt.savefig(filepath)
plt.close()
def save_anova_significance_table(self, output_file="anova_significance.csv"):
"""
Computes ANOVA p-values for demographic variables before and after debiasing.
Saves the results as a CSV.
"""
formula = """
MOS ~ C(Q('Observer Gender')) + C(Q('Observer Ethnicity'))
+ C(Q('Image Gender')) + C(Q('Image Ethnicity'))
+ C(Q('Observer Gender')):C(Q('Image Gender'))
+ C(Q('Observer Ethnicity')):C(Q('Image Ethnicity'))
"""
model_before = smf.ols(formula, data=self.df).fit()
anova_before = sm.stats.anova_lm(model_before, typ=2)
model_after = smf.ols(formula.replace("MOS", "MOS_debiased"), data=self.df).fit()
anova_after = sm.stats.anova_lm(model_after, typ=2)
table = pd.DataFrame({
"Factor": anova_before.index,
"p-value (Before)": anova_before["PR(>F)"].values,
"p-value (After)": anova_after["PR(>F)"].values
})
output_path = os.path.join(os.path.dirname(self.output_path), output_file)
table.to_csv(output_path, index=False)
print(f"Saved ANOVA significance table to {output_path}")
def run(self):
"""
Executes the full debiasing pipeline:
1. Load and prepare data
2. Run ANOVA tests
3. Residualize (debias) MOS
4. Save debiased results
5. Plot violinplots and interactions
6. Save ANOVA significance table
"""
self.load_and_prepare_data()
self.run_anova_tests()
self.residualize_mos()
if self.output_path:
self.save_debiased_mos(self.output_path)
self.plot_violinplots([
"Observer Gender", "Observer Ethnicity",
"Image Gender", "Image Ethnicity"
])
self.plot_interaction()
self.save_anova_significance_table()
def load_main_debiased_csv(path):
"""
Carrega o CSV principal com MOS_debiased por linha, normaliza os nomes e
retorna um DataFrame com média de MOS_debiased por imagem.
"""
df = pd.read_csv(path)
# Confere colunas necessárias
required_cols = {"file_name", "distortion", "Distortion Level", "MOS_debiased"}
if not required_cols.issubset(df.columns):
missing = required_cols - set(df.columns)
raise ValueError(f"Faltam colunas obrigatórias: {missing}")
df["file_name"] = df["file_name"].astype(str)
df["distortion"] = df["distortion"].astype(str)
df["Distortion Level"] = df["Distortion Level"].astype(str)
def normalize_file_id(name):
parts = name.split("_")
if parts:
parts[0] = parts[0].zfill(3)
return "_".join(parts)
df["file_name"] = df["file_name"].apply(normalize_file_id)
# Cria nome único de imagem
df["full_file_name"] = df.apply(
lambda row: f"{row['file_name']}_{row['distortion']}_{row['Distortion Level']}.jpg", axis=1
)
# Agrupa por imagem e calcula a média de MOS_debiased
df_out = df.groupby("full_file_name", as_index=False)["MOS_debiased"].mean()
df_out.rename(columns={"full_file_name": "file_name"}, inplace=True)
return df_out
def save_debiased_per_folder(root_folder, debiased_df):
"""
Cria ficheiros 'mos_debiased.csv' em todas as pastas que tenham 'mos.csv',
contendo apenas file_name e MOS_debiased.
"""
def normalize_file_id(name):
parts = name.split("_")
if parts:
parts[0] = parts[0].zfill(3)
return "_".join(parts)
debiased_df = debiased_df.rename(columns={"MOS_debiased": "mos"})
debiased_df["file_name"] = debiased_df["file_name"].astype(str)
debiased_df["file_name"] = debiased_df["file_name"].apply(normalize_file_id)
for dirpath, _, filenames in os.walk(root_folder):
if "mos.csv" not in filenames:
continue
mos_path = os.path.join(dirpath, "mos.csv")
try:
df = pd.read_csv(mos_path)
except (pd.errors.EmptyDataError, FileNotFoundError, PermissionError) as e:
print(f"[ERRO] Falha ao ler {mos_path}: {e}")
continue
if "file_name" not in df.columns:
print(f"[WARN] Ignorado (sem coluna 'file_name'): {mos_path}")
continue
df["file_name"] = df["file_name"].astype(str)
df["file_name"] = df["file_name"].apply(normalize_file_id)
# Retém apenas nomes únicos para merge
unique_files = df[["file_name"]].drop_duplicates()
merged = unique_files.merge(debiased_df, on="file_name", how="left")
output_path = os.path.join(dirpath, "mos_debiased.csv")
merged.to_csv(output_path, index=False)
print(f"[OK] Gerado: {output_path}")
# Example usage
if __name__ == "__main__":
pipeline = Debiasing(
csv_path="results/webapp/tests.csv",
output_path="results/pipeline_unbias/tests_debiased.csv"
)
pipeline.run()
debiased = load_main_debiased_csv("results/pipeline_unbias/tests_debiased.csv")
save_debiased_per_folder("data", debiased)