SmartHearingAids-data / plot_ood_backgrounds_no_input_heatmap.py
carankt's picture
Verification: upload code and scripts only
c22b544 verified
Raw
History Blame Contribute Delete
6.59 kB
#!/usr/bin/env python3
"""
Heatmap: OOD_backgrounds, combined_v1, no_input command type.
X-axis: distractor class (in-distribution, known)
Y-axis: OOD background scene (unseen during training)
Cell value: mean CLAP cosine similarity between model output and isolated
distractor stem, cropped to the distractor's active segment.
High CLAP sim → distractor sound present in output → KEPT (green)
Low CLAP sim → distractor removed from output → REMOVED (red)
Colormap center is fixed at 0.35 (rough speech-baseline CLAP sim).
Annotations show the raw value + K/R tag relative to per-column median.
"""
import re
import csv
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
CSV_PATH = BASE_DIR / "experiments_final/combined_v1/eval_outputs_OOD_backgrounds/event_detection_scores.csv"
OUT_PATH = BASE_DIR / "heatmap_ood_backgrounds_no_input_combined_v1.png"
# ── Load ──────────────────────────────────────────────────────────────────────
df = pd.read_csv(CSV_PATH)
df = df[df["error"].isna() | (df["error"] == "")]
df = df[df["command_type"] == "no_input"].copy()
df["clap_sim"] = pd.to_numeric(df["clap_sim"], errors="coerce")
df["scene"] = df["mixture_id"].str.extract(r"^(.+?)_\d+dist_")
df = df.dropna(subset=["clap_sim", "scene"])
print(f"Rows: {len(df)} | scenes: {df['scene'].nunique()} | distractors: {df['distractor_name'].nunique()}")
# ── Pivot: mean CLAP sim per scene × distractor ───────────────────────────────
pivot = (
df.groupby(["scene", "distractor_name"])["clap_sim"]
.mean()
.unstack("distractor_name")
)
# Order: distractors by mean CLAP sim descending (most-kept left → most-removed right)
dist_order = df.groupby("distractor_name")["clap_sim"].mean().sort_values(ascending=False).index.tolist()
scene_order = df.groupby("scene")["clap_sim"].mean().sort_values(ascending=False).index.tolist()
pivot = pivot.reindex(index=scene_order, columns=dist_order)
# ── Annotation array ──────────────────────────────────────────────────────────
# Use global median as K/R threshold
global_median = df["clap_sim"].median()
print(f"Global CLAP sim median: {global_median:.3f} (used as K/R boundary)")
annots = np.empty(pivot.shape, dtype=object)
for i, scene in enumerate(pivot.index):
for j, dist in enumerate(pivot.columns):
v = pivot.iloc[i, j]
if np.isnan(v):
annots[i, j] = ""
else:
tag = "K" if v >= global_median else "R"
annots[i, j] = f"{tag}\n{v:.2f}"
# ── Column header: overall mean per distractor ────────────────────────────────
dist_means = df.groupby("distractor_name")["clap_sim"].mean()
xlabels = []
for d in dist_order:
v = dist_means.get(d, np.nan)
tag = "K" if v >= global_median else "R"
xlabels.append(f"{d}\n({tag} {v:.2f})")
# ── Row header: overall mean per scene ────────────────────────────────────────
scene_means = df.groupby("scene")["clap_sim"].mean()
ylabels = []
for s in scene_order:
v = scene_means.get(s, np.nan)
tag = "K" if v >= global_median else "R"
ylabels.append(f"{s} ({tag} {v:.2f})")
# ── Plot ──────────────────────────────────────────────────────────────────────
n_dist = len(dist_order)
n_scene = len(scene_order)
fig, ax = plt.subplots(figsize=(max(14, n_dist * 0.55 + 2), max(5, n_scene * 0.65 + 3)))
sns.heatmap(
pivot,
ax=ax,
mask=pivot.isna(),
annot=annots,
fmt="",
annot_kws={"size": 7.5, "weight": "bold"},
vmin=0.25, vmax=0.65,
center=global_median,
cmap="RdYlGn",
linewidths=0.4,
linecolor="#cccccc",
cbar_kws={
"label": "CLAP sim ← REMOVED | KEPT →",
"shrink": 0.6,
},
)
ax.set_xticklabels(xlabels, fontsize=7.5, rotation=45, ha="right")
ax.set_yticklabels(ylabels, fontsize=9, rotation=0)
ax.set_title(
"OOD Backgrounds | combined_v1 | no_input command\n"
"CLAP sim (output crop vs distractor stem) — green = KEPT, red = REMOVED\n"
f"K/R boundary = global median ({global_median:.3f})",
fontsize=11, fontweight="bold", pad=10,
)
ax.set_xlabel("Distractor class (in-distribution, known)", fontsize=10)
ax.set_ylabel("Background scene (OOD, unseen during training)", fontsize=10)
plt.tight_layout()
fig.savefig(OUT_PATH, dpi=150, bbox_inches="tight")
plt.close(fig)
print(f"Saved: {OUT_PATH}")
# ── Per-distractor summary ────────────────────────────────────────────────────
print(f"\n{'═'*60}")
print(" Per-distractor CLAP sim (sorted, K = above median)")
print(f"{'═'*60}")
print(f" {'distractor':<35} {'N':>4} {'mean_sim':>9} {'call'}")
print(" " + "─" * 57)
stats = (
df.groupby("distractor_name")["clap_sim"]
.agg(["mean", "count"])
.sort_values("mean", ascending=False)
)
for name, row in stats.iterrows():
v = row["mean"]; n = int(row["count"])
tag = "KEPT " if v >= global_median else "REMOVED"
bar = ("█" * int((v - 0.25) / 0.40 * 20)).ljust(20)
print(f" {name:<35} {n:>4} {v:>9.3f} {tag} {bar}")
# ── Per-scene summary ─────────────────────────────────────────────────────────
print(f"\n{'═'*60}")
print(" Per-scene CLAP sim (sorted, K = above median)")
print(f"{'═'*60}")
print(f" {'scene':<25} {'N':>4} {'mean_sim':>9} {'call'}")
print(" " + "─" * 47)
scene_stats = (
df.groupby("scene")["clap_sim"]
.agg(["mean", "count"])
.sort_values("mean", ascending=False)
)
for name, row in scene_stats.iterrows():
v = row["mean"]; n = int(row["count"])
tag = "KEPT " if v >= global_median else "REMOVED"
print(f" {name:<25} {n:>4} {v:>9.3f} {tag}")