SmartHearingAids-data / compare_eval_results.py
carankt's picture
Verification: upload code and scripts only
c22b544 verified
Raw
History Blame Contribute Delete
4.92 kB
#!/usr/bin/env python3
"""Compare evaluation results across multiple models, split by command type.
Usage:
python compare_eval_results.py \
experiments_v2_location/combined_v1/eval_outputs_old_no_speech/results.eval.csv \
experiments_v2_location/combined_v1_large/eval_outputs_old_no_speech/results.eval.csv \
experiments_v2_location/no_TSDL_old_mixtures/eval_outputs_old_no_speech/results.eval.csv \
experiments_v2_location/no_TSDL_old_mixtures_large/eval_outputs_old_no_speech/results.eval.csv
# Save summary to CSV:
python compare_eval_results.py --out summary.csv ...
"""
import argparse
import os
import pandas as pd
import numpy as np
SHORT_NAMES = {
"scale_invariant_signal_noise_ratio": "SI-SNR-i",
"signal_noise_ratio": "SNR-i",
"si_snr": "SI-SNR-abs",
"si_snr_improvement": "SI-SNR-i",
"snr_improvement": "SNR-i",
"si_snr_absolute": "SI-SNR-abs",
"td_loss": "TD Loss",
"td_freq_weighted_score": "TD FreqW",
"td_multi_scale_score": "TD MultiS",
"td_combined_score": "TD Combined",
"delta_ITD": "dITD",
"delta_ITD_gcc": "dITD_gcc",
"delta_ILD": "dILD",
"msclap_score": "CLAP",
"spatial_clap_score": "Spatial CLAP",
}
# Non-metric columns to exclude from aggregation
META_COLS = {"mixture_id", "mixture_file", "command_type", "user_input", "target_sources"}
def extract_model_name(path):
parts = path.replace("\\", "/").split("/")
for i, p in enumerate(parts):
if p.startswith("eval_outputs"):
return parts[i - 1]
return os.path.basename(os.path.dirname(path))
def print_table(rows, metric_cols, title=None):
"""Print a formatted table given a list of (model_name, metrics_dict) rows."""
if title:
print(f"\n{'=' * 40}")
print(f" {title}")
print(f"{'=' * 40}")
if not rows:
print(" (no data)")
return
model_names = [r[0] for r in rows]
max_name_len = max(len(n) for n in model_names)
col_width = 14
header = f"{'Model':<{max_name_len}}"
for m in metric_cols:
display = SHORT_NAMES.get(m, m)
header += f" {display:>{col_width}}"
print(header)
print("-" * len(header))
for name, metrics in rows:
row = f"{name:<{max_name_len}}"
for m in metric_cols:
val = metrics.get(m, float("nan"))
row += f" {val:>{col_width}.4f}"
print(row)
def main():
parser = argparse.ArgumentParser(description="Compare eval results across models")
parser.add_argument("paths", nargs="+", help="Paths to results.eval.csv files")
parser.add_argument("--out", type=str, default=None, help="Save summary table to CSV")
args = parser.parse_args()
# Load all CSVs
all_dfs = {}
for path in args.paths:
name = extract_model_name(path)
df = pd.read_csv(path)
df['model'] = name
all_dfs[name] = df
combined = pd.concat(all_dfs.values(), ignore_index=True)
# Identify metric columns (numeric, non-meta)
metric_cols = [c for c in combined.columns
if c not in META_COLS and c != 'model'
and pd.api.types.is_numeric_dtype(combined[c])]
model_names = list(all_dfs.keys())
def safe_means(df, metric_cols):
return {m: df[m].mean() if m in df.columns else float("nan") for m in metric_cols}
# --- Overall ---
overall_rows = []
for name in model_names:
overall_rows.append((name, safe_means(all_dfs[name], metric_cols)))
print_table(overall_rows, metric_cols, "OVERALL")
# --- By command_type ---
cmd_types = sorted(combined['command_type'].dropna().unique())
for cmd in cmd_types:
cmd_rows = []
for name in model_names:
subset = all_dfs[name][all_dfs[name]['command_type'] == cmd]
if len(subset) == 0:
continue
cmd_rows.append((name, safe_means(subset, metric_cols)))
n_samples = len(combined[(combined['command_type'] == cmd) & (combined['model'] == model_names[0])])
print_table(cmd_rows, metric_cols, f"command_type = {cmd} (n={n_samples})")
# --- Save summary CSV ---
if args.out:
summary_rows = []
for cmd in ['overall'] + cmd_types:
for name in model_names:
df = all_dfs[name]
subset = df if cmd == 'overall' else df[df['command_type'] == cmd]
if len(subset) == 0:
continue
row = {'model': name, 'command_type': cmd, 'n_samples': len(subset)}
for m in metric_cols:
row[SHORT_NAMES.get(m, m)] = subset[m].mean() if m in subset.columns else float("nan")
summary_rows.append(row)
pd.DataFrame(summary_rows).to_csv(args.out, index=False)
print(f"\nSaved to {args.out}")
if __name__ == "__main__":
main()