184 lines
6.2 KiB
Python
184 lines
6.2 KiB
Python
"""噪声鲁棒性实验。
|
||
|
||
做两组对照:
|
||
|
||
1. **信噪比消融**:固定预处理开,扫描 SNR 22 → 5 dB,看 Top-1 如何衰减;
|
||
2. **预处理消融**:固定若干 SNR,对比「去噪 + 带通」开/关的效果。
|
||
|
||
输出 ``data/noise_report.json``(网页端读取)、``data/noise_curve.csv``
|
||
(便于外部绘图),若装了 matplotlib 还会导出 PNG。
|
||
|
||
用法::
|
||
|
||
python -m scripts.noise_experiment
|
||
python -m scripts.noise_experiment --per-song 2 --levels 22,18,15,12.5,10,7.5,5
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import csv
|
||
import json
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||
|
||
from qbh.config import DEFAULT # noqa: E402
|
||
from qbh.evaluate import evaluate, make_query_specs # noqa: E402
|
||
from qbh.library import Library # noqa: E402
|
||
from qbh.search import SearchEngine # noqa: E402
|
||
from qbh.store import Store # noqa: E402
|
||
|
||
|
||
def _run_levels(
|
||
engine: SearchEngine,
|
||
library: Library,
|
||
levels: list[float],
|
||
*,
|
||
per_song: int,
|
||
seed: int,
|
||
preprocess_on: bool,
|
||
label: str,
|
||
) -> list[dict]:
|
||
rows: list[dict] = []
|
||
for snr in levels:
|
||
specs = make_query_specs(
|
||
library.melodies(),
|
||
n_per_song=per_song,
|
||
difficulty="normal",
|
||
seed=seed,
|
||
snr_db=snr,
|
||
)
|
||
# 通过覆写 engine.search_audio 的预处理开关来实现消融
|
||
original = engine.search_audio
|
||
|
||
def patched(samples, sr, *, top_k=None, cfg=None, **kw):
|
||
kw.setdefault("do_bandpass", preprocess_on)
|
||
kw.setdefault("do_denoise", preprocess_on)
|
||
return original(samples, sr, top_k=top_k, cfg=cfg, **kw)
|
||
|
||
engine.search_audio = patched # type: ignore[assignment]
|
||
try:
|
||
report = evaluate(engine, specs, label=f"{label}-{snr:g}dB", cfg=DEFAULT)
|
||
finally:
|
||
engine.search_audio = original # type: ignore[assignment]
|
||
|
||
rows.append(
|
||
{
|
||
"snr_db": snr,
|
||
"top1": report.top1,
|
||
"top3": report.top3,
|
||
"top5": report.top5,
|
||
"mrr": report.mrr,
|
||
"p50_ms": report.p50_latency_ms,
|
||
}
|
||
)
|
||
print(f" [{label}] SNR {snr:>5.1f} dB → Top-1 {report.top1*100:5.1f}% "
|
||
f"Top-5 {report.top5*100:5.1f}% MRR {report.mrr:.3f}")
|
||
return rows
|
||
|
||
|
||
def main() -> int:
|
||
parser = argparse.ArgumentParser(description="噪声鲁棒性实验")
|
||
parser.add_argument("--db", default="data/qbh.db")
|
||
parser.add_argument("--per-song", type=int, default=2)
|
||
parser.add_argument("--seed", type=int, default=20260908)
|
||
parser.add_argument("--levels", default="22,18,15,12.5,10,7.5,5")
|
||
parser.add_argument("--out", default="data/noise_report.json")
|
||
parser.add_argument("--csv", default="data/noise_curve.csv")
|
||
parser.add_argument("--png", default="data/noise_curve.png")
|
||
args = parser.parse_args()
|
||
|
||
levels = [float(v) for v in args.levels.split(",")]
|
||
store = Store(args.db)
|
||
library = Library(store, DEFAULT)
|
||
if library.count() == 0:
|
||
library.build()
|
||
engine = SearchEngine(library, DEFAULT)
|
||
|
||
print(f"曲库 {library.count()} 首,每首 {args.per_song} 条查询\n")
|
||
print("预处理开启(去噪 + 带通 60–2000 Hz):")
|
||
on_rows = _run_levels(
|
||
engine, library, levels, per_song=args.per_song, seed=args.seed,
|
||
preprocess_on=True, label="preprocess-on",
|
||
)
|
||
print("\n预处理关闭(原始波形直接送 YIN):")
|
||
off_rows = _run_levels(
|
||
engine, library, levels, per_song=args.per_song, seed=args.seed,
|
||
preprocess_on=False, label="preprocess-off",
|
||
)
|
||
|
||
# 找 50% Top-1 的拐点
|
||
def knee(rows: list[dict]) -> float | None:
|
||
for row in sorted(rows, key=lambda r: -r["snr_db"]):
|
||
if row["top1"] < 0.5:
|
||
return float(row["snr_db"])
|
||
return None
|
||
|
||
report = {
|
||
"levels": levels,
|
||
"per_song": args.per_song,
|
||
"seed": args.seed,
|
||
"n_songs": library.count(),
|
||
"curve": on_rows,
|
||
"baseline_no_preprocess": off_rows,
|
||
"knee_snr_db": knee(on_rows),
|
||
"note": (
|
||
"查询为合成哼唱(含颤音/滑音/丢音)按目标信噪比叠加白噪声;"
|
||
"knee_snr_db 表示 Top-1 首次跌破 50% 的信噪比。"
|
||
),
|
||
}
|
||
Path(args.out).write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
||
print(f"\n→ {args.out}")
|
||
|
||
csv_path = Path(args.csv)
|
||
csv_path.parent.mkdir(parents=True, exist_ok=True)
|
||
with csv_path.open("w", newline="", encoding="utf-8") as fh:
|
||
writer = csv.writer(fh)
|
||
writer.writerow(["mode", "snr_db", "top1", "top3", "top5", "mrr", "p50_ms"])
|
||
for mode, rows in (("preprocess-on", on_rows), ("preprocess-off", off_rows)):
|
||
for row in rows:
|
||
writer.writerow([mode, row["snr_db"], row["top1"], row["top3"],
|
||
row["top5"], row["mrr"], row["p50_ms"]])
|
||
print(f"→ {csv_path}")
|
||
|
||
try: # 可选:画图
|
||
import matplotlib
|
||
|
||
matplotlib.use("Agg")
|
||
import matplotlib.pyplot as plt
|
||
|
||
# 让中文标题正常显示(Windows 自带字体)
|
||
matplotlib.rcParams["font.sans-serif"] = [
|
||
"Microsoft YaHei", "SimHei", "DejaVu Sans"
|
||
]
|
||
matplotlib.rcParams["axes.unicode_minus"] = False
|
||
|
||
fig, ax = plt.subplots(figsize=(7, 4.2), dpi=140)
|
||
for mode, rows, style in (
|
||
("预处理开启", on_rows, "o-"),
|
||
("预处理关闭", off_rows, "s--"),
|
||
):
|
||
xs = [r["snr_db"] for r in rows]
|
||
ys = [r["top1"] * 100 for r in rows]
|
||
ax.plot(xs, ys, style, label=mode)
|
||
ax.set_xlabel("SNR (dB)")
|
||
ax.set_ylabel("Top-1 准确率 (%)")
|
||
ax.set_title("哼唱检索在不同信噪比下的 Top-1")
|
||
ax.invert_xaxis()
|
||
ax.grid(alpha=0.3)
|
||
ax.legend()
|
||
fig.tight_layout()
|
||
fig.savefig(args.png)
|
||
print(f"→ {args.png}")
|
||
except Exception as exc:
|
||
print(f"(跳过 PNG 绘图:{exc})")
|
||
|
||
store.close()
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|