"""参数调优:坐标下降法在固定查询集上搜索更好的排序参数。 为避免重复的音频处理开销,先一次性把查询音频转成旋律特征并缓存, 之后只重跑「粗召回 + 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())