ハイブリッド検索
読了まで約66 分分、12 節 節の 12 例 例。
この章を終えると、字句的な順位付けと意味的な順位付けを、正規化したスコアの加算または逆順位融合(reciprocal rank fusion)によって一つの順位にまとめられるようになる。また、各順位付けの寄与の大きさを訓練クエリで調整し、その組み合わせが二つの入力のうち良いほうを上回るかどうかを、テストクエリでの対応のある検定によって判断できるようになる。
ストアは、家具・ホームグッズのカタログを二つの検索器で検索しており、第1章ではその二つを融合して一つの順位にした。この融合は、意味検索単独には勝てなかった。テストクエリでは、その融合のnDCG@10はnDCG@10が0.812であったのに対し、意味検索は0.830であった。この差は、第3章の検定でもどちらが優れるとも立証できない。そこでストアは、これまでで最良の順位付け器であり、したがって打ち負かすべき相手である意味検索を、より良い混合が上回れるのかどうかを知る必要がある。
そこでこの章では、まず、本書の基準であるステミングなしのBM25(bm25sの既定設定)と、オープンモデルSnowflake/snowflake-arctic-embed-m-v1.5で埋め込みを作る意味検索が、異なるクエリで失敗するのかどうかを問う。混合が効果を上げうるのは両者の失敗が異なる場合に限られるので、その上で、二通りの混合方法を調整する。
業界の検索システムでは、この二つを組み合わせることが多い。ある意味的な商品検索モデルは「アドホックな商品検索において字句検索エンジンを補完する」ように作られており(Nigam et al., 2019)、あるソーシャルネットワークの検索エンジンは、埋め込み検索とキーワードマッチングを併用して文書をスコア付けしている(Huang et al., 2020)。
ストアには、調整用の訓練クエリが50件、報告用のテストクエリが30件ある。この章では、各検索器が勝つクエリを調べ、各検索器を単独で検証する。次に、二つの混合を構成する。混合とは、各々の寄与の大きさを決める重みを使って、字句的な順位付けと意味的な順位付けを融合する方法であり、その重みを調整する。分析と調整のすべての手順は訓練クエリで行う。テストクエリでは、最後に一度だけ二つの比較を行う計画である。調整済みの各混合、すなわち重み付き和と重み付き逆順位融合を、それぞれ意味検索と比較する。
この部分はまだ翻訳されていないため、英語で表示している。
Find the queries each retriever wins
Hybrid retrieval combines the rankings of a lexical and a semantic retriever into one ranking. Combining rankings is called fusion. Fusion can only help if the two retrievers fail on different queries: if both put poor products first for a query, no mix of their rankings fixes it. Published studies find that they do. Embeddings miss rare entities and selective keywords that BM25 matches (chapter 6), and on a dataset built to test the limits of one embedding per text, BM25 finds what embeddings miss but loses most of its score when words are replaced with synonyms (chapter 1). So the first check is per query, not on average.
Score both of the store's retrievers by nDCG@10 on every train query, keeping each one's top 100.
1"""Scores BM25 and semantic retrieval on each train query and counts the queries each one wins, ties included.2The prose's point rests on the win counts and on the mean of the better score per query."""3import numpy as np45from lib.lexical import LexicalSearch6from lib.metrics import evaluate7from lib.semantic import SemanticSearch8from lib.store import load_products, load_queries, qrels910products, queries, judgments = load_products(), load_queries("train"), qrels("train")11bm25 = LexicalSearch(products).run(queries, k=100)12semantic = SemanticSearch().run(queries, k=100)13bm25_scores, semantic_scores = evaluate(bm25, judgments)["ndcg@10"], evaluate(semantic, judgments)["ndcg@10"]1415print("train queries:", len(queries))16print(f"bm25 ndcg@10: {bm25_scores.mean():.3f}")17print(f"semantic ndcg@10: {semantic_scores.mean():.3f}")18# rounded to 3 places, so differences that are float noise count as ties19lead = (bm25_scores - semantic_scores).round(3) # per train query; above 0 means BM25 wins20print("bm25 better:", (lead > 0).sum())21print("semantic better:", (lead < 0).sum())22print("tied:", (lead == 0).sum())23print(f"better of the two, chosen per query: {np.maximum(bm25_scores, semantic_scores).mean():.3f}")24has_digit = queries["query"].str.contains(r"\d")25print("queries with a digit:", has_digit.sum())26print("queries with a digit, bm25 better:", (lead[has_digit] > 0).sum())27print()28print("queries where bm25 leads by 0.1 or more:", (lead >= 0.1).sum())29print(queries.loc[lead[lead >= 0.1].index, "query"].to_string())
python bm25-semantic-wins-by-query.pytrain queries: 50
bm25 ndcg@10: 0.695
semantic ndcg@10: 0.772
bm25 better: 15
semantic better: 31
tied: 4
better of the two, chosen per query: 0.802
queries with a digit: 5
queries with a digit, bm25 better: 1
queries where bm25 leads by 0.1 or more: 6
query_id
44 chrome shower head and valve
146 laundry vanity cabinet
277 barstool patio sets
313 malachi sled
359 french molding
432 butcher block island
Neither retriever wins every query. Semantic retrieval averages 0.772 nDCG@10 against BM25's 0.695, but BM25 still wins 15 train queries to semantic retrieval's 31, and 4 tie.
If you could choose the better of the two for each query, the mean would be 0.802. That isn't a ceiling for fusion, which mixes the lists rather than choosing one, but it shows what the differences could be worth.
Next, see whether the two lists hold different products, and what share of each query's exact products (those the judges graded as fully matching) each list finds:
1"""Measures how much BM25's and semantic retrieval's top 10s overlap, and the share of each query's exact products2that each list, and their union, holds at depths 100 and 20. The prose's point rests on the union's shares at both depths."""3import numpy as np45from lib.lexical import LexicalSearch6from lib.metrics import recall_at_k7from lib.semantic import SemanticSearch8from lib.store import load_products, load_queries, qrels910products, queries, judgments = load_products(), load_queries("train"), qrels("train")11bm25 = LexicalSearch(products).run(queries, k=100)12semantic = SemanticSearch().run(queries, k=100)1314shared = [len(set(bm25[query_id][:10]) & set(semantic[query_id][:10])) for query_id in queries.index]15print(f"products in both top 10s, mean: {np.mean(shared):.1f}")161718def share_retrieved(run):19 """The share of each query's exact products that the run's list holds, averaged over queries."""20 # k is the whole list, so this is the share of exact products (grade 2) anywhere in it21 shares = [recall_at_k(ranking, judgments[query_id], k=len(ranking)) for query_id, ranking in run.items()]22 return np.mean(shares)232425for depth in [100, 20]:26 lists = {"bm25": {query_id: ranking[:depth] for query_id, ranking in bm25.items()},27 "semantic": {query_id: ranking[:depth] for query_id, ranking in semantic.items()}}28 # the union in first-seen order, without repeats29 lists["union"] = {query_id: list(dict.fromkeys(lists["bm25"][query_id] + lists["semantic"][query_id]))30 for query_id in queries.index}31 for name, run in lists.items():32 print(f"{name} top {depth}, share of exact products retrieved: {share_retrieved(run):.3f}")
python overlap-and-union-recall.pyproducts in both top 10s, mean: 3.7
bm25 top 100, share of exact products retrieved: 0.672
semantic top 100, share of exact products retrieved: 0.759
union top 100, share of exact products retrieved: 0.810
bm25 top 20, share of exact products retrieved: 0.297
semantic top 20, share of exact products retrieved: 0.353
union top 20, share of exact products retrieved: 0.445
The two top 10s share 3.7 products on average, so most of each is missing from the other. Fusion can't rank a product neither list holds, so each list's depth caps what fusion can reach. The union beats either list at both depths:
| Share of exact products retrieved | Top 20 | Top 100 |
|---|---|---|
| BM25 | 0.297 | 0.672 |
| Semantic retrieval | 0.353 | 0.759 |
| Union of both | 0.445 | 0.810 |
Two train queries show the kinds of failure:
1"""Prints the top 5 products of BM25 and semantic retrieval for two train queries, with their judgments, and counts2the exact products in each top 10. The prose's point rests on those exact counts and on the two spellings of 7qt."""3from lib.lexical import LexicalSearch4from lib.semantic import SemanticSearch5from lib.store import load_products, load_queries, product_text, qrels67LABELS = {2: "exact", 1: "partial", 0: "irrelevant"}8products, queries, judgments = load_products(), load_queries("train"), qrels("train")9bm25 = LexicalSearch(products).run(queries, k=10)10semantic = SemanticSearch().run(queries, k=10)11text = product_text(products)12# the size written as one token, `7qt`13print("products containing 7qt:", text.str.contains(r"\b7qt\b", case=False).sum())14# the size written apart, `7 qt`15print("products containing 7 qt:", text.str.contains(r"\b7 qt\b", case=False).sum())1617for query_id in [432, 62]: # butcher block island, 7qt slow cooker18 query = queries.at[query_id, "query"]19 for name, run in [("bm25", bm25), ("semantic", semantic)]:20 # grade 2 is exact, 1 partial, 0 irrelevant; None for a product nobody judged21 grades = [judgments[query_id].get(product_id) for product_id in run[query_id]]22 print()23 print(f"exact in {name} top 10 for {query}: {grades.count(2)}")24 for product_id, grade in list(zip(run[query_id], grades))[:5]:25 print(f" {LABELS.get(grade, 'unjudged'):<10} {products.at[product_id, 'name'][:55]}")
python two-queries-two-winners.pyproducts containing 7qt: 0
products containing 7 qt: 9
exact in bm25 top 10 for butcher block island: 9
exact carol kitchen island with butcher block top
exact brunton kitchen island with butcher block top
partial brunton kitchen cart butcher block top
exact janigian kitchen island with butcher block
exact avelar kitchen island with butcher block
exact in semantic top 10 for butcher block island: 3
partial boosblock® prep table with butcher block top
partial boosblock® butcher block
partial prep table
partial pro chef kitchen cart with butcher block top
exact brunton kitchen island with butcher block top
exact in bm25 top 10 for 7qt slow cooker: 1
partial cuisinart 6.5 quart programmable slow cooker
partial midea 6.5 qt . slow cooker
partial delonghi cks1660d livenza programmable 6 qt . slow cook
partial nesco 1.5 qt . analog slow cooker
partial 360 cookware gourmet slow cooker
exact in semantic top 10 for 7qt slow cooker: 7
exact 7-qt . stay or go slow cooker
exact crock-pot 7 qt . slow cooker
exact zing 7 qt . digital slow cooker
exact black + decker 7 qt . digital slow cooker
exact crock-pot 7 qt . slow cooker
For butcher block island, BM25's top 10 holds 9 exact products to semantic retrieval's 3. BM25 rewards products whose text contains all three words: kitchen islands with butcher-block tops. Semantic retrieval ranks prep tables and carts with butcher-block tops near the top too, and the judges graded those partial: the right material, but not the island the query asks for.
For 7qt slow cooker it's the other way round: BM25's top 10 holds 1 exact and semantic retrieval's 7. The catalog has 0 products whose text contains 7qt and 9 that contain 7 qt, so BM25 matches only slow cooker and ranks cookers of every size, while semantic retrieval puts 7-quart cookers first.
Those are single queries: they show a kind of failure, not its frequency. The per-query count lists the 6 train queries where BM25 leads by 0.1 nDCG@10 or more. Most name a specific kind of product in two or more words that all have to match, and one, malachi sled, names a product line.
Chapter 1 found BM25 ahead on 2 of the 2 test queries that give a size in inches, yet of the 5 train queries that contain a digit, BM25 wins 1.
Working rule: Before you fuse, count per query where each retriever wins on your train queries, and check how many relevant products the union of their lists holds that the better one misses. Consider fusing when each wins a real share of queries and the union holds more relevant products than either list. That is necessary, not sufficient: next, check each retriever alone, and test the tuned blend on held-out queries before you adopt it.
融合の前に各検索器を検証する
各検索器がどこで優れているかを知るだけでは十分ではない。融合では、弱い入力も含めてすべての入力が最終的な順位付けに影響を及ぼすからである。11 個のデータセットを対象にしたハイブリッド検索の研究では「最弱リンク」効果が報告された。弱い検索器が 1 つあるだけで、融合結果の精度が大きく引き下げられうるため、融合の前に各検索器を検証しておく必要がある(Wang et al., PVLDB 2026)。そこで、各検索器の平均 nDCG@10 を比較し、あわせて judged@10 も確認する。続いて、対応のある検定でクエリごとに比較する。2 つの検索器の性能が等しいと仮定したとき、これほど大きな平均差が生じる確率はどれほどか、という問いである。本書で用いる検定は順列検定であり、対応のある t 検定を併記する。
第 1 章と同様に、BM25 と意味検索を逆順位融合(RRF)で融合する。各商品は、それぞれの順位付けで 1 / (60 + その順位) のスコアを得て、2 つの順位付けにわたって合計される。したがって、各順位付けの票の重みは等しい。次に、学習用クエリを勝者別に分け、融合と意味検索単独を比較する。
1"""Compares BM25, semantic retrieval and their RRF fusion on the train queries, then splits the queries by which2retriever wins. The prose's point rests on the hybrid-minus-semantic lines, which give the net change, and on the mean3change within each winning group."""4from lib.fusion import reciprocal_rank_fusion5from lib.lexical import LexicalSearch6from lib.metrics import evaluate7from lib.semantic import SemanticSearch8from lib.significance import compare9from lib.store import load_products, load_queries, qrels1011products, queries, judgments = load_products(), load_queries("train"), qrels("train")12bm25 = LexicalSearch(products).run(queries, k=100)13semantic = SemanticSearch().run(queries, k=100)14hybrid = reciprocal_rank_fusion([bm25, semantic]) # k = 60 and equal votes, as in chapter 115bm25_scores, semantic_scores, hybrid_scores = (evaluate(run, judgments) for run in (bm25, semantic, hybrid))1617print(f"bm25 judged@10: {bm25_scores['judged@10'].mean():.3f}")18print(f"semantic judged@10: {semantic_scores['judged@10'].mean():.3f}")19for name, after, before in [("semantic minus bm25", semantic_scores, bm25_scores),20 ("hybrid minus semantic", hybrid_scores, semantic_scores)]:21 result = compare(after["ndcg@10"], before["ndcg@10"]) # paired by query22 print(f"{name}, mean ndcg@10: {result['mean difference']:.3f}")23 print(f"{name}, permutation p: {result['permutation p']:.3f}")24 print(f"{name}, t-test p: {result['t-test p']:.3f}")25print()2627# rounded to 3 places, so float noise can't make a query a win or a loss28change = (hybrid_scores["ndcg@10"] - semantic_scores["ndcg@10"]).round(3) # fusion against semantic alone29lead = (bm25_scores["ndcg@10"] - semantic_scores["ndcg@10"]).round(3) # above 0 means BM25 wins30for name, group in [("bm25 wins", lead > 0), ("semantic wins", lead < 0)]:31 print(f"{name}, queries: {group.sum()}")32 print(f"{name}, fusion better than semantic: {(change[group] > 0).sum()}")33 print(f"{name}, fusion worse than semantic: {(change[group] < 0).sum()}")34 print(f"{name}, mean change in ndcg@10: {change[group].mean():.3f}")
python fusion-gain-by-winning-retriever.pybm25 judged@10: 0.930
semantic judged@10: 0.964
semantic minus bm25, mean ndcg@10: 0.077
semantic minus bm25, permutation p: 0.003
semantic minus bm25, t-test p: 0.004
hybrid minus semantic, mean ndcg@10: 0.002
hybrid minus semantic, permutation p: 0.863
hybrid minus semantic, t-test p: 0.872
bm25 wins, queries: 15
bm25 wins, fusion better than semantic: 12
bm25 wins, fusion worse than semantic: 2
bm25 wins, mean change in ndcg@10: 0.101
semantic wins, queries: 31
semantic wins, fusion better than semantic: 5
semantic wins, fusion worse than semantic: 25
semantic wins, mean change in ndcg@10: -0.045
BM25 の judged@10 は 0.930 であり、意味検索の 0.964 と比べると、つまり、BM25 の上位 10 件には、誰も判定していない商品がやや多く含まれる。そうした商品がスコアを下げうることは第 2 章で示した。意味検索は nDCG@10 で 0.077 上回り、順列検定の p 値は 0.003、t 検定の p 値は 0.004 である。テスト用クエリでも、第 3 章で同じ優位が確認されている。したがって、このストアには強い検索器と弱い検索器が 1 つずつある。
勝者別に分けると、融合は BM25 が勝つクエリでは平均して改善をもたらし、意味検索が勝つクエリでは悪化をもたらす。
| 勝つ検索器 | クエリ数 | 融合が意味検索より良い | 融合が意味検索より悪い | nDCG@10 の平均変化 |
|---|---|---|---|---|
| BM25 が勝つ | 15 | 12 | 2 | 0.101 |
| 意味検索が勝つ | 31 | 5 | 25 | -0.045 |
勝者でクエリを分けるとこのパターンは必然的に現れる。BM25 が勝つクエリではほぼどんな混合でも改善し、負けるクエリでは悪化するからである。重要なのは、すべての学習用クエリにわたる正味の変化である。融合は意味検索と比べて nDCG@10 が平均で 0.002 異なり、順列検定の p 値は 0.863 である。これらのクエリでは、等しい票を与えても測定可能な改善は得られない。
この分割は、どちらの検索器が勝つかを判定するのに判定データを用いる。したがって、パターンの診断には使えるが、判定データのない実運用のクエリに対して検索器を選ぶ用途には使えない。
実践ルール: 融合の前に、学習用クエリで各検索器を単独で検証する。検証には judged@10 と対応のある検定を用いる。一方が弱く、勝つクエリも少ない場合は、等しい票を与えてはならない。重みを付けてその重みを調整するか、その検索器を除外する。等しい票が適しているのは、品質がほぼ同じ 2 つの検索器の場合である。
スコアを足し合わせる前に正規化する
より弱い検索器(この店舗ではBM25)の発言力を小さくする最も直接的な方法は、二つの検索器のスコアに重みを付けて足し合わせることである。すなわち、意味検索のスコアのα倍に、BM25のスコアの(1 − α)倍を加える。重みの合計が1になる和を凸結合、または重み付き和という。ただし、これはスコアの尺度が同程度である場合にしか機能しない。ここでは尺度が揃っていない。BM25のスコアには決まった範囲がなく、クエリの語の数が多く、語が希少であるほど大きくなる。一方、意味検索のスコアであるコサイン類似度は−1から1の間に収まる。スコア正規化は、足し合わせる前にクエリごとに各検索器のスコアを再スケーリングする。クエリごとのmin-maxスケーリングは、そのクエリでランク付けされた商品のうち最も低いスコアを0に、最も高いスコアを1に写す。融合関数を調べた研究は、これを「文献における事実上の標準的な方法」と呼び、二つの代替手法を検証している(Bruch et al., 2023)。理論的min-maxは、観測された最小値の代わりに、各スコアが取りうる最小値を用いる。BM25では0、コサイン類似度では−1である。zスコアは、クエリのスコアから平均を引き、標準偏差で割る。例に共通のモジュールlib/blend.pyは、これらをそれぞれ数行で記述している。
min-max(s) = (s − lowest score among the query's candidates) / (highest − lowest)
blend = α · min-max(similarity) + (1 − α) · min-max(BM25)
和を計算するには、ランク付けする全商品について両方のスコアが必要である。クエリの候補集合は、BM25の上位100件と意味検索の上位100件の和集合であり、lib.blend.candidatesは、その集合に含まれる全商品について両方のスコアを取得する。すなわち、BM25のスコア(商品がクエリと語を共有しない場合は0)とコサイン類似度である。
まず、学習クエリで店舗の生のスコアをα = 0.5で足し合わせ、次にmin-maxスケーリングの後で同じ計算を行う。例の中で手作業で書き下し、lib.blend.weighted_sumと照合している。
1"""Adds BM25 and cosine scores with equal weights, raw and after min-max scaling, and checks the scaled sum against2lib.blend.weighted_sum. The prose's point rests on the two sums' top 10 overlaps and nDCG@10, and on the count of3train queries where the by-hand ranking matches the library's."""4from lib.blend import candidates, weighted_sum5from lib.lexical import LexicalSearch6from lib.metrics import evaluate7from lib.semantic import SemanticSearch8from lib.significance import compare9from lib.store import load_products, load_queries, qrels1011products, queries, judgments = load_products(), load_queries("train"), qrels("train")12lexical, semantic = LexicalSearch(products), SemanticSearch()13tables = candidates(lexical, semantic, queries) # both scores for each query's candidates1415# the candidate tables are keyed by query_id16table = tables[36] # laundry basket with wheels17print("candidates for laundry basket with wheels:", len(table))18print(f"bm25 range: {table['bm25'].min():.3f} to {table['bm25'].max():.3f}")19print(f"similarity range: {table['similarity'].min():.3f} to {table['similarity'].max():.3f}")202122def min_max(scores):23 return (scores - scores.min()) / (scores.max() - scores.min())242526def blend(normalize, alpha=0.5):27 run = {}28 for query_id, table in tables.items():29 score = alpha * normalize(table["similarity"]) + (1 - alpha) * normalize(table["bm25"])30 # the top 100; the stable sort keeps the candidates' order on equal scores31 run[query_id] = list(score.sort_values(ascending=False, kind="stable").index[:100])32 return run333435top_10s = {"bm25": lexical.run(queries, k=10), "semantic": semantic.run(queries, k=10)}36per_query = {}37for name, normalize in [("raw", lambda scores: scores), ("min-max", min_max)]:38 run = blend(normalize)39 per_query[name] = evaluate(run, judgments)["ndcg@10"]40 print(f"{name} sum ndcg@10: {per_query[name].mean():.3f}")41 for other, top in top_10s.items():42 shared = [len(set(run[query_id][:10]) & set(top[query_id])) for query_id in queries.index]43 print(f"{name} sum, products shared with the {other} top 10: {sum(shared) / len(shared):.1f}")44# the library sorts equal scores by product_id; this blend keeps the candidates' order45by_hand, library = blend(min_max), weighted_sum(tables, 0.5)46matches = sum(by_hand[query_id] == library[query_id] for query_id in tables)47print(f"train queries ranked as lib.blend.weighted_sum ranks them: {matches} of {len(tables)}")48p_value = compare(per_query["min-max"], per_query["raw"])["permutation p"] # a tuning check on train49print("min-max minus raw, permutation p:", "below 0.001" if p_value < 0.001 else f"{p_value:.3f}")
python raw-scores-versus-min-max.pycandidates for laundry basket with wheels: 125
bm25 range: 2.059 to 8.229
similarity range: 0.336 to 0.597
raw sum ndcg@10: 0.706
raw sum, products shared with the bm25 top 10: 9.6
raw sum, products shared with the semantic top 10: 3.9
min-max sum ndcg@10: 0.771
min-max sum, products shared with the bm25 top 10: 6.5
min-max sum, products shared with the semantic top 10: 6.2
train queries ranked as lib.blend.weighted_sum ranks them: 50 of 50
min-max minus raw, permutation p: below 0.001
laundry basket with wheelsでは、125件の候補のBM25スコアは2.059 to 8.229の範囲、類似度は0.336 to 0.597の範囲にある。BM25の広がりは何倍も大きく、そのため生のスコアの和の順序はBM25が決める。学習クエリ全体で平均すると、生のスコアの和の上位10件は、BM25の上位10件と9.6件、意味検索の上位10件と3.9件の商品を共有する。
重みは「半分ずつ」と述べているが、順位付けはほとんどBM25のものである。生のスコアの和のnDCG@10である0.706は、BM25の0.695に近い。
min-maxスケーリングの後では、両方の検索器が発言力を持つ。スケーリング後の和の上位10件は、BM25の上位10件と6.5件、意味検索の上位10件と6.2件の商品を共有し、nDCG@10は0.771に上がる。生のスコアの和との差に対する順列検定のp値はbelow 0.001である。手作業版は、50 of 50の学習クエリをlib.blend.weighted_sumとまったく同じ順位に並べる。
生のスコアでも、重みを調整すれば機能しうる。埋め込みベースの検索器であるDPRの著者らは、BM25にDPRの類似度の1.1倍を加えた値で候補を順位付けしており、1.1は開発セットで選ばれている(Karpukhin et al., 2020)。正規化を行うと、αはどのクエリでも同じ意味を持つ。正規化しなければ、BM25の発言力の割合はその範囲に応じてクエリごとに変わる。ただし、min-maxは絶対的な尺度ではない。クエリの候補に対する相対値であるため、最良の候補は、それがどれほど質の低いものであっても、常に1を得る。
実践ルール: 生のBM25スコアとコサイン類似度を、推測した重みで足し合わせてはならない。既定の方法としては、どちらのスコア関数についても知識を必要としないクエリごとのmin-maxを推奨する。各スコアの取りうる最小値が分かっていて、候補によって動かない下限が欲しい場合は、理論的min-maxを用いる。いずれの場合も、αは学習クエリで調整する。
逆順位融合の設定を訓練クエリで検証する
順位はスコアと違って共通の尺度をもつため、順位による融合には正規化が要らない。逆順位融合(reciprocal rank fusion, RRF)は、各商品が含まれる順位リストのそれぞれについて、定数 k とその順位の和で 1 を割った値を足し合わせて、商品のスコアとする(Cormack et al., 2009)。これは第1章の式に書いたとおりである。その代償は情報の損失である。「RRF は順位の関数であるため、スコアの分布を無視し、したがって有用な情報を捨てている」(Bruch et al., 2023)。首位のすぐ後ろにいる商品と、首位から大きく離れた商品とでも、スコアは順位だけで決まる。
定数 k は、上位の順位がどれだけ強く効くかを決める。第1章では RRF の考案者らに従って k = 60 を採用した。彼らは予備実験で、60 が最良値に近く、正確な値の選び方はほとんど影響しないことを見いだしている。この予備実験では、一つの検索エンジンである Wumpus Search の 30 通りの構成を、共同検索評価のシリーズである TREC のコレクションで融合した(Cormack et al., 2009)。Bruch らは、語彙的な検索器と意味的な検索器を一つずつ融合し、それぞれに固有の定数 η を与えた。その結果、定数間のバランスに対して結果が敏感であることを見いだした。このバランスは重みとして働く。「意味モデルがすでに高い性能を示している場合には、例えば η_Lex を大きくして語彙システムを割り引くと、性能が向上する」。ストアのように二つの順位リストで一つの k を共有する場合、両者の間にバランスは設定されない。
各リストの深さも影響する。一方の検索器の上位 20 件に入り、もう一方の上位 20 件には入らない商品は、後者では低い順位をもつにもかかわらず、その順位リストからは何も得られない。Bruch らが述べるように、「順位は、すべてのクエリについて検索システム o がコレクション D 全体を順位付けしない限り、正確には計算できない」。ストアの訓練クエリでは、上位 20 件のリスト二つの和集合に含まれる正解商品は、上位 100 件のリスト二つの和集合よりもはるかに少ない。これは各リストに含まれる正解商品の割合が示すとおりである。
深さ 100 のリストを融合し、訓練クエリで k の六つの値を試す。実行前に一つの検証を計画しておく。最良の k は、既定値の k = 60 を上回るか。
1"""Fuses BM25 and semantic retrieval with six values of k on the train queries, and tests the best k against the2default k = 60. The prose's point rests on the rank ratios at k = 1 and k = 60, on the best k, and on its permutation3p-value."""4from lib.fusion import reciprocal_rank_fusion5from lib.lexical import LexicalSearch6from lib.metrics import evaluate7from lib.semantic import SemanticSearch8from lib.significance import compare9from lib.store import load_products, load_queries, qrels1011products, queries, judgments = load_products(), load_queries("train"), qrels("train")12bm25 = LexicalSearch(products).run(queries, k=100)13semantic = SemanticSearch().run(queries, k=100)1415# RRF gives rank r the score 1 / (k + r), so rank 1 over rank 10 is (k + 10) / (k + 1)16for k in [1, 60]:17 print(f"rank 1 over rank 10 at k={k}: {(1 / (k + 1)) / (1 / (k + 10)):.3f}")18scores = {k: evaluate(reciprocal_rank_fusion([bm25, semantic], k=k), judgments)["ndcg@10"]19 for k in [1, 10, 30, 60, 100, 300]}20for k, per_query in scores.items():21 print(f"k={k} ndcg@10: {per_query.mean():.3f}")2223best = max(scores, key=lambda k: scores[k].mean()) # ties go to the smaller k24print("best k on train:", best)25result = compare(scores[best], scores[60]) # the planned check: best k against the default26print(f"best k minus k=60: {result['mean difference']:.3f}")27print(f"best k minus k=60, permutation p: {result['permutation p']:.3f}")28print(f"best k minus k=60, t-test p: {result['t-test p']:.3f}")29print(f"best k minus k=60, 95% interval: {result['ci low']:.3f} to {result['ci high']:.3f}")30print(f"best k minus k=60, wins, losses, ties: {result['wins']}, {result['losses']}, {result['ties']}")
python rrf-k-on-train.pyrank 1 over rank 10 at k=1: 5.500
rank 1 over rank 10 at k=60: 1.148
k=1 ndcg@10: 0.753
k=10 ndcg@10: 0.770
k=30 ndcg@10: 0.771
k=60 ndcg@10: 0.774
k=100 ndcg@10: 0.778
k=300 ndcg@10: 0.777
best k on train: 100
best k minus k=60: 0.004
best k minus k=60, permutation p: 0.093
best k minus k=60, t-test p: 0.103
best k minus k=60, 95% interval: 0.001 to 0.011
best k minus k=60, wins, losses, ties: 6, 3, 41
k = 1 では、順位 1 は順位 10 の 5.500 倍のスコアを得る。k = 60 では 1.148 倍となり、両方のリストの上位にある商品は、片方のリストの上位にしかない商品を上回る。k = 1 から k = 300 までの六つの設定のスコアは、0.753、0.770、0.771、0.774、0.778、0.777 である。
訓練データでの最良の設定は k = 100 であり、k = 60 を 0.004 上回る。並べ替え検定の p 値は 0.093、t 検定の p 値は 0.103 である。本書は判定を並べ替え検定に基づいて下すが、この検定では、この改善が偶然によるものかどうかを 0.05 の水準で区別できない。改善の 95% ブートストラップ区間 0.001 to 0.011 は 0 を含まないため、この区間は二つの検定のどちらとも食い違う。
二つの設定の順位が異なるクエリは、ごくわずかである(勝ち、負け、引き分けの数:6, 3, 41)。どの k が最良かという点も不安定である。BM25 で同点の商品を逆の順序に並べると、代わりに k = 300 が勝つ。これは、k の選び方はほとんど影響しないという Cormack らの知見と合致する。
実践ルール: k = 60 を既定値として保ち、リストは少なくとも深さ 100 で融合する。深いリストは候補を増やすだけで、減らすことはないからである。k = 60 から離れるのは、訓練データでの最良の k が、並べ替え検定で偶然と区別できる差、すなわち p が 0.05 を下回る差でこれを上回る場合に限る。ストアのように、一方の検索器がより強い場合、変えるべき設定は k ではなく、RRF の等しい投票のほうである。順位リストに重みを与え、それを調整するのである。
学習クエリでブレンドの重みを調整する
この章の二つのブレンドは、それぞれ一つの重み α を取る。α は意味検索に与える割合である。重み付き和では、α を正規化した類似度に掛け、1 − α を正規化した BM25 スコアに掛ける。重み付き RRF では、商品のスコアは (1 − α) / (k + その商品の BM25 順位) と α / (k + その商品の意味検索順位) の和になる。どちらの場合も、α = 0 は BM25 のみ、α = 1 は意味検索のみを表す。RRF では、α = 0.5 は第 1 章の重みなし融合の各スコアをすべて半分にしたものに等しい。ここでは、説明のために α = 0.75 とおき、ある学習クエリの先頭商品について計算を示す。
1"""Scores every candidate for one train query by weighted RRF, by hand, and checks the ranking against2lib.blend.weighted_rrf. The prose's point rests on the top product's two ranks and its score, and on the count of3places that match the library."""4from lib.blend import weighted_rrf5from lib.lexical import LexicalSearch6from lib.semantic import SemanticSearch7from lib.store import load_products, load_queries89alpha, k = 0.75, 60 # an illustrative weight; tuning picks one on train10products, queries = load_products(), load_queries("train")11bm25 = LexicalSearch(products).run(queries, k=100)12semantic = SemanticSearch().run(queries, k=100)13query_id = 36 # laundry basket with wheels141516def part(ranking, weight, product_id):17 """weight / (k + rank) from one ranking, or 0 when the product isn't in it."""18 # index counts from 0, so one is added to get the rank19 return weight / (k + ranking.index(product_id) + 1) if product_id in ranking else 0.0202122candidates = dict.fromkeys(bm25[query_id] + semantic[query_id]) # the union, in the order first seen23score = {product_id: part(bm25[query_id], 1 - alpha, product_id) + part(semantic[query_id], alpha, product_id)24 for product_id in candidates}25ranking = sorted(score, key=lambda product_id: (-score[product_id], product_id)) # ties by product_id26first = ranking[0]27print("first product:", products.at[first, "name"])28print("its bm25 rank:", bm25[query_id].index(first) + 1)29print("its semantic rank:", semantic[query_id].index(first) + 1)30print(f"its weighted rrf score: {score[first]:.5f}")31library = weighted_rrf(bm25, semantic, alpha)[query_id] # the top 10032matches = sum(mine == theirs for mine, theirs in zip(ranking, library))33print(f"places that match lib.blend.weighted_rrf: {matches} of {len(library)}")
python weighted-rrf-one-product.pyfirst product: laundry sorter basket on wheels
its bm25 rank: 1
its semantic rank: 2
its weighted rrf score: 0.01620
places that match lib.blend.weighted_rrf: 100 of 100
laundry basket with wheels について、先頭の商品 laundry sorter basket on wheels は BM25 の順位で 1 位、意味検索の順位で 2 位にある。したがってそのスコアは 0.25 / (60 + 1) + 0.75 / (60 + 2) = 0.01620 となる。
この例はすべての候補をこのように採点する。その順位付けは、100 of 100 か所で lib.blend.weighted_rrf と一致する。
調整では、学習クエリに対して α の値をグリッドで試し、平均 nDCG@10 が最良となるものを採用する。Bruch et al. (2023) は、凸結合(CC)の調整について三つの知見を報告している。調整済みの CC はどの正規化を用いてもほぼ同程度の性能を示すこと、領域内でも領域外でも RRF を上回ること、そして標本効率が高いことである。標本効率が高いとは、α が「学習データの 5% 未満」で収束したという意味であり、この割合は、このストアのものよりはるかに大きな学習セットに対するものである。
重み付き和については、三つの正規化のそれぞれで α を 0, 0.1, … 1 にわたって調整し、重み付き RRF については k = 60 で調整する。続いて、調整の検証として、各正規化を min-max と比較して検定し、さらにテストクエリに持ち込む二つのブレンドを意味検索と比較して検定する。
1"""Tunes α on the train queries for the weighted sum under three normalizations and for weighted RRF, then compares2the two blends that go to test with semantic retrieval. The prose's point rests on each setting's best α and nDCG@10,3on the p-values against tuned min-max, and on the two gains over semantic retrieval."""4from lib.blend import ALPHAS, NORMALIZATIONS, best_alpha, candidates, scores_by_alpha, weighted_rrf, weighted_sum5from lib.lexical import LexicalSearch6from lib.semantic import SemanticSearch7from lib.significance import compare8from lib.store import load_products, load_queries, qrels910products, queries, judgments = load_products(), load_queries("train"), qrels("train")11lexical, semantic = LexicalSearch(products), SemanticSearch()12tables = candidates(lexical, semantic, queries)13bm25, semantic_run = lexical.run(queries, k=100), semantic.run(queries, k=100)1415per_query = {} # nDCG@10 per query (rows) and alpha (columns)16for name in NORMALIZATIONS:17 per_query[name] = scores_by_alpha(lambda alpha: weighted_sum(tables, alpha, name), judgments)18per_query["weighted rrf"] = scores_by_alpha(lambda alpha: weighted_rrf(bm25, semantic_run, alpha), judgments)19semantic_alone = per_query["min-max"][1.0] # alpha = 1 is semantic retrieval in either blend20print("alphas tried:", len(ALPHAS))21print("min-max ndcg@10 for alpha 0 to 1:", " ".join(f"{mean:.3f}" for mean in per_query["min-max"].mean()))22print(f"semantic alone ndcg@10: {semantic_alone.mean():.3f}")23# alpha 0.5 is unweighted RRF, chapter 1's fusion24print(f"unweighted rrf (alpha 0.5) ndcg@10: {per_query['weighted rrf'][0.5].mean():.3f}")2526best = {name: frame[best_alpha(frame)] for name, frame in per_query.items()}27for name, frame in per_query.items():28 print(f"{name} best alpha: {best_alpha(frame)}")29 print(f"{name} best ndcg@10: {best[name].mean():.3f}")30for name in ["theoretical min-max", "z-score", "weighted rrf"]: # each tuned, against tuned min-max31 print(f"{name} against min-max, permutation p: {compare(best[name], best['min-max'])['permutation p']:.3f}")32for name in ["min-max", "weighted rrf"]: # the two blends that go to test33 gain = compare(best[name], semantic_alone)34 print(f"{name} gain over semantic: {gain['mean difference']:.3f}")35 print(f"{name} gain over semantic, permutation p: {gain['permutation p']:.3f}")36 print(f"{name} gain over semantic, t-test p: {gain['t-test p']:.3f}")
python tune-blend-weights-on-train.pyalphas tried: 11
min-max ndcg@10 for alpha 0 to 1: 0.695 0.709 0.736 0.746 0.758 0.771 0.781 0.784 0.777 0.778 0.772
semantic alone ndcg@10: 0.772
unweighted rrf (alpha 0.5) ndcg@10: 0.774
min-max best alpha: 0.7
min-max best ndcg@10: 0.784
theoretical min-max best alpha: 0.9
theoretical min-max best ndcg@10: 0.789
z-score best alpha: 0.7
z-score best ndcg@10: 0.787
weighted rrf best alpha: 0.6
weighted rrf best ndcg@10: 0.787
theoretical min-max against min-max, permutation p: 0.164
z-score against min-max, permutation p: 0.349
weighted rrf against min-max, permutation p: 0.776
min-max gain over semantic: 0.013
min-max gain over semantic, permutation p: 0.177
min-max gain over semantic, t-test p: 0.161
weighted rrf gain over semantic: 0.015
weighted rrf gain over semantic, permutation p: 0.215
weighted rrf gain over semantic, t-test p: 0.205
同じクエリで意味検索のみのスコアは 0.772 である。各設定の最良の α とスコアは次のとおりである。
| 設定 | 最良の α | 平均 nDCG@10 | 調整済み min-max に対する並べ替え検定の p |
|---|---|---|---|
| 重み付き和、min-max | 0.7 | 0.784 | — |
| 重み付き和、理論上の min-max | 0.9 | 0.789 | 0.164 |
| 重み付き和、z スコア | 0.7 | 0.787 | 0.349 |
| 重み付き RRF、k = 60 | 0.6 | 0.787 | 0.776 |
有意水準 0.05 では、学習クエリでの検定は、どちらの代替正規化も min-max と区別できない。これは、正規化はほとんど影響しないという Bruch et al. の知見に合致する。重み付き RRF も、調整済み min-max と区別できない。重み付き和が RRF を上回るという Bruch et al. の第二の知見はここには現れず、これらのクエリでは決着をつけることができない。
調整済みのブレンドは、グリッドに α = 1 が含まれるため、学習クエリでは少なくとも意味検索と同等のスコアを示す。しかし、ブレンドを選んだそのクエリ上でさえ、並べ替え検定は、どちらのブレンドの向上も 0.05 の水準では偶然と区別できない。重み付き和の向上は 0.013 で、並べ替え検定の p 値は 0.177 である。重み付き RRF の向上は 0.015 で、p 値は 0.215 である。各向上は、同じクエリで 11 通りを試した中の最良値でもあり、そのぶん実際より良く見える。
実践ルール: 学習クエリで粗いグリッドを用いて重みを一つ調整し、別の正規化が、学習クエリでの検定により偶然と区別でき p が 0.05 未満となる差で min-max を上回らない限り、正規化は min-max のままにする。最良の単独検索器に対する学習時の向上は楽観的な値として扱い、テストクエリでは縮むものと考えておく。これは、複数の候補から最良のものとして選んだ設定であれば何にでも当てはまる経験則である。設定を信頼する前に、それが安定していることを確認し、そのうえでテストクエリで報告する。
調整した重みが安定しているかを確認する
調整した重みは数十件のクエリから得られたものであり、どのクエリを持っていたかに左右される可能性がある。ブートストラップを使うと、その影響の大きさがわかる。train クエリを再標本化し、各標本で α を調整し、これを何度も繰り返す。選ばれた α が大きく変動するなら、調整された値はストアよりも標本を反映していることになる。第3章では、同じ再標本化を用いてスコアに区間を付ける。
固定したシードで train クエリを1000回再標本化し、調整対象の2つのブレンド、すなわち min-max スコアの重み付き和と重み付き RRF について、同じ再標本のもとで各 α が選ばれる回数を数える。
1"""Resamples the train queries with a fixed seed and counts which α wins each resample, for the weighted sum and for2weighted RRF on the same resamples. The prose's point rests on the α tuned on all train queries and on the counts of3resamples choosing each α."""4import numpy as np5import pandas as pd67from lib.blend import best_alpha, candidates, scores_by_alpha, weighted_rrf, weighted_sum8from lib.lexical import LexicalSearch9from lib.semantic import SemanticSearch10from lib.store import load_products, load_queries, qrels1112products, queries, judgments = load_products(), load_queries("train"), qrels("train")13lexical, semantic = LexicalSearch(products), SemanticSearch()14tables = candidates(lexical, semantic, queries)15bm25, semantic_run = lexical.run(queries, k=100), semantic.run(queries, k=100)16blends = {"weighted sum": scores_by_alpha(lambda alpha: weighted_sum(tables, alpha), judgments),17 "weighted rrf": scores_by_alpha(lambda alpha: weighted_rrf(bm25, semantic_run, alpha), judgments)}1819resamples = 100020print("resamples:", resamples)21# a fixed seed, so every run draws the same resamples22rng = np.random.default_rng(2026)23draws = [rng.integers(0, len(queries), len(queries)) for _ in range(resamples)] # the same draws for both24for name, per_query in blends.items(): # per_query: train queries x alphas25 print(f"{name} alpha tuned on all train queries: {best_alpha(per_query)}")26 # best alpha per resample; idxmax takes the first, smaller alpha when two tie27 chosen = pd.Series([per_query.iloc[draw].mean().idxmax() for draw in draws])28 for alpha, count in chosen.value_counts().sort_index().items():29 print(f"{name} resamples choosing alpha {alpha}: {count}")
python blend-weight-bootstrap.pyresamples: 1000
weighted sum alpha tuned on all train queries: 0.7
weighted sum resamples choosing alpha 0.5: 13
weighted sum resamples choosing alpha 0.6: 171
weighted sum resamples choosing alpha 0.7: 686
weighted sum resamples choosing alpha 0.8: 11
weighted sum resamples choosing alpha 0.9: 74
weighted sum resamples choosing alpha 1.0: 45
weighted rrf alpha tuned on all train queries: 0.6
weighted rrf resamples choosing alpha 0.5: 2
weighted rrf resamples choosing alpha 0.6: 513
weighted rrf resamples choosing alpha 0.7: 76
weighted rrf resamples choosing alpha 0.8: 365
weighted rrf resamples choosing alpha 0.9: 26
weighted rrf resamples choosing alpha 1.0: 18
重み付き和の重みは保たれている。train クエリ全体では α は0.7であり、α = 0.7 は686回の再標本で選ばれ、他のどの選択よりも多い。α = 0.6 は171回、意味検索のみの α = 1 は45回選ばれる。
重み付き RRF は、α = 0.6と調整されたが、安定性は低い。重みは 0.6 から 0.8 の間で動き、α = 0.6 は513回、α = 0.8 は365回、α = 0.7 は76回選ばれる。
どちらの重みも、グリッドのうち意味検索を重視する側にとどまっている。例外は均等な重み α = 0.5 で、重み付き和では13回、重み付き RRF では2回の再標本で選ばれる。
再標本化だけが確認の手段ではない。BM25 のスコアが等しい商品には何らかの順序を与える必要があり、lib.lexicalはそれらをproduct_idの昇順に並べるが、この順序は情報を持たない。product_idの降順も同様に情報を持たない。重み付き和では、同順位の商品に同じ BM25 の項が与えられるため、順序はほとんど影響しない。一方 RRF では、同順位の商品に連続した順位が与えられ、したがってスコアも異なる。BM25 の同順位をproduct_idの降順で並べ、最良の RRF kと2つの重みを train クエリで再び調整する。結果は次のとおりである。
1"""Tunes RRF's k and both blends' α again with BM25's equal scores listed in descending product_id order, to test2whether the order of ties matters. The prose's point rests on each setting's pair of lines, ties by product_id and3ties reversed."""4import numpy as np56from lib.blend import best_alpha, candidates, scores_by_alpha, weighted_rrf, weighted_sum7from lib.fusion import reciprocal_rank_fusion8from lib.lexical import LexicalSearch9from lib.metrics import evaluate10from lib.semantic import SemanticSearch11from lib.store import load_products, load_queries, qrels121314class TiesReversed(LexicalSearch):15 """BM25 with equal scores in descending product_id order, an order as arbitrary as ascending."""1617 def search(self, query, k=100):18 scores = super().search(query, k=len(self.ids)) # every match, so the cut at k can move too19 # highest score first, then descending product_id (np.lexsort sorts by its last key first)20 order = np.lexsort((-scores.index.to_numpy(), -scores.to_numpy()))21 return scores.iloc[order[:k]]222324products, queries, judgments = load_products(), load_queries("train"), qrels("train")25semantic = SemanticSearch()26semantic_run = semantic.run(queries, k=100)27# each order runs in turn, against the same semantic run28for ties, lexical in [("ties by product_id", LexicalSearch(products)), ("ties reversed", TiesReversed(products))]:29 bm25 = lexical.run(queries, k=100)30 by_k = {k: evaluate(reciprocal_rank_fusion([bm25, semantic_run], k=k), judgments)["ndcg@10"].mean()31 for k in [1, 10, 30, 60, 100, 300]}32 print(f"best rrf k, {ties}: {max(by_k, key=by_k.get)}") # ties go to the smaller k33 rrf = scores_by_alpha(lambda alpha: weighted_rrf(bm25, semantic_run, alpha), judgments)34 print(f"weighted rrf alpha, {ties}: {best_alpha(rrf)}")35 tables = candidates(lexical, semantic, queries)36 total = scores_by_alpha(lambda alpha: weighted_sum(tables, alpha), judgments)37 print(f"weighted sum alpha, {ties}: {best_alpha(total)}")
python tuning-with-ties-reversed.pybest rrf k, ties by product_id: 100
weighted rrf alpha, ties by product_id: 0.6
weighted sum alpha, ties by product_id: 0.7
best rrf k, ties reversed: 300
weighted rrf alpha, ties reversed: 0.8
weighted sum alpha, ties reversed: 0.7
同順位を逆にすると、RRF の設定は変わるが、重み付き和の設定は変わらない。
| 設定 | product_id 順の同順位 | 同順位を逆順 |
|---|---|---|
| 最良の RRF k | 100 | 300 |
| 重み付き RRF の α | 0.6 | 0.8 |
| 重み付き和の α | 0.7 | 0.7 |
情報を持たない順序が設定を変えるとき、train クエリでは設定どうしを区別できない。したがって RRF の k と重みは脆く、重み付き和の重みは脆くない。ストアにはこれ以上 train クエリがなく、重み付き RRF の重みを確定させる手段がない。またその test での比較は、同順位をproduct_idの順に並べて調整した重みで計画されていたため、α = 0.6を test に進める。
安定しているとは、train クエリの間で重みについて意見が一致しているということであり、他のクエリで検索が改善することを意味しない。再標本は同じクエリを再利用するため、それらのクエリに共通する性質をそのまま共有する。
実践ルール: train クエリをブートストラップして各標本で調整し、さらに、情報を持たない別の順序で同順位を並べて、もう一度調整する。選ばれた重みがグリッド上で散らばるなら、より粗いグリッドか、より多くの train クエリを使うか、より単純な設定を選ぶ。同順位の順序だけで重みが動くなら、報告する場所ごとにその旨を述べる。2つの確認のどちらでも重みが安定しているなら、test クエリに進める。
チューニング済みブレンドをテストクエリで報告する
チューニングした設定が、それを選んだクエリを超えて有効かどうかを示すのは、ホールドアウトしたクエリだけである。チューニング済みの各ブレンドをテストクエリで一度ずつ実行し、最良の単一検索器であるセマンティック検索とクエリごとに比較する。比較には第3章のハーネスを用いる。この2つの比較は、結果を見る前に第3章で固定してある。第3章に従い、Bonferroni 補正により、基準は並べ替え検定の p 値が 0.025 を下回ることとなる。これは 0.05 を計画した2つの比較で割った値である。t 検定と、対応する信頼水準 0.975 のブートストラップ区間を併せて示す。
ストアの訓練クエリでは、チューニング済みブレンドはセマンティック検索に対して 0.013 と 0.015 の向上を示したが、どちらも並べ替え検定で偶然と区別できる向上ではなかった。まず予測してみよう。テストクエリでは、α = 0.7 の重み付き和と α = 0.6 の重み付き RRF は、セマンティック検索を上回るか、同等か、下回るか。
1"""Chooses each blend's α on the train queries, runs both once on the test queries, and compares each with semantic2retrieval at the corrected threshold. The prose's point rests on the two mean differences and their permutation3p-values, and the assert checks that neither clears the threshold."""4from lib.blend import best_alpha, candidates, scores_by_alpha, weighted_rrf, weighted_sum5from lib.lexical import LexicalSearch6from lib.metrics import evaluate7from lib.semantic import SemanticSearch8from lib.significance import compare9from lib.store import load_products, load_queries, qrels1011lexical, semantic = LexicalSearch(load_products()), SemanticSearch()121314def blends(queries):15 tables, bm25, semantic_run = candidates(lexical, semantic, queries), lexical.run(queries), semantic.run(queries)16 return {"weighted sum": lambda alpha: weighted_sum(tables, alpha), # each blend's run at a given alpha17 "weighted rrf": lambda alpha: weighted_rrf(bm25, semantic_run, alpha)}181920train, test = blends(load_queries("train")), blends(load_queries("test"))21threshold = 0.05 / len(test) # two planned comparisons, Bonferroni-corrected22semantic_scores = evaluate(semantic.run(load_queries("test")), qrels("test"))23print("test queries:", len(semantic_scores))24print(f"semantic ndcg@10: {semantic_scores['ndcg@10'].mean():.3f}")25unweighted = evaluate(test["weighted rrf"](0.5), qrels("test")) # alpha 0.5 is chapter 1's fusion26print(f"unweighted rrf ndcg@10: {unweighted['ndcg@10'].mean():.3f}")27print(f"p-value threshold for each comparison: {threshold:.3f}")28print(f"confidence level of each interval: {1 - threshold:.3f}")29judged = [semantic_scores["judged@10"].mean()]30for name, blend in test.items():31 alpha = best_alpha(scores_by_alpha(train[name], qrels("train"))) # train only32 scores = evaluate(blend(alpha), qrels("test"))33 judged.append(scores["judged@10"].mean())34 # the interval's level matches the corrected threshold35 result = compare(scores["ndcg@10"], semantic_scores["ndcg@10"], confidence=1 - threshold)36 print(f"{name} alpha chosen on train: {alpha}")37 print(f"{name} ndcg@10: {scores['ndcg@10'].mean():.3f}")38 print(f"{name} minus semantic: {result['mean difference']:.3f}")39 print(f"{name} permutation p: {result['permutation p']:.3f}")40 print(f"{name} t-test p: {result['t-test p']:.3f}")41 print(f"{name} interval: {result['ci low']:.3f} to {result['ci high']:.3f}")42 # neither difference is established: each permutation p-value stays at or above the corrected threshold43 assert result['permutation p'] >= threshold44print(f"lowest judged@10: {min(judged):.3f}")45print(f"highest judged@10: {max(judged):.3f}")
python tuned-blends-on-test.pytest queries: 30
semantic ndcg@10: 0.830
unweighted rrf ndcg@10: 0.812
p-value threshold for each comparison: 0.025
confidence level of each interval: 0.975
weighted sum alpha chosen on train: 0.7
weighted sum ndcg@10: 0.816
weighted sum minus semantic: -0.014
weighted sum permutation p: 0.229
weighted sum t-test p: 0.221
weighted sum interval: -0.042 to 0.008
weighted rrf alpha chosen on train: 0.6
weighted rrf ndcg@10: 0.825
weighted rrf minus semantic: -0.005
weighted rrf permutation p: 0.650
weighted rrf t-test p: 0.643
weighted rrf interval: -0.029 to 0.016
lowest judged@10: 0.980
highest judged@10: 0.990
どちらのブレンドもセマンティック検索を上回らない。セマンティック検索のスコアは 0.830、min-max スコアの重み付き和は 0.816、重み付き RRF は 0.825 である。
各実行結果の judged@10 の値は 0.980 から 0.990 の間にあり、判定の欠落は3つの実行結果にほぼ等しく影響する。
どちらの差も確立されていない。並べ替え検定の p 値はいずれも、補正後の閾値である 0.025 以上にとどまる。重み付き和とセマンティック検索の差は -0.014 で、並べ替え検定の p 値は 0.229、t 検定の p 値は 0.221、区間は -0.042 to 0.008 である。重み付き RRF の差は -0.005 で、p 値は 0.650 と 0.643、区間は -0.029 to 0.016 である。どちらの区間も 0 を含み、検定もそれと一致するので、結論は「悪化」ではなく「改善なし」である。重み付き RRF については、これは α = 0.6 での結論であり、この重みはBM25 のタイの順序によって動きうる。
「上回る」と結論づければ、訓練での向上を信頼したことになる。その向上は、それを選んだクエリ上でさえ並べ替え検定が偶然と区別できず、しかも複数回の試行のうちの最良のものだった。
実践ルール: ブレンドを採用するのは、ホールドアウトしたクエリで最良の単一検索器を上回り、並べ替え検定の p 値が、計画した比較の数で補正した閾値を下回る場合に限る。そうでなければ、より単純なシステムを保つ。その場合、ストアで超えるべきランカーはセマンティック検索のみとなる。チューニングした重みとコードは保存しておき、検索器やカタログが変わったときにブレンドを再度テストする。
この部分はまだ翻訳されていないため、英語で表示している。
Learn sparse term weights with SPLADE
Instead of fusing two retrievers, you can change one so that it misses less. BM25 only matches words that appear in a product's text. Learned sparse retrieval keeps BM25's machinery, an inverted index of terms, but has a neural model choose each product's terms and their weights. SPLADE is one learned sparse retrieval model (Formal et al., 2021). A language model of the BERT family, a transformer that reads text as subword tokens, reads the product's text and, at each token i, gives every term j in its vocabulary a raw score w_ij. ReLU sets the negative scores to 0, and the original paper sums a logarithm of what's left over the text's tokens:
weight of term j = sum over the text's tokens i of log(1 + ReLU(w_ij))
The logarithm is a saturation, like BM25's: in the authors' words, it "prevents some terms to dominate and naturally ensures sparsity in representations". SPLADE v2 replaced the sum with the maximum over the tokens, and the authors made max pooling their default (Formal et al., 2021, SPLADE v2). A SPLADE vector has one dimension per vocabulary entry, 30,522 for a BERT vocabulary, and typically more than 99% of them are zero (Sentence Transformers). The nonzero terms of a SPLADE vector include expansion terms: words the text doesn't contain but the model weights anyway, so a product can match a query word it never uses.
Expansion terms target one of BM25's failures in the store. Count, on the train queries, how many exact products lack at least one of the query's words, as BM25's tokenizer sees them:
1"""Counts the exact train pairs whose product lacks a word of its query, as BM25's tokenizer sees them, and counts the2exact products of one query by term. The prose's point rests on the share missing a query word and on the per-term3counts for midcentury tv unit."""4from collections import Counter56import bm25s78from lib.store import load_products, load_queries, product_text, qrels910products, queries, judgments = load_products(), load_queries("train"), qrels("train")111213def words(texts):14 """The tokens BM25 matches on: bm25s's default tokenizer with English stopwords, as in lib.lexical."""15 tokenized = bm25s.tokenize(texts, stopwords="en", return_ids=False, show_progress=False)16 return [set(tokens) for tokens in tokenized]171819product_words = dict(zip(products.index, words(product_text(products).tolist())))20query_words = dict(zip(queries.index, words(queries["query"].tolist())))21exact_pairs = [(query_id, product_id) for query_id in queries.index22 for product_id, grade in judgments[query_id].items() if grade == 2]23missed = Counter(word for query_id, product_id in exact_pairs24 for word in query_words[query_id] - product_words[product_id])25# a pair counts as missing when some query word is absent from the product's set of tokens26missing = sum(not query_words[query_id] <= product_words[product_id] for query_id, product_id in exact_pairs)27print("exact train pairs:", len(exact_pairs))28print("exact pairs missing a query word:", missing)29print(f"share missing a query word: {missing / len(exact_pairs):.3f}")30print("most often missing:", ", ".join(f"{word} ({count})" for word, count in missed.most_common(8)))3132exact = [product_id for query_id, product_id in exact_pairs if query_id == 453] # midcentury tv unit33print("exact products for midcentury tv unit:", len(exact))34for word in ["midcentury", "unit", "stand"]:35 print(f"exact products containing {word}:", sum(word in product_words[product_id] for product_id in exact))36mid_century = product_text(products)[exact].str.contains("mid-century")37print("exact products whose text says mid-century:", mid_century.sum())
python exact-products-missing-query-words.pyexact train pairs: 1937
exact pairs missing a query word: 1454
share missing a query word: 0.751
most often missing: ligth (193), decorative (134), modern (102), freestanding (78), floats (58), queen (57), dining (56), infant (43)
exact products for midcentury tv unit: 25
exact products containing midcentury: 0
exact products containing unit: 0
exact products containing stand: 25
exact products whose text says mid-century: 20
Of 1937 exact (query, product) pairs, 1454 miss at least one query word, a share of 0.751. The words missed most often, with their counts, are ligth (193), decorative (134), modern (102), freestanding (78), floats (58), queen (57), dining (56), infant (43). Some are typos, which chapter 8's corrector targets, and plural forms, which chapter 5 stems; others are descriptive words the product text leaves out, or different words for one thing.
For midcentury tv unit, the exact products use other words. Of the 25 exact products, 0 contain midcentury and 0 contain unit. Their text says mid-century instead in 20 and stand in 25.
Expansion terms are aimed at gaps like these, though whether a model learns that a TV stand is a TV unit is something you'd measure.
The SPLADE authors' own technical report gives SPLADE-v3 an MRR@10 above 0.40 on the MS MARCO development set, a passage-ranking benchmark where MRR@10 measures how high the first relevant passage lands, and describes it as "comparing well to cross-encoder re-rankers" (Lassance et al., 2024). The book doesn't run SPLADE. The reference checkpoints, naver/splade-cocondenser-ensembledistil and naver/splade-v3, are licensed CC-BY-NC-SA-4.0, which rules out commercial use. An Apache-2.0 model, opensearch-neural-sparse-encoding-doc-v3-distill, runs its neural model on products only, and encodes queries with a tokenizer and a table of weights.
Working rule: Consider learned sparse retrieval when BM25's misses are mostly vocabulary misses and you want to keep an inverted index. Check the model's licence first, and measure it like any retriever: alone, per query, on train queries, then on test.
ColBERTでトークンごとに照合する
SPLADEが語彙的検索を変えるのに対し、遅延相互作用(late interaction)は意味的検索を変える。ストアの意味的検索は単一ベクトル方式であり、商品ごとに1つ、クエリごとに1つの埋め込みを作り、一度だけ比較する。遅延相互作用は、テキストごとに1つではなくトークンごとに1つのベクトルを保持する。そのためマルチベクトル検索とも呼ばれる。ColBERTは、埋め込みモデルと同様にクエリと商品を別々に符号化し、比較は最後にだけ行う。クエリの各トークンについて、最も類似した商品トークンを探し、それらの最大値を合計する。この演算はMaxSimと呼ばれる(Khattab and Zaharia, 2020)。
score(query, product) = sum over query tokens q of max over product tokens d of cosine(q, d)
商品はクエリとは無関係に符号化されるため、そのトークンベクトルはあらかじめ計算しておける。クロスエンコーダは両方のテキストを1つの入力として読むので、これができない。ColBERTの論文は、クエリと文章を一緒に読む既存のBERTベースのモデルに「匹敵する」有効性を、「2桁高速」な速度で達成したと報告している。代償は記憶容量である。商品ごとではなくトークンごとに1つのベクトルを持つ必要がある。ColBERTv2はこれらのベクトルを圧縮し、遅延相互作用モデルに必要な容量を6〜10分の1に減らしている(Santhanam et al., 2022)。
midcentury tv unitの例に戻ろう。この完全一致する商品はstandと言い、unitとは決して言わない。単一ベクトルでは、クエリ全体が1つの方向に、商品テキスト全体が別の1つの方向にまとめられてしまう。遅延相互作用では、クエリのunitが商品の各トークン(その中のstandも含む)と比較され、その最良の一致が単独で評価される。トークン単位の照合は、難しいケースの一部で効果がある。否定表現を扱うベンチマークNevIRでは、ランダムに選んだ場合のスコアが25%であるのに対し、ColBERTv1は19.7%、ColBERTv2は13.0%であり、試験した単一ベクトルモデルのすべて(12%以下)を上回ったが、それでも偶然の水準には届かなかった(Weller et al., 2024)。モデルが訓練されていないデータセットでゼロショットに評価するベンチマークBEIRでは、リランカーと遅延相互作用モデルが「平均して最良のゼロショット性能を達成」したが、計算コストは高かった(Thakur et al., 2021)。PyLateライブラリや、Apache-2.0ライセンスのモデルlightonai/GTE-ModernColBERT-v1など、公開されたツールも存在する(Chaffin and Sourty, 2025)。本書ではColBERTも実行しない。
実践ルール: 単一ベクトル検索が1つの語に左右される細部を取りこぼし、かつトークンごとにベクトルを持つ余裕がある場合に、遅延相互作用を検討する。ストアと同規模のカタログでは、まず絞り込んだ候補に対してリランカーを試すことを勧める(9章)。リランカーはクエリ時に同じ細部を読み取り、新しいインデックスを必要としない。ただし、9章のどのリランカーも、ストアの意味的検索に対して確立した改善を示してはいない。
ハイブリッド検索が有効になる条件を見極める
融合が効果をもたらすかどうかは、融合する検索器に依存し、公表された研究の結論も両方向に分かれている。字句検索と密検索(ここでの密とは埋め込みに基づくことを指す)は、密モデルのほうが弱い場合でも互いに補い合うことがある。ドメイン外では、ゼロショットのハイブリッドが、3つのデータセットの平均で、深層検索モデルに対し相対値で20.4%の向上を示した(T. Chen et al., 2022)。ここでは字句検索のベースラインが重要である。密検索器であるDPRの著者らは、ハイブリッドからほとんど利得を得られなかったが、より強力なBM25を用いた再現実験では「統計的に有意な利得」が見られた(Ma et al., 2021)。意味検索器の強さも重要である。推論を多く要するクエリのベンチマークであるBRIGHTでは、min-maxスコアの重み付き和でα = 0.5としてBM25を融合したところ、中位の密検索器ではnDCG@10が3.5〜4.9ポイント向上し、最も強い2つの検索器では2.0〜2.9ポイント低下した。著者らは、すでに強力な検索器では融合が逆効果になりうると警告している。その理由は「融合されたリストが、字句的には似ているが意味的には無関係な文書を上位に押し上げる」ためである(Abdallah et al., 2026)。
本番環境の報告は、通常、ハイブリッドを字句検索単独と比較している。ある小売業者のプレプリントは、オンラインA/Bテストで、字句検索とベクトル検索のハイブリッドが字句検索単独を上回り、クリック率が0.97%、コンバージョン率が0.98%向上したと報告している(Sonagara et al., 2026)。これは字句検索のシステムに意味検索を加える根拠にはなるが、強力な意味検索に字句検索を加える根拠にはならない。後者こそがこのストアの問いである。
このストアは強力な検索器の場合に当たる。テストクエリについて、第3章は意味検索がBM25に対して優位であることを示しており、調整したどちらのブレンドもそれを上回らない。ストアのBM25は、本書のステミングなしのベースラインである。第5章ではより強力なベースラインを構築する。Maらの再現実験は、それを用いてブレンドを再度検証する理由になる。
スコアの融合だけがハイブリッドの形ではない。検索エンジンは、字句の一致を意味検索に対するフィルタとして用いることもできる。あるエンジンはクエリ言語に埋め込み演算子を追加し、「埋め込みと語の任意の組み合わせによるハイブリッド検索式」を1つのクエリとして実行する(Huang et al., 2020)。ストアのフィルタでは、48のようなサイズの完全一致を必須とし、一致した商品を埋め込みで順位付けする方法が考えられる。これは検証すべき仮説であり結果ではない。単純なフィルタは7qt slow cookerでは失敗する。その表記はどの商品にも使われていないからである。クエリがいつこのような制約を含むかの判定はクエリ理解であり(第8章)、第8章では、色、形、サイズ、仕上げを挙げる買い物客のフォローアップメッセージに対して、そのようなフィルタを試す。クエリごとに重みを選ぶこともクエリ理解にあたり、本書では構築しない。訓練クエリごとに良いほうのランキングを選べば0.802というスコアになるが、リストを混ぜるクエリ別の重みは、この数値に縛られない。クエリ別の手法の1つに、LLM(大規模言語モデル)に各検索器の最上位の結果を判定させ、その判定からαを設定するものがある(Hsu and Tzeng, 2025)。BRIGHTの研究では、そのスコアベースの変種は不安定であった(Abdallah et al., 2026)。
実践ルール: 2つの検索器の品質が近い場合、埋め込みモデルが学習されたドメインの外で使われる場合、または多くのクエリが埋め込みの捉えられない正確な語に依存する場合には、ハイブリッドを試すことを勧める。まず重み付きRRFから始めるとよい。順位だけを必要とし、ストアの訓練クエリでは、順列検定によって重み付き和と区別できなかった。両方のエンジンがすべての候補にスコアを与える場合は、正規化スコアの重み付き和に移行する。2つの研究がそれぞれのデータでRRFを上回ることを見いだしており(Bruch et al., 2023; Abdallah et al., 2026)、ストアの訓練クエリでもその重みはより安定していた。一方の検索器がホールドアウトのクエリで強いと確認され、調整したどのブレンドもそこで上回らない場合は、その検索器を単独で使い、もう一方をベースラインとして残し、正確な制約に対しては字句フィルタを試す。これがストアのケースである。
本番環境で何が問題になるか
2つの検索器には、あらゆるものが2倍かかる。 本書の例はカタログのサンプルをオフラインで採点するが、実際のハイブリッド検索では2つのインデックスを最新に保ち、クエリごとに2回の検索を実行する。両者は並列に実行できるが、応答時間を決めるのは遅いほうであり、どちらか一方が失敗しても結果は劣化する。このコストを、測定した改善幅と比較して考える必要がある。
短いリストは候補を落とす。 融合では、どちらの検索器も返さなかった商品を順位付けすることはできない。ストアの train クエリでは、上位100件のリスト2つの和集合には各クエリの正解商品の 0.810 が含まれ、上位20件のリスト2つの和集合には 0.445 が含まれる。一方のエンジンの設定にある深さの上限が、誰にも気づかれないまま候補を切り落とすことがある。
欠損したスコアには扱いの規則が必要である。 各検索器が上位 k 件だけを返す場合、一方のリストに現れない商品には、その検索器によるスコアがない。DPR の再現実験では、そうした商品に「取得された文書のうち最小の密検索スコア」を割り当て、BM25 についてはその逆を行っている(Ma et al., 2021)。Bruch らは、lib.blend.candidates が行うように、代わりに欠損したスコアを正確に計算している。ただし、本番のエンジンではこの方法を取れないことがある(Bruch et al., 2023)。
min-max は相対的である。 あるクエリの最良の候補は、すべての候補が不適切であっても、常に1を得る。カタログのどの商品とも単語を共有しないクエリでは、すべての候補の BM25 スコアが0になる。単純な min-max ではこのときゼロ除算が起こり、lib.blend はゼロを返すため、ブレンドは何の通知もなく意味検索だけになる。ストアのクエリにこのようなものはないが、実際の検索ボックスでは起こる。
融合スコアは確信度ではない。 検索スコアは較正が不十分である。「確信度の較正は、モデルファミリー全体で一貫して弱い」(Abdallah et al., 2026)。融合スコアに閾値を設けて、あるクエリに良い結果がないと判定してはならない。
調整済みの重みは、1組の検索器にのみ属する。 ストアの α は、この BM25 の設定、この埋め込みモデル、このカタログに合わせたものである。これらのいずれかを変えたら、以前の重みを信頼する前に train クエリで再調整する。調整した RRF は「ドメイン外のデータセットへの汎化が悪い」(Bruch et al., 2023)。
実践ルール: 融合結果と並べて両方の検索器の順位をログに記録し、すべてのエンジンの設定でリストの深さを確認し、検索器が変わるたびに α を再調整する。
この章で下した決定
後の変更は、それぞれの決定を上回る理由を示さなければならない。
- 調整は train で行い、報告は test で行う。 すべての分析と調整済みの設定は、50 件の train クエリを用いる。この章では test クエリを、報告のために一度だけ読む。
- 計画した比較は 2 つである。 調整済みの各ブレンドを意味検索と比較し、0.05 を 2 で割った水準の順列検定で判定する。t 検定とブートストラップ区間を併記する。
- 融合の前に各検索器を検証する。 judged@10 と対応のある検定を用い、クエリごとにどちらが勝つかを数える。
- 候補は、両検索器の上位 100 件の和集合とする。 すべての候補について両方のスコアを引き当てるため、スコアの欠ける商品は生じない。
- 正規化はクエリごとの min-max とする。 train 上の順列検定は、他の 2 つの正規化を min-max から 0.05 の水準で区別できず、min-max はどちらのスコア関数についての知識も必要としない。
- RRF は k = 60、リストの深さは 100 とする。 train で最良の k も、60 に対して、順列検定が 0.05 の水準で偶然と区別できる利得を何ももたらさず、BM25 の同点の順序によって変わる。リストを深くすると、増えるのは候補だけである。
- 重み α は 1 つとし、0 から 1 まで 0.1 刻みで調整する。 2 つのブレンドに共通で、train の平均 nDCG@10 によって選び、ブートストラップを行ったうえで、BM25 の同点を逆順にして再度調整する。重み付き和の α はどちらの検証にも耐えるが、重み付き RRF の α は耐えない。
- SPLADE と ColBERT は、説明にとどめ、記録は行わない。 ストアの問いに答えるには、どちらも必要ないためである。
- ブレンドを採用するのは、test で最良の単独検索器を上回る場合に限る。 調整済みのブレンドはどちらも上回らなかった。したがって、ストアで打ち負かすべきランカーは意味検索単独のままであり、語幹処理をしない BM25 をベースラインとして保持する。
- この章が示したこと: ブレンドが役立つのは、各検索器が異なるクエリで失敗する場合に限られる。また、train で勝つ重みは test でも成り立たなければならない。ストアでは、調整済みのどちらのブレンドも意味検索を上回らなかった。
この版における本章
第2026.11.10版2026年11月19日時点で例が通過この章の12 例件のうち12件が合格
英語版の書籍(版2026.11.10)から翻訳した。