File size: 5,801 Bytes
c22b544 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 | #!/usr/bin/env python3
"""
Heatmap of CLAP success rate: scene × distractor.
success = score(output, GT) > score(mixture, GT) — threshold-free.
Two figures (one per model), each showing an 11 × 30 heatmap.
Cells are coloured by success rate; white = no data.
Distractors sorted by overall success rate (descending).
Scenes sorted by overall success rate (descending).
"""
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": BASE_DIR / "experiments_final/combined_v1/eval_outputs_test_3k/event_detection_scores_gt_relative.csv",
"no_TSDL_old_mixtures": BASE_DIR / "experiments_final/no_TSDL_old_mixtures/eval_outputs_test_3k/event_detection_scores_gt_relative.csv",
}
SUCCESS_COL = "success_clap"
def load(path: Path) -> pd.DataFrame:
df = pd.read_csv(path)
df = df[df["error"].isna() | (df["error"] == "")]
df[SUCCESS_COL] = pd.to_numeric(df[SUCCESS_COL], errors="coerce")
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"])[SUCCESS_COL]
.mean()
.mul(100)
.unstack("distractor_name")
.reindex(index=scene_order, columns=dist_order)
)
return pivot
def plot_heatmap(pivot: pd.DataFrame,
model_name: str,
overall_scene: pd.Series,
overall_dist: pd.Series,
out_path: Path):
n_scenes = len(pivot.index)
n_dist = len(pivot.columns)
fig, ax = plt.subplots(figsize=(max(14, n_dist * 0.55), max(5, n_scenes * 0.55 + 2)))
# Mask NaN cells (no data)
mask = pivot.isna()
sns.heatmap(
pivot,
ax=ax,
mask=mask,
annot=True,
fmt=".0f",
annot_kws={"size": 7},
vmin=50, vmax=100,
cmap="RdYlGn",
linewidths=0.4,
linecolor="#cccccc",
cbar_kws={"label": "CLAP success rate (%)", "shrink": 0.6},
)
# Y-axis: scene + overall rate
ylabels = [
f"{s} ({overall_scene.get(s, float('nan')):.1f}%)"
for s in pivot.index
]
ax.set_yticklabels(ylabels, fontsize=9, rotation=0)
# X-axis: distractor + overall rate
xlabels = [
f"{d}\n({overall_dist.get(d, float('nan')):.1f}%)"
for d in pivot.columns
]
ax.set_xticklabels(xlabels, fontsize=8, rotation=45, ha="right")
ax.set_xlabel("Distractor", fontsize=11)
ax.set_ylabel("Scene", fontsize=11)
ax.set_title(
f"CLAP success rate: scene × distractor | {model_name}\n"
f"success = output closer to GT than raw mixture (no threshold)",
fontsize=11, fontweight="bold", pad=12,
)
plt.tight_layout()
fig.savefig(out_path, dpi=150, bbox_inches="tight")
plt.close(fig)
print(f"Saved: {out_path}")
def main():
dfs = {name: load(path) for name, path in MODELS.items() if path.exists()}
if not dfs:
print("No CSVs found.")
return
# Compute shared distractor and scene order based on pooled success rate
all_df = pd.concat(dfs.values(), ignore_index=True)
dist_order = (
all_df.groupby("distractor_name")[SUCCESS_COL]
.mean()
.sort_values(ascending=False)
.index.tolist()
)
scene_order = (
all_df.groupby("scene")[SUCCESS_COL]
.mean()
.sort_values(ascending=False)
.index.tolist()
)
# Per-model plots
for model_name, df in dfs.items():
overall_dist = (
df.groupby("distractor_name")[SUCCESS_COL].mean().mul(100)
)
overall_scene = (
df.groupby("scene")[SUCCESS_COL].mean().mul(100)
)
pivot = build_pivot(df, scene_order, dist_order)
out = BASE_DIR / f"heatmap_scene_distractor_{model_name}.png"
plot_heatmap(pivot, model_name, overall_scene, overall_dist, out)
# Difference heatmap (combined_v1 − no_TSDL_old_mixtures)
if len(dfs) == 2:
names = list(dfs.keys())
p0 = build_pivot(dfs[names[0]], scene_order, dist_order)
p1 = build_pivot(dfs[names[1]], scene_order, dist_order)
diff = p0 - p1 # positive = combined_v1 better
fig, ax = plt.subplots(figsize=(max(14, len(dist_order) * 0.55),
max(5, len(scene_order) * 0.55 + 2)))
mask = diff.isna()
lim = max(abs(diff.min().min()), abs(diff.max().max()), 5)
sns.heatmap(
diff, ax=ax, mask=mask,
annot=True, fmt=".1f", annot_kws={"size": 7},
vmin=-lim, vmax=lim,
cmap="coolwarm", center=0,
linewidths=0.4, linecolor="#cccccc",
cbar_kws={"label": "Δ success rate pp (combined_v1 − no_TSDL)", "shrink": 0.6},
)
ax.set_yticklabels(scene_order, fontsize=9, rotation=0)
ax.set_xticklabels(
dist_order, fontsize=8, rotation=45, ha="right"
)
ax.set_xlabel("Distractor", fontsize=11)
ax.set_ylabel("Scene", fontsize=11)
ax.set_title(
f"Δ CLAP success rate: {names[0]} − {names[1]}\n"
f"Red = combined_v1 better | Blue = no_TSDL better",
fontsize=11, fontweight="bold", pad=12,
)
plt.tight_layout()
out = BASE_DIR / "heatmap_scene_distractor_diff.png"
fig.savefig(out, dpi=150, bbox_inches="tight")
plt.close(fig)
print(f"Saved: {out}")
if __name__ == "__main__":
main()
|