File size: 4,538 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 | #!/usr/bin/env python3
"""
Plot score distributions (REMOVED vs PRESENT) for each model.
Two figures — one per model — each with 3 subplots (SI-SNR, NXCorr, CLAP sim).
REMOVED and PRESENT distributions are overlaid with a vertical Youden T* line.
"""
from pathlib import Path
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from sklearn.metrics import roc_auc_score, roc_curve
BASE_DIR = Path(__file__).parent
MODELS = {
"combined_v1": BASE_DIR / "experiments_final/combined_v1/eval_outputs_test_3k/event_detection_scores_gt.csv",
"no_TSDL_old_mixtures": BASE_DIR / "experiments_final/no_TSDL_old_mixtures/eval_outputs_test_3k/event_detection_scores_gt.csv",
}
METRICS = [
("si_snr_db", "SI-SNR (dB)", (-40, 20), 1.0),
("nxcorr", "NXCorr", (0, 1.0), 0.02),
("clap_sim", "CLAP similarity", (0, 1.0), 0.02),
]
COLORS = {"REMOVED": "#E05C5C", "PRESENT": "#4C9BE8"}
ALPHA = 0.55
def load(path):
df = pd.read_csv(path)
df = df[df["error"].isna() | (df["error"] == "")]
for col, *_ in METRICS:
df[col] = pd.to_numeric(df[col], errors="coerce")
df["gt_binary"] = df["gt_label"].map({"PRESENT": 1, "REMOVED": 0})
return df
def youden_t(df, col):
valid = df[col].notna() & df["gt_binary"].notna()
fpr, tpr, thresholds = roc_curve(
df.loc[valid, "gt_binary"], df.loc[valid, col]
)
j = tpr + (1 - fpr) - 1
return float(thresholds[np.argmax(j)])
def dprime(present, removed):
sigma_pooled = np.sqrt((present.std()**2 + removed.std()**2) / 2)
return (present.mean() - removed.mean()) / sigma_pooled
def pooled_youden_t(dfs, col):
all_s = pd.concat([df[col].dropna() for df in dfs.values()])
all_l = pd.concat([
df.loc[df[col].notna(), "gt_binary"].dropna()
for df in dfs.values()
])
valid = all_s.notna() & all_l.notna()
fpr, tpr, thresholds = roc_curve(all_l[valid].values, all_s[valid].values)
j = tpr + (1 - fpr) - 1
return float(thresholds[np.argmax(j)])
def plot_model(df, model_name, pooled_thresholds, out_path):
fig, axes = plt.subplots(1, 3, figsize=(15, 5.0))
fig.suptitle(
f"Score distributions: REMOVED vs PRESENT | Model: {model_name}",
fontsize=13, fontweight="bold", y=1.01,
)
for ax, (col, xlabel, xlim, bw) in zip(axes, METRICS):
present = df.loc[df["gt_label"] == "PRESENT", col].dropna()
removed = df.loc[df["gt_label"] == "REMOVED", col].dropna()
bins = np.arange(xlim[0], xlim[1] + bw, bw)
for vals, label in [(removed, "REMOVED"), (present, "PRESENT")]:
ax.hist(vals, bins=bins, color=COLORS[label], alpha=ALPHA,
label=f"{label} (n={len(vals)})", density=True, edgecolor="none")
# Youden T* line
t = pooled_thresholds[col]
ax.axvline(t, color="black", linewidth=1.5, linestyle="--",
label=f"Youden T*={t:.3f}")
# AUC and d' annotation
valid = df[col].notna() & df["gt_binary"].notna()
auc = roc_auc_score(df.loc[valid, "gt_binary"], df.loc[valid, col])
dp = dprime(present.values, removed.values)
ax.text(0.97, 0.97, f"AUC = {auc:.4f}\nd′ = {dp:.4f}",
transform=ax.transAxes, fontsize=9,
verticalalignment="top", horizontalalignment="right",
bbox=dict(boxstyle="round,pad=0.3", facecolor="white",
edgecolor="grey", alpha=0.8))
ax.set_xlabel(xlabel, fontsize=11)
ax.set_ylabel("Density", fontsize=10)
ax.set_xlim(xlim)
ax.legend(fontsize=8.5, framealpha=0.7)
ax.set_title(xlabel, fontsize=11)
ax.spines[["top", "right"]].set_visible(False)
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 pooled Youden thresholds (same for both plots)
pooled_t = {col: pooled_youden_t(dfs, col) for col, *_ in METRICS}
print("Pooled Youden T*:")
for col, label, *_ in METRICS:
print(f" {label:<20}: {pooled_t[col]:.4f}")
for model_name, df in dfs.items():
out = BASE_DIR / f"gt_score_hist_{model_name}.png"
plot_model(df, model_name, pooled_t, out)
if __name__ == "__main__":
main()
|