Initial commit: 基于旋律的音乐哼唱检索系统 (Query by Humming)
This commit is contained in:
@@ -0,0 +1,183 @@
|
||||
"""噪声鲁棒性实验。
|
||||
|
||||
做两组对照:
|
||||
|
||||
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())
|
||||
@@ -0,0 +1,108 @@
|
||||
"""跑完整评测并输出可复现的报告。
|
||||
|
||||
用法::
|
||||
|
||||
python -m scripts.run_eval # 三个难度各跑一遍
|
||||
python -m scripts.run_eval --per-song 5 # 每首 5 条查询
|
||||
python -m scripts.run_eval --difficulty normal # 只跑中等难度
|
||||
python -m scripts.run_eval --markdown docs/评测报告.md
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
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
|
||||
|
||||
DIFFICULTIES = ("easy", "normal", "hard")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="QBH 评测")
|
||||
parser.add_argument("--db", default="data/qbh.db")
|
||||
parser.add_argument("--per-song", type=int, default=3)
|
||||
parser.add_argument("--seed", type=int, default=20260908)
|
||||
parser.add_argument("--top-k", type=int, default=10)
|
||||
parser.add_argument("--difficulty", default="all", choices=("all",) + DIFFICULTIES)
|
||||
parser.add_argument("--out-dir", default="data")
|
||||
parser.add_argument("--markdown", default="")
|
||||
parser.add_argument("--verbose", action="store_true")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
store = Store(args.db)
|
||||
library = Library(store, DEFAULT)
|
||||
if library.count() == 0:
|
||||
print("曲库为空,先构建…")
|
||||
library.build()
|
||||
engine = SearchEngine(library, DEFAULT)
|
||||
|
||||
difficulties = DIFFICULTIES if args.difficulty == "all" else (args.difficulty,)
|
||||
reports = []
|
||||
print(f"曲库 {library.count()} 首,每首 {args.per_song} 条查询,随机种子 {args.seed}\n")
|
||||
|
||||
for difficulty in difficulties:
|
||||
specs = make_query_specs(
|
||||
library.melodies(),
|
||||
n_per_song=args.per_song,
|
||||
difficulty=difficulty,
|
||||
seed=args.seed,
|
||||
)
|
||||
report = evaluate(
|
||||
engine, specs, label=difficulty, top_k=args.top_k, cfg=DEFAULT, verbose=args.verbose
|
||||
)
|
||||
reports.append(report)
|
||||
print(report.summary_line())
|
||||
print(f" 音符数比 {report.note_count_ratio:.2f} · "
|
||||
f"音高误差中位数 {report.pitch_err_median:.2f} 半音 · "
|
||||
f"平均排名 {report.mean_rank:.2f}")
|
||||
out = Path(args.out_dir) / f"eval_report_{difficulty}.json"
|
||||
report.save(out)
|
||||
print(f" → {out}")
|
||||
|
||||
# 网页端读取的主报告用中等难度
|
||||
primary = next((r for r in reports if r.label == "normal"), reports[0])
|
||||
primary.save(Path(args.out_dir) / "eval_report.json")
|
||||
|
||||
if args.markdown:
|
||||
lines = [
|
||||
"## 评测结果(合成哼唱查询 → 完整流水线)",
|
||||
"",
|
||||
f"- 曲库:**{primary.n_songs} 首**(27 首真实 MIDI + 16 首内置曲谱)",
|
||||
f"- 查询:每首 {args.per_song} 条,随机种子 {args.seed},共 {primary.n_queries} 条/难度",
|
||||
"- 查询扰动:移调 ±5 半音(12% 概率再 ±12)、速度 0.82–1.28×、"
|
||||
"逐音抖动 σ≈0.35 半音、丢音/劈音/插音、哼唱音色渲染、按 SNR 加噪",
|
||||
"",
|
||||
"| 难度 | Top-1 | Top-3 | Top-5 | Top-10 | MRR | 粗召回率 | 延迟 p50 | 延迟 p95 |",
|
||||
"|---|---:|---:|---:|---:|---:|---:|---:|---:|",
|
||||
]
|
||||
for report in reports:
|
||||
lines.append(
|
||||
f"| {report.label} | {report.top1*100:.1f}% | {report.top3*100:.1f}% | "
|
||||
f"{report.top5*100:.1f}% | {report.top10*100:.1f}% | {report.mrr:.3f} | "
|
||||
f"{report.candidate_recall*100:.1f}% | {report.p50_latency_ms:.0f} ms | "
|
||||
f"{report.p95_latency_ms:.0f} ms |"
|
||||
)
|
||||
lines += [
|
||||
"",
|
||||
"> 说明:查询由合成器生成,曲库中 27 首为真实 MIDI、16 首为内置曲谱,"
|
||||
"因此这组数字是**自洽基准**而非绝对泛化能力。噪声鲁棒性见"
|
||||
" `docs/评测报告.md` 的 SNR 消融章节。",
|
||||
"",
|
||||
]
|
||||
Path(args.markdown).write_text("\n".join(lines), encoding="utf-8")
|
||||
print(f"\nMarkdown 片段已写入 {args.markdown}")
|
||||
|
||||
store.close()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
"""参数调优:坐标下降法在固定查询集上搜索更好的排序参数。
|
||||
|
||||
为避免重复的音频处理开销,先一次性把查询音频转成旋律特征并缓存,
|
||||
之后只重跑「粗召回 + DTW 精排」,因此一轮扫描只需几十秒。
|
||||
|
||||
用法::
|
||||
|
||||
python -m scripts.tune [--per-song 3] [--rounds 2]
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import itertools
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
from qbh.config import DEFAULT, Config # noqa: E402
|
||||
from qbh.evaluate import make_query_specs, perturb_melody, synth_query_audio # noqa: E402
|
||||
from qbh.library import Library # noqa: E402
|
||||
from qbh.search import SearchEngine # noqa: E402
|
||||
from qbh.store import Store # noqa: E402
|
||||
|
||||
|
||||
def build_cache(engine: SearchEngine, specs, cfg: Config):
|
||||
"""预计算每条查询的旋律特征(音频处理只做一次)。"""
|
||||
melodies = {m.song_id: m for m in engine.library.melodies()}
|
||||
cache = []
|
||||
for spec in specs:
|
||||
source = melodies.get(spec.song_id)
|
||||
if source is None:
|
||||
continue
|
||||
truth = perturb_melody(source, spec, cfg)
|
||||
audio = synth_query_audio(truth, spec, cfg)
|
||||
from qbh.audio import preprocess
|
||||
from qbh.notes import segment_notes
|
||||
from qbh.pitch import extract_pitch
|
||||
|
||||
track = extract_pitch(preprocess(audio, cfg.sample_rate, cfg), cfg.sample_rate, cfg)
|
||||
cache.append((spec.song_id, segment_notes(track, cfg), truth.n_notes))
|
||||
return cache
|
||||
|
||||
|
||||
def score_config(library: Library, cache, cfg: Config, top_k: int = 10) -> float:
|
||||
engine = SearchEngine(library, cfg)
|
||||
hits = 0
|
||||
for answer, query, _ in cache:
|
||||
result = engine.search_melody(query, top_k=top_k, with_path=False)
|
||||
if result.hits and result.hits[0].song_id == answer:
|
||||
hits += 1
|
||||
return hits / max(len(cache), 1)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="QBH 排序参数调优")
|
||||
parser.add_argument("--per-song", type=int, default=3)
|
||||
parser.add_argument("--difficulty", default="normal")
|
||||
parser.add_argument("--rounds", type=int, default=2)
|
||||
parser.add_argument("--db", default="data/qbh.db")
|
||||
parser.add_argument("--out", default="data/tuning_report.json")
|
||||
args = parser.parse_args()
|
||||
|
||||
store = Store(args.db)
|
||||
library = Library(store, DEFAULT)
|
||||
engine = SearchEngine(library, DEFAULT)
|
||||
|
||||
specs = make_query_specs(
|
||||
library.melodies(), n_per_song=args.per_song, difficulty=args.difficulty, seed=20260908
|
||||
)
|
||||
print(f"查询数 {len(specs)},曲库 {library.count()} 首,预计算特征…")
|
||||
started = time.perf_counter()
|
||||
cache = build_cache(engine, specs, DEFAULT)
|
||||
print(f"缓存完成 {len(cache)} 条,用时 {time.perf_counter()-started:.1f}s")
|
||||
|
||||
grid = {
|
||||
"w_index": [0.0, 0.05, 0.1, 0.15, 0.2, 0.3, 0.4],
|
||||
"dtw_dur_weight": [0.0, 0.2, 0.35, 0.5, 0.7, 0.9],
|
||||
"dtw_pitch_free_band": [0.0, 0.2, 0.3, 0.5, 0.8],
|
||||
"dtw_score_lambda": [0.2, 0.32, 0.45, 0.6, 0.8],
|
||||
"transpose_span": [2, 3, 4, 6],
|
||||
}
|
||||
|
||||
def derive(cfg: Config, name: str, value) -> Config:
|
||||
"""w_index 与 w_dtw 是互补权重,需成对调整。"""
|
||||
if name == "w_index":
|
||||
return cfg.with_(w_index=value, w_dtw=1.0 - value)
|
||||
return cfg.with_(**{name: value})
|
||||
|
||||
current = DEFAULT
|
||||
best_score = score_config(library, cache, current)
|
||||
print(f"初始 Top-1 = {best_score*100:.1f}%")
|
||||
history = [{"config": current.to_dict(), "top1": best_score}]
|
||||
|
||||
for round_idx in range(args.rounds):
|
||||
improved = False
|
||||
for name, values in grid.items():
|
||||
best_value = getattr(current, name)
|
||||
for value in values:
|
||||
if value == best_value:
|
||||
continue
|
||||
candidate = derive(current, name, value)
|
||||
value_score = score_config(library, cache, candidate)
|
||||
if value_score > best_score + 1e-9:
|
||||
best_score, best_value, improved = value_score, value, True
|
||||
if best_value != getattr(current, name):
|
||||
current = derive(current, name, best_value)
|
||||
print(f" round{round_idx+1} {name} -> {best_value} Top-1={best_score*100:.1f}%")
|
||||
history.append({"config": current.to_dict(), "top1": best_score})
|
||||
if not improved:
|
||||
print(f" round{round_idx+1} 无改进,提前结束")
|
||||
break
|
||||
|
||||
print(f"\n最终 Top-1 = {best_score*100:.1f}%")
|
||||
diff = {k: v for k, v in current.to_dict().items() if getattr(DEFAULT, k) != v}
|
||||
print("相对默认值的改动:", json.dumps(diff, ensure_ascii=False, indent=2))
|
||||
|
||||
Path(args.out).write_text(
|
||||
json.dumps(
|
||||
{"best_top1": best_score, "config_diff": diff, "history": history},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
print(f"报告已写入 {args.out}")
|
||||
store.close()
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user