| |
| """ |
| OOD stem-based CLAP heatmaps — all 3 splits × 2 models. |
| |
| Metric: CLAP cosine similarity between model output crop and isolated |
| distractor stem crop (from evaluate_event_detection.py). |
| |
| High CLAP sim → distractor present in output → KEPT (green) |
| Low CLAP sim → distractor removed → REMOVED (red) |
| |
| Only no_input command type (unambiguous: no user command given). |
| |
| Outputs (one figure per OOD split, two subplots per figure): |
| heatmap_ood_stem_OOD_backgrounds.png |
| heatmap_ood_stem_OOD_distractors.png |
| heatmap_ood_stem_OOD_both.png |
| """ |
|
|
| import re |
| 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_backgrounds": ("eval_outputs_OOD_backgrounds", |
| "Background scene (OOD)", |
| "Distractor class (in-distribution)"), |
| "OOD_distractors": ("eval_outputs_OOD_distractors", |
| "Background scene (in-distribution)", |
| "Distractor class (OOD)"), |
| "OOD_both": ("eval_outputs_OOD_both", |
| "Background scene (OOD)", |
| "Distractor class (OOD)"), |
| } |
|
|
| CMD_TYPE = "no_input" |
| CSV_NAME = "event_detection_scores.csv" |
|
|
| |
| |
| DISTRACTOR_CANONICAL_ORDER = [ |
| "computer_typing", "drill", "cricket", "sneeze", "cough", |
| "jackhammer", "hammer", "engine", "applause", "birds_chirping", |
| "fireworks", "helicopter", "dog", "car_horn", "footsteps", |
| "alarm_clock", "slam", "baby_cry", "train_horn", "cat", |
| "ringtone", "cellphone_buzz_vibrating_alert", "car_alarm", |
| "glass_breaking", "door_knock", "siren", "boom", |
| "doorbell", "fire_alarm", "gunshot", |
| ] |
|
|
| DISPLAY_NAMES = { |
| "computer_typing": "Computer Typing", |
| "drill": "Drill", |
| "cricket": "Cricket", |
| "sneeze": "Sneeze", |
| "cough": "Cough", |
| "jackhammer": "Jackhammer", |
| "hammer": "Hammer", |
| "engine": "Engine", |
| "applause": "Applause", |
| "birds_chirping": "Birds Chirping", |
| "fireworks": "Fireworks", |
| "helicopter": "Helicopter", |
| "dog": "Dog", |
| "car_horn": "Car Horn", |
| "footsteps": "Footsteps", |
| "alarm_clock": "Alarm Clock", |
| "slam": "Slam", |
| "baby_cry": "Baby Cry", |
| "train_horn": "Train Horn", |
| "cat": "Cat", |
| "ringtone": "Ringtone", |
| "cellphone_buzz_vibrating_alert":"Smartphone Vibration", |
| "car_alarm": "Car Alarm", |
| "glass_breaking": "Glass Breaking", |
| "door_knock": "Door Knock", |
| "siren": "Siren", |
| "boom": "Boom", |
| "doorbell": "Doorbell", |
| "fire_alarm": "Fire Alarm", |
| "gunshot": "Gunshot", |
| } |
|
|
| |
| SCENE_DISPLAY_NAMES = { |
| "airplane": "Airplane", |
| "bus_station": "Bus Station", |
| "gym": "Gym", |
| "harbour": "Harbour", |
| "library": "Library", |
| "museum": "Museum", |
| "office": "Office", |
| "park": "Park", |
| "shopping_mall": "Shopping Mall", |
| "train_station": "Train Station", |
| "airport": "Airport", |
| "beach": "Beach", |
| "bus": "Bus", |
| "cafe": "Cafe", |
| "coffee_shop": "Coffee Shop", |
| "city": "City", |
| "forest": "Forest", |
| "home": "Home", |
| "kitchen": "Kitchen", |
| "restaurant": "Restaurant", |
| "supermarket": "Supermarket", |
| "train": "Train", |
| } |
|
|
|
|
| def canonical_dist_order(present: list) -> list: |
| """Return distractors in canonical order; extras appended at end.""" |
| ordered = [d for d in DISTRACTOR_CANONICAL_ORDER if d in present] |
| extras = [d for d in present if d not in DISTRACTOR_CANONICAL_ORDER] |
| return ordered + extras |
|
|
|
|
| |
| 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["clap_sim"] = pd.to_numeric(df["clap_sim"], errors="coerce") |
| df["scene"] = df["mixture_id"].str.extract(r"^(.+?)_\d+dist_") |
| return df.dropna(subset=["clap_sim", "scene"]) |
|
|
|
|
| def build_pivot(df: pd.DataFrame, scene_order, dist_order) -> pd.DataFrame: |
| return ( |
| df.groupby(["scene", "distractor_name"])["clap_sim"] |
| .mean() |
| .unstack("distractor_name") |
| .reindex(index=scene_order, columns=dist_order) |
| ) |
|
|
|
|
| def annot_array(pivot: pd.DataFrame) -> np.ndarray: |
| """Single-line value annotation — colour already conveys K/R.""" |
| arr = np.empty(pivot.shape, dtype=object) |
| for i in range(pivot.shape[0]): |
| for j in range(pivot.shape[1]): |
| v = pivot.iloc[i, j] |
| arr[i, j] = "" if np.isnan(v) else f"{v:.2f}" |
| return arr |
|
|
|
|
| def dist_xlabel(name, mean_val, threshold): |
| tag = "K" if mean_val >= threshold else "R" |
| disp = DISPLAY_NAMES.get(name, name) |
| return f"{disp}\n({tag} {mean_val:.2f})" |
|
|
|
|
| def scene_ylabel(name, mean_val, threshold): |
| tag = "K" if mean_val >= threshold else "R" |
| disp = SCENE_DISPLAY_NAMES.get(name, name.replace("_", " ").title()) |
| return f"{disp} ({tag} {mean_val:.2f})" |
|
|
|
|
| |
| def plot_split(split_key: str, dist_order_override=None): |
| split_dir, ylabel, xlabel = OOD_SPLITS[split_key] |
|
|
| |
| 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_key}: {len(df)} rows, " |
| f"{df['scene'].nunique()} scenes, " |
| f"{df['distractor_name'].nunique()} distractors") |
| dfs[model_name] = df |
|
|
| if not dfs: |
| print(f" [SKIP] {split_key} — no data") |
| return |
|
|
| |
| all_df = pd.concat(dfs.values(), ignore_index=True) |
| threshold = all_df["clap_sim"].median() |
| print(f" Threshold (pooled median): {threshold:.3f}") |
|
|
| |
| present_dists = all_df["distractor_name"].unique().tolist() |
| if dist_order_override is not None: |
| |
| dist_order = [d for d in dist_order_override if d in present_dists] |
| |
| extras = [d for d in present_dists if d not in dist_order_override] |
| dist_order = dist_order + canonical_dist_order(extras) |
| else: |
| dist_order = canonical_dist_order(present_dists) |
| scene_order = ( |
| all_df.groupby("scene")["clap_sim"] |
| .mean().sort_values(ascending=False).index.tolist() |
| ) |
|
|
| n_dist = len(dist_order) |
| n_scene = len(scene_order) |
|
|
| ood_tag = { |
| "OOD_backgrounds": "OOD: background scenes unseen, distractors known", |
| "OOD_distractors": "OOD: distractor classes unseen, backgrounds known", |
| "OOD_both": "OOD: both background scenes and distractor classes unseen", |
| }[split_key] |
|
|
| |
| for model_name, df in dfs.items(): |
|
|
| |
| cell_w = 0.62 |
| cell_h = 0.28 |
| margin_w = 3.5 |
| hm_title = 0.8 |
| bp_h = 2.8 |
| xlbl_h = 2.5 |
| suptitle_h = 0.9 |
|
|
| fw = n_dist * cell_w + margin_w |
| heatmap_h = n_scene * cell_h + hm_title |
| fh = suptitle_h + heatmap_h + bp_h + xlbl_h |
|
|
| fig, axes = plt.subplots( |
| 2, 1, |
| figsize=(fw, fh), |
| gridspec_kw={"height_ratios": [heatmap_h, bp_h + xlbl_h], |
| "hspace": 0.02}, |
| squeeze=False, |
| ) |
| ax_hm = axes[0][0] |
| ax_box = axes[1][0] |
|
|
| fig.suptitle( |
| f"{split_key} | {model_name} | no_input | stem-based CLAP similarity\n" |
| f"{ood_tag}\n" |
| f"green = KEPT (distractor present), red = REMOVED " |
| f"| K/R boundary = pooled median ({threshold:.3f})", |
| fontsize=11, fontweight="bold", y=1.01, |
| ) |
|
|
| |
| pivot = build_pivot(df, scene_order, dist_order) |
| annots = annot_array(pivot) |
|
|
| sns.heatmap( |
| pivot, ax=ax_hm, mask=pivot.isna(), |
| annot=annots, fmt="", |
| annot_kws={"size": 7, "weight": "bold"}, |
| vmin=0.20, vmax=0.70, center=threshold, |
| cmap="RdYlGn", linewidths=0.4, linecolor="#cccccc", |
| cbar_kws={ |
| "label": "CLAP sim ← REMOVED | KEPT →", |
| "shrink": 0.7, |
| "ticks": [0.20, 0.30, threshold, 0.50, 0.60, 0.70], |
| }, |
| ) |
|
|
| scene_means = df.groupby("scene")["clap_sim"].mean() |
| ax_hm.set_xticklabels([]) |
| ax_hm.set_xlabel("") |
| ax_hm.set_yticklabels( |
| [scene_ylabel(s, scene_means.get(s, np.nan), threshold) |
| for s in scene_order], |
| fontsize=9, rotation=0, |
| ) |
| kept_pct = (df["clap_sim"] >= threshold).mean() * 100 |
| ax_hm.set_title(f"KEPT {kept_pct:.0f}% overall", |
| fontsize=10, fontweight="bold", pad=6) |
| ax_hm.set_ylabel(ylabel, fontsize=9) |
|
|
| |
| |
| model_dists = df["distractor_name"].unique() |
| model_dist_order = [d for d in dist_order if d in model_dists] |
|
|
| bp_df = df[["distractor_name", "clap_sim"]].copy() |
| bp_df["kept"] = (bp_df["clap_sim"] >= threshold).astype(float) |
| mean_kept = bp_df.groupby("distractor_name")["kept"].mean() * 100 |
|
|
| |
| col_idx = {d: i for i, d in enumerate(dist_order)} |
| bar_positions = np.array([col_idx[d] + 0.5 for d in model_dist_order]) |
| bar_values = [mean_kept.get(d, np.nan) for d in model_dist_order] |
| bar_colors = [ |
| "#2ca02c" if (not np.isnan(v) and v >= 50) else "#d62728" |
| for v in bar_values |
| ] |
|
|
| ax_box.bar( |
| bar_positions, bar_values, |
| width=0.6, color=bar_colors, alpha=0.85, zorder=3, |
| edgecolor="white", linewidth=0.4, |
| ) |
|
|
| |
| for pos, val, color in zip(bar_positions, bar_values, bar_colors): |
| if not np.isnan(val): |
| ax_box.text( |
| pos, val + 1.5, f"{val:.0f}%", |
| ha="center", va="bottom", fontsize=5.5, |
| fontweight="bold", color="black", |
| ) |
|
|
| ax_box.axhline(50, color="gray", linestyle="--", |
| linewidth=1.0, alpha=0.8, label="50% boundary (K/R)") |
|
|
| |
| ax_hm.set_xlim(0, n_dist) |
| ax_box.set_xlim(0, n_dist) |
|
|
| ax_box.set_ylim(0, 115) |
| ax_box.set_yticks([0, 25, 50, 75, 100]) |
| ax_box.set_yticklabels(["0%", "25%", "50%", "75%", "100%"], fontsize=8) |
| |
| ax_box.set_xticks(np.arange(n_dist) + 0.5) |
| ax_box.set_xticklabels( |
| [DISPLAY_NAMES.get(d, d) for d in dist_order], |
| fontsize=7.5, rotation=45, ha="right", |
| ) |
| ax_box.set_xlabel(xlabel, fontsize=10) |
| ax_box.set_ylabel("Mean Kept Rate (%)", fontsize=9) |
| ax_box.set_title("Mean kept rate per distractor across scenes " |
| "(green ≥ 50%, red < 50%)", |
| fontsize=10, fontweight="bold", pad=6) |
| ax_box.yaxis.grid(True, linestyle="--", linewidth=0.5, alpha=0.5, zorder=0) |
| ax_box.set_axisbelow(True) |
| ax_box.legend(fontsize=8, loc="upper left", framealpha=0.85) |
|
|
| |
| |
| |
| plt.tight_layout() |
| fig.canvas.draw() |
| pos_hm = ax_hm.get_position() |
| pos_box = ax_box.get_position() |
| ax_box.set_position([pos_hm.x0, pos_box.y0, |
| pos_hm.width, pos_box.height]) |
|
|
| out = BASE_DIR / f"heatmap_ood_stem_{split_key}_{model_name}.png" |
| fig.savefig(out, dpi=150, bbox_inches="tight") |
| plt.close(fig) |
| print(f" Saved: {out}") |
|
|
|
|
| def print_summary(): |
| print(f"\n{'═'*72}") |
| print(" OOD no_input summary — % KEPT (CLAP sim ≥ pooled median)") |
| print(f"{'═'*72}") |
| print(f" {'split':<20} {'combined_v1':>20} {'no_TSDL_old_mixtures':>22}") |
| print(" " + "─" * 65) |
|
|
| for split_key, (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 path.exists(): |
| dfs[model_name] = load(path) |
|
|
| if not dfs: |
| continue |
|
|
| threshold = pd.concat(dfs.values())["clap_sim"].median() |
| row = f" {split_key:<20}" |
| for model_name in MODELS: |
| if model_name in dfs: |
| pct = (dfs[model_name]["clap_sim"] >= threshold).mean() * 100 |
| row += f" {pct:>19.1f}%" |
| else: |
| row += f" {'N/A':>20}" |
| print(row) |
|
|
|
|
| if __name__ == "__main__": |
| |
| |
| SHARED_SPLITS = {"OOD_distractors", "OOD_both"} |
| shared_all_dists = set() |
| for sk in SHARED_SPLITS: |
| split_dir = OOD_SPLITS[sk][0] |
| for model_dir in MODELS.values(): |
| path = BASE_DIR / model_dir / split_dir / CSV_NAME |
| if path.exists(): |
| df_tmp = load(path) |
| shared_all_dists.update(df_tmp["distractor_name"].unique()) |
| shared_dist_order = canonical_dist_order(list(shared_all_dists)) |
| print(f"\nShared distractor order (OOD_distractors + OOD_both): " |
| f"{len(shared_dist_order)} classes") |
|
|
| for split_key in OOD_SPLITS: |
| print(f"\n{'─'*60}") |
| print(f" Plotting {split_key} ...") |
| override = shared_dist_order if split_key in SHARED_SPLITS else None |
| plot_split(split_key, dist_order_override=override) |
|
|
| print_summary() |
|
|