| |
| """ |
| GT-comparison event detection analysis. |
| |
| Primary metric : AUC-ROC (threshold-free model comparison) |
| Operating point: Youden's J = argmax(TPR + TNR − 1) |
| Found on pooled scores from both models → single shared threshold. |
| |
| Binary labels: PRESENT = 1 (keep command, distractor in GT) |
| REMOVED = 0 (remove command, distractor absent from GT) |
| |
| Only eval_outputs_test_3k (non-OOD) is used. |
| |
| Usage: |
| python analyze_detection_scores_gt.py |
| python analyze_detection_scores_gt.py --sisnr_threshold 2.5 --nxcorr_threshold 0.80 --clap_threshold 0.65 |
| """ |
|
|
| import argparse |
| from pathlib import Path |
|
|
| import numpy as np |
| import pandas as pd |
| from sklearn.metrics import roc_auc_score, roc_curve |
|
|
| |
| BASE_DIR = Path(__file__).parent |
|
|
| MODELS_FINAL = { |
| "combined_v1": BASE_DIR / "experiments_final/combined_v1", |
| "no_TSDL_old_mixtures": BASE_DIR / "experiments_final/no_TSDL_old_mixtures", |
| } |
|
|
| TEST_3K_CSV = "eval_outputs_test_3k/event_detection_scores_gt.csv" |
|
|
|
|
| |
|
|
| def load_csv(path: Path) -> pd.DataFrame: |
| df = pd.read_csv(path) |
| df = df[df["error"].isna() | (df["error"] == "")] |
| for col in ["si_snr_db", "nxcorr", "clap_sim"]: |
| df[col] = pd.to_numeric(df[col], errors="coerce") |
| df["gt_binary"] = df["gt_label"].map({"PRESENT": 1, "REMOVED": 0}) |
| return df |
|
|
|
|
| def print_section(title: str): |
| print(f"\n{'═'*70}") |
| print(f" {title}") |
| print(f"{'═'*70}") |
|
|
|
|
| def predict(series: pd.Series, threshold: float) -> pd.Series: |
| return (series > threshold).map({True: "PRESENT", False: "REMOVED"}) |
|
|
|
|
| def accuracy(pred: pd.Series, gt: pd.Series) -> float: |
| valid = gt.notna() & pred.notna() |
| if valid.sum() == 0: |
| return float("nan") |
| return (pred[valid] == gt[valid]).mean() * 100.0 |
|
|
|
|
| |
| |
| |
|
|
| def print_score_stats(dfs: dict): |
| print_section("Score statistics (higher = model output matches GT better)") |
| header = f" {'metric':<12} {'stat':<8}" |
| for name in dfs: |
| header += f" {name:>26}" |
| print(header) |
| print(" " + "─" * (22 + len(dfs) * 28)) |
| for col in ["si_snr_db", "nxcorr", "clap_sim"]: |
| for stat, fn in [("mean", np.nanmean), ("median", np.nanmedian), ("std", np.nanstd)]: |
| row = f" {col:<12} {stat:<8}" |
| for df in dfs.values(): |
| row += f" {fn(df[col].dropna().values):>26.4f}" |
| print(row) |
| print() |
|
|
|
|
| |
| |
| |
|
|
| def compute_auc(df: pd.DataFrame, col: str) -> float: |
| """AUC-ROC for one model / one metric.""" |
| valid = df[col].notna() & df["gt_binary"].notna() |
| if valid.sum() < 2: |
| return float("nan") |
| return roc_auc_score(df.loc[valid, "gt_binary"], df.loc[valid, col]) |
|
|
|
|
| def youden_threshold(scores: np.ndarray, labels: np.ndarray) -> float: |
| """ |
| Find threshold T* = argmax(TPR + TNR − 1) via sklearn's roc_curve. |
| scores : continuous scores |
| labels : binary (1 = PRESENT, 0 = REMOVED) |
| """ |
| fpr, tpr, thresholds = roc_curve(labels, scores) |
| j = tpr + (1.0 - fpr) - 1.0 |
| best = int(np.argmax(j)) |
| return float(thresholds[best]) |
|
|
|
|
| def pooled_youden_threshold(dfs: dict, col: str) -> float: |
| """ |
| Youden's J on the combined scores of all models. |
| Gives a single shared operating-point threshold for fair comparison. |
| """ |
| all_scores = pd.concat([df[col].dropna() for df in dfs.values()]) |
| all_labels = pd.concat([ |
| df.loc[df[col].notna(), "gt_binary"].dropna() |
| for df in dfs.values() |
| ]) |
| |
| valid = all_scores.notna() & all_labels.notna() |
| return youden_threshold(all_scores[valid].values, all_labels[valid].values) |
|
|
|
|
| def print_auc_and_youden(dfs: dict) -> dict: |
| """ |
| Print AUC table and per-model Youden thresholds. |
| Returns {col: pooled_youden_T} for use in the breakdown tables. |
| """ |
| metrics = [ |
| ("SI-SNR", "si_snr_db"), |
| ("NXCorr", "nxcorr"), |
| ("CLAP sim", "clap_sim"), |
| ] |
| model_names = list(dfs.keys()) |
|
|
| |
| print_section("AUC-ROC (threshold-free model comparison; higher = better)") |
| print(f"\n {'Metric':<12} {'N':>6}", end="") |
| for name in model_names: |
| print(f" {name:>26}", end="") |
| print() |
| print(" " + "─" * (20 + len(model_names) * 28)) |
|
|
| for m_label, col in metrics: |
| first_df = list(dfs.values())[0] |
| n = (first_df[col].notna() & first_df["gt_binary"].notna()).sum() |
| print(f" {m_label:<12} {n:>6}", end="") |
| for df in dfs.values(): |
| auc = compute_auc(df, col) |
| print(f" {auc:>26.4f}", end="") |
| print() |
|
|
| |
| print_section( |
| "Youden's J operating-point threshold\n" |
| " T* = argmax(TPR + TNR − 1) on pooled scores from both models\n" |
| " Per-model T* shown for reference; pooled T* used in breakdown tables" |
| ) |
|
|
| youden_thresholds = {} |
|
|
| for m_label, col in metrics: |
| pooled_t = pooled_youden_threshold(dfs, col) |
| youden_thresholds[col] = pooled_t |
|
|
| print(f"\n {m_label}") |
| for name, df in dfs.items(): |
| valid = df[col].notna() & df["gt_binary"].notna() |
| t_model = youden_threshold( |
| df.loc[valid, col].values, |
| df.loc[valid, "gt_binary"].values, |
| ) |
| |
| tpr = (df.loc[valid & (df["gt_label"] == "PRESENT"), col] > t_model).mean() |
| tnr = (df.loc[valid & (df["gt_label"] == "REMOVED"), col] <= t_model).mean() |
| j = tpr + tnr - 1.0 |
| print(f" {name:<30} T*={t_model:.4f} TPR={tpr:.3f} TNR={tnr:.3f} J={j:.3f}") |
|
|
| |
| all_s, all_l = [], [] |
| for df in dfs.values(): |
| valid = df[col].notna() & df["gt_binary"].notna() |
| all_s.append(df.loc[valid, col].values) |
| all_l.append(df.loc[valid, "gt_binary"].values) |
| s = np.concatenate(all_s) |
| l = np.concatenate(all_l) |
| tpr_p = (s[l == 1] > pooled_t).mean() |
| tnr_p = (s[l == 0] <= pooled_t).mean() |
| j_p = tpr_p + tnr_p - 1.0 |
| print(f" {'[pooled]':<30} T*={pooled_t:.4f} TPR={tpr_p:.3f} TNR={tnr_p:.3f} J={j_p:.3f}") |
|
|
| return youden_thresholds |
|
|
|
|
| |
| |
| |
|
|
| def analyse(dfs: dict, sisnr_t: float, nxcorr_t: float, clap_t: float, |
| label: str = ""): |
| metrics = [ |
| ("SI-SNR", "si_snr_db", sisnr_t), |
| ("NXCorr", "nxcorr", nxcorr_t), |
| ("CLAP sim", "clap_sim", clap_t), |
| ] |
| model_names = list(dfs.keys()) |
| suffix = f" [{label}]" if label else "" |
|
|
| print_section( |
| f"Accuracy vs gt_label at Youden threshold{suffix}\n" |
| f" SI-SNR>{sisnr_t:+.4f}dB | NXCorr>{nxcorr_t:.4f} | CLAP>{clap_t:.4f}" |
| ) |
|
|
| |
| print(f"\n {'Metric':<12} {'N':>6}", end="") |
| for name in model_names: |
| print(f" {name:>26}", end="") |
| print() |
| print(" " + "─" * (20 + len(model_names) * 28)) |
|
|
| for m_label, col, thr in metrics: |
| first_df = list(dfs.values())[0] |
| n = (first_df[col].notna() & first_df["gt_label"].notna()).sum() |
| print(f" {m_label:<12} {n:>6}", end="") |
| for df in dfs.values(): |
| valid = df[col].notna() & df["gt_label"].notna() |
| pred = predict(df.loc[valid, col], thr) |
| acc = accuracy(pred, df.loc[valid, "gt_label"]) |
| print(f" {'%.2f%%' % acc:>26}", end="") |
| print() |
|
|
| |
| print_section(f"Accuracy by command_type{suffix}") |
| command_types = sorted( |
| set().union(*[set(df["command_type"].dropna()) for df in dfs.values()]) |
| ) |
|
|
| for m_label, col, thr in metrics: |
| print(f"\n [ {m_label} @ T*={thr:.4f} ]\n") |
| print(f" {'command_type':<22} {'N':>6}", end="") |
| for name in model_names: |
| print(f" {name:>26}", end="") |
| print() |
| print(" " + "─" * (30 + len(model_names) * 28)) |
|
|
| for ct in command_types: |
| row_str = f" {ct:<22}" |
| n_shown = False |
| for df in dfs.values(): |
| sub = df[df["command_type"] == ct] |
| valid = sub[col].notna() & sub["gt_label"].notna() |
| if not n_shown: |
| row_str += f" {valid.sum():>6}" |
| n_shown = True |
| pred = predict(sub.loc[valid, col], thr) |
| acc = accuracy(pred, sub.loc[valid, "gt_label"]) |
| s = f"{'%.2f%%' % acc}" if not np.isnan(acc) else "N/A" |
| row_str += f" {s:>26}" |
| print(row_str) |
|
|
| |
| print_section(f"Accuracy by distractor_name (CLAP @ T*={clap_t:.4f}){suffix} sorted by {model_names[0]}") |
| col, thr = "clap_sim", clap_t |
| dist_names = sorted(list(dfs.values())[0]["distractor_name"].dropna().unique()) |
|
|
| rows = [] |
| for dname in dist_names: |
| row = {"distractor": dname} |
| for name, df in dfs.items(): |
| sub = df[df["distractor_name"] == dname] |
| valid = sub[col].notna() & sub["gt_label"].notna() |
| pred = predict(sub.loc[valid, col], thr) |
| row[name] = accuracy(pred, sub.loc[valid, "gt_label"]) |
| row[f"{name}_n"] = valid.sum() |
| rows.append(row) |
|
|
| dist_df = pd.DataFrame(rows).sort_values(model_names[0], ascending=False) |
| print(f"\n {'distractor':<32} {'N':>5}", end="") |
| for name in model_names: |
| print(f" {name:>26}", end="") |
| print() |
| print(" " + "─" * (39 + len(model_names) * 28)) |
| for _, r in dist_df.iterrows(): |
| n = int(r[f"{model_names[0]}_n"]) |
| print(f" {r['distractor']:<32} {n:>5}", end="") |
| for name in model_names: |
| v = r[name] |
| print(f" {'%.2f%%' % v if not np.isnan(v) else 'N/A':>26}", end="") |
| print() |
|
|
| |
| print_section(f"Accuracy by gt_label (CLAP @ T*={clap_t:.4f}){suffix}") |
| print(f" {'gt_label':<12} {'N':>6}", end="") |
| for name in model_names: |
| print(f" {name:>26}", end="") |
| print() |
| print(" " + "─" * (20 + len(model_names) * 28)) |
| for lbl in ["REMOVED", "PRESENT"]: |
| row_str = f" {lbl:<12}" |
| n_shown = False |
| for df in dfs.values(): |
| sub = df[df["gt_label"] == lbl] |
| valid = sub[col].notna() & sub["gt_label"].notna() |
| if not n_shown: |
| row_str += f" {valid.sum():>6}" |
| n_shown = True |
| pred = predict(sub.loc[valid, col], thr) |
| acc = accuracy(pred, sub.loc[valid, "gt_label"]) |
| row_str += f" {'%.2f%%' % acc if not np.isnan(acc) else 'N/A':>26}" |
| print(row_str) |
|
|
|
|
| |
|
|
| def main(): |
| parser = argparse.ArgumentParser( |
| description="GT event detection analysis: AUC + Youden's J threshold." |
| ) |
| parser.add_argument("--sisnr_threshold", type=float, default=None, |
| help="Override SI-SNR threshold (default: Youden's J from data)") |
| parser.add_argument("--nxcorr_threshold", type=float, default=None, |
| help="Override NXCorr threshold (default: Youden's J from data)") |
| parser.add_argument("--clap_threshold", type=float, default=None, |
| help="Override CLAP threshold (default: Youden's J from data)") |
| args = parser.parse_args() |
|
|
| dfs = {} |
| for name, model_path in MODELS_FINAL.items(): |
| p = model_path / TEST_3K_CSV |
| if not p.exists(): |
| print(f"[WARN] CSV not found: {p}") |
| continue |
| df = load_csv(p) |
| print(f"Loaded {len(df):>5} rows ({df['gt_label'].notna().sum()} with gt_label) ← {name}") |
| dfs[name] = df |
|
|
| if not dfs: |
| print("No CSVs found. Run the GT eval jobs first.") |
| return |
|
|
| print_score_stats(dfs) |
| youden_t = print_auc_and_youden(dfs) |
|
|
| |
| sisnr_t = args.sisnr_threshold if args.sisnr_threshold is not None else youden_t["si_snr_db"] |
| nxcorr_t = args.nxcorr_threshold if args.nxcorr_threshold is not None else youden_t["nxcorr"] |
| clap_t = args.clap_threshold if args.clap_threshold is not None else youden_t["clap_sim"] |
|
|
| label = "Youden's J pooled" if args.clap_threshold is None else "manual override" |
| analyse(dfs, sisnr_t, nxcorr_t, clap_t, label=label) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|