SmartHearingAids-data / plot_ood_no_input_heatmap.py
carankt's picture
Verification: upload code and scripts only
c22b544 verified
Raw
History Blame Contribute Delete
9.63 kB
#!/usr/bin/env python3
"""
OOD no_input heatmap: scene × distractor coloured by KEPT (+1) vs REMOVED (-1).
Filters command_type == "no_input" from each OOD eval set.
Logic (GT is always speech-only in OOD):
success_clap = 1 → output closer to speech-only GT → model REMOVED → score = -1
success_clap = 0 → output closer to mixture → model KEPT → score = +1
Cell value = mean score across all samples in that scene × distractor cell.
+1.0 = always kept
-1.0 = always removed
0.0 = 50 / 50
Three heatmaps — one per OOD split — two subplots per figure (one per model).
Usage:
python plot_ood_no_input_heatmap.py
"""
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import seaborn as sns
BASE_DIR = Path(__file__).parent
MODELS = {
"combined_v1": "experiments_final/combined_v1",
"no_TSDL_old_mixtures": "experiments_final/no_TSDL_old_mixtures",
}
OOD_SPLITS = {
"OOD_distractors": "eval_outputs_OOD_distractors", # unseen distractor classes
"OOD_backgrounds": "eval_outputs_OOD_backgrounds", # unseen background scenes
"OOD_both": "eval_outputs_OOD_both", # both unseen
}
CSV_NAME = "event_detection_scores_gt_relative.csv"
CMD_TYPE = "no_input"
SUCCESS_COL = "success_clap"
# ═══════════════════════════════════════════════════════════════════════════════
def load(path: Path) -> pd.DataFrame:
df = pd.read_csv(path)
df = df[df["error"].isna() | (df["error"] == "")]
df = df[df["command_type"] == CMD_TYPE].copy()
df[SUCCESS_COL] = pd.to_numeric(df[SUCCESS_COL], errors="coerce")
# kept_score: +1 = kept, -1 = removed
df["kept_score"] = 1 - 2 * df[SUCCESS_COL] # success=1→-1, success=0→+1
df["scene"] = df["mixture_id"].str.extract(r"^(.+?)_\d+dist_")
return df
def build_pivot(df: pd.DataFrame,
scene_order: list,
dist_order: list) -> pd.DataFrame:
pivot = (
df.groupby(["scene", "distractor_name"])["kept_score"]
.mean()
.unstack("distractor_name")
.reindex(index=scene_order, columns=dist_order)
)
return pivot
def annot_array(pivot: pd.DataFrame) -> np.ndarray:
"""Return string array: +value with KEPT/REM label."""
arr = np.empty(pivot.shape, dtype=object)
for i, row in enumerate(pivot.index):
for j, col in enumerate(pivot.columns):
v = pivot.iloc[i, j]
if np.isnan(v):
arr[i, j] = ""
else:
pct = abs(v) * 100
label = "KEPT" if v > 0 else "REM"
arr[i, j] = f"{label}\n{pct:.0f}%"
return arr
def plot_split(split_name: str, dfs: dict, out_path: Path):
"""
dfs: {model_name: DataFrame} — already filtered to no_input for this split.
"""
# Shared distractor + scene ordering by pooled kept_score (most-kept first)
all_df = pd.concat(dfs.values(), ignore_index=True)
if all_df.empty:
print(f" [SKIP] No no_input data for {split_name}")
return
dist_order = (
all_df.groupby("distractor_name")["kept_score"]
.mean()
.sort_values(ascending=False) # most-kept → most-removed
.index.tolist()
)
scene_order = (
all_df.groupby("scene")["kept_score"]
.mean()
.sort_values(ascending=False)
.index.tolist()
)
if not scene_order:
scene_order = ["(all)"]
n_models = len(dfs)
n_dist = max(len(dist_order), 1)
n_scene = max(len(scene_order), 1)
fig, axes = plt.subplots(
1, n_models,
figsize=(max(10, n_dist * 0.55) * n_models, max(4, n_scene * 0.55 + 3)),
squeeze=False,
)
fig.suptitle(
f"OOD no_input | {split_name}\n"
f"KEPT (+1) vs REMOVED (−1) — model default behaviour on unseen sounds",
fontsize=12, fontweight="bold", y=1.02,
)
for ax, (model_name, df) in zip(axes[0], dfs.items()):
if df.empty:
ax.set_title(f"{model_name}\n(no data)")
ax.axis("off")
continue
pivot = build_pivot(df, scene_order, dist_order)
annots = annot_array(pivot)
mask = pivot.isna()
sns.heatmap(
pivot,
ax=ax,
mask=mask,
annot=annots,
fmt="",
annot_kws={"size": 7, "weight": "bold"},
vmin=-1, vmax=1,
center=0,
cmap="RdYlGn", # green = kept, red = removed
linewidths=0.4,
linecolor="#cccccc",
cbar_kws={
"label": "← REMOVED | KEPT →",
"shrink": 0.6,
"ticks": [-1, -0.5, 0, 0.5, 1],
},
)
# Overall kept % per distractor (column header)
dist_overall = df.groupby("distractor_name")["kept_score"].mean()
xlabels = []
for d in dist_order:
v = dist_overall.get(d, float("nan"))
if np.isnan(v):
xlabels.append(d)
else:
pct = abs(v) * 100
tag = "K" if v > 0 else "R"
xlabels.append(f"{d}\n({tag}{pct:.0f}%)")
ax.set_xticklabels(xlabels, fontsize=7.5, rotation=45, ha="right")
# Overall kept % per scene (row header)
scene_overall = df.groupby("scene")["kept_score"].mean()
ylabels = []
for s in scene_order:
v = scene_overall.get(s, float("nan"))
if np.isnan(v):
ylabels.append(s)
else:
pct = abs(v) * 100
tag = "K" if v > 0 else "R"
ylabels.append(f"{s} ({tag}{pct:.0f}%)")
ax.set_yticklabels(ylabels, fontsize=9, rotation=0)
ax.set_title(model_name, fontsize=10, fontweight="bold", pad=8)
ax.set_xlabel("Distractor (OOD)", fontsize=10)
ax.set_ylabel("Scene", fontsize=10)
plt.tight_layout()
fig.savefig(out_path, dpi=150, bbox_inches="tight")
plt.close(fig)
print(f"Saved: {out_path}")
# ═══════════════════════════════════════════════════════════════════════════════
def main():
for split_name, split_dir in OOD_SPLITS.items():
dfs = {}
for model_name, model_dir in MODELS.items():
path = BASE_DIR / model_dir / split_dir / CSV_NAME
if not path.exists():
print(f"[WARN] missing: {path}")
continue
df = load(path)
print(f" {model_name} / {split_name}: {len(df)} no_input rows, "
f"{df['distractor_name'].nunique()} distractors, "
f"{df['scene'].nunique()} scenes")
dfs[model_name] = df
if not dfs:
print(f"[SKIP] {split_name} — no data found")
continue
out = BASE_DIR / f"heatmap_ood_no_input_{split_name}.png"
plot_split(split_name, dfs, out)
# ── Print summary table ────────────────────────────────────────────────────
print(f"\n{'═'*70}")
print(" OOD no_input summary: % KEPT per model per split (CLAP)")
print(f"{'═'*70}")
print(f" {'split':<25} {'combined_v1':>20} {'no_TSDL_old_mixtures':>22}")
print(" " + "─" * 70)
for split_name, split_dir in OOD_SPLITS.items():
row = f" {split_name:<25}"
for model_name, model_dir in MODELS.items():
path = BASE_DIR / model_dir / split_dir / CSV_NAME
if not path.exists():
row += f" {'N/A':>20}"
continue
df = load(path)
if df.empty:
row += f" {'N/A':>20}"
else:
kept_pct = (df["kept_score"] > 0).mean() * 100
row += f" {kept_pct:>19.1f}%"
print(row)
# ── Per-distractor breakdown (OOD_distractors only, combined_v1) ──────────
path = BASE_DIR / "experiments_final/combined_v1" / OOD_SPLITS["OOD_distractors"] / CSV_NAME
if path.exists():
df = load(path)
if not df.empty:
print(f"\n{'═'*70}")
print(" Per-distractor breakdown (OOD_distractors, combined_v1)")
print(" sorted by kept_score (green = model tends to keep, red = tends to remove)")
print(f"{'═'*70}")
print(f" {'distractor':<36} {'N':>4} {'kept_score':>10} {'behaviour'}")
print(" " + "─" * 65)
stats = (
df.groupby("distractor_name")["kept_score"]
.agg(["mean", "count"])
.sort_values("mean", ascending=False)
)
for name, row in stats.iterrows():
v = row["mean"]
n = int(row["count"])
pct = abs(v) * 100
beh = f"KEPT ({pct:.0f}%)" if v > 0 else f"REMOVED ({pct:.0f}%)"
bar = ("█" * int(pct / 5)).ljust(20)
print(f" {name:<36} {n:>4} {v:>+10.3f} {beh} {bar}")
if __name__ == "__main__":
main()