検索をエンドツーエンドで
読了まで約63 分分、10 節 節の 11 例 例。
この章を終えるまでに、商品カタログを対象とした、粗削りだが完結した検索パイプラインを構築できるようになる。パイプラインは、買い物客のクエリから順序付けられた商品のリストを得るまでを扱う。さらに、パイプラインへの変更が効果をもたらすかどうかを、一つの数値で測定できるようになる。以降の各章では、このパイプラインの一部分を取り上げ、それを堅牢なものにしていく。
家具・生活雑貨のオンラインストアでは、買い物客が検索ボックスに clear shower curtain や 48 inch kitchen hood といったクエリを入力する。本書では、全体を通してこのストアを題材とし、単に「ストア」と呼ぶ。ストアには二つの答えが必要である。検索の質はどれほどか、そして変更によって検索が良くなるかどうかである。どのような検索システムでも同じ二つの問いに直面するため、本書ではあらゆる手法をストアで試す。そうすれば、各手法が実際のクエリに何をもたらすかを確認できる。
ストアには、これらに答えるための材料がそろっている。カタログ、実際のクエリの集合、そしてどの商品がどのクエリに合致するかについての人々の判定である。そこでこの章では、カタログを三通りの方法で検索する。単語の一致による検索、意味の一致による検索、そして両者を組み合わせた検索である。さらに、上位の結果を処理の遅いモデルで並べ替え、各バージョンをこれらの判定に照らして採点する。すべての段階でスコアが改善するわけではない。これがこの章の主な教訓であり、あらゆる変更を測定せよということである。
この部分はまだ翻訳されていないため、英語で表示している。
Load the store's data
Before you can improve a search system, you need three things: the items it searches, the queries people type, and judgments that say which items match which query. Search engines call the items documents. In this book they are products. A judgment is a person's label for one pair of a query and a product, and a grade is the number that stands for a judgment's label. Without judgments, you can look at results and form opinions, but you can't tell a fix from a regression.
The store's data, which the book's examples search and score, is real. It is a sample of WANDS, a public product-search dataset that Wayfair published with a paper at ECIR 2022 (Chen et al., 2022), under the MIT licence (licence). The full dataset has 42,994 products, 480 queries and 233,448 judgments (repository). The queries are a stratified sample of real shopper queries from a quarter's search log in 2021, and each label is the majority vote of up to three trained annotators (Chen et al., sections 4.1 and 5). The script prep/wands_sample.py draws the book's sample, and the sample's data card, examples/data/wands/README.md, says how. Setup code that many examples need lives in the book's shared modules, short files in examples/lib/ that you can open and read. lib.store, one of those modules, loads the sample, and the next example prints what comes back:
1"""Loads the store's sample and prints its size, how its queries split, and how its judgments are labelled. The prose quotes the split from the `train queries` and `test queries` lines."""2import pandas as pd34from lib.store import DATA, load_labels, load_products, load_queries56products = load_products()7queries = load_queries()8labels = load_labels() # one row per judged (query, product) pair9conflicts = pd.read_csv(DATA / "label_conflicts.csv") # pairs WANDS labelled two ways1011print(f"products: {len(products):,}")12print("queries:", len(queries))13print("train queries:", (queries["split"] == "train").sum())14print("test queries:", (queries["split"] == "test").sum())15print(f"judged pairs: {len(labels):,}")16print("pairs with conflicting labels:", len(conflicts))17for label in ["exact", "partial", "irrelevant"]:18 print(f"{label} pairs: {(labels['label'] == label).sum():,}")19print(f"products judged for at least one query: {labels['product_id'].nunique():,}")2021print()22print(queries.head(4).to_string())
python load-the-store.pyproducts: 12,000
queries: 80
train queries: 50
test queries: 30
judged pairs: 13,077
pairs with conflicting labels: 7
exact pairs: 3,252
partial pairs: 7,972
irrelevant pairs: 1,853
products judged for at least one query: 11,917
query query_class split
query_id
6 acrylic clear chair Dining Chairs train
10 king poster bed Beds train
20 foutains with brick look Wallpaper train
36 laundry basket with wheels Hampers & Baskets train
The sample has 12,000 products and 80 queries. It splits the queries once, before any ranker runs: 50 train queries for tuning and 30 test queries for reporting. Every score in this book is reported on the test queries, and nothing is tuned on them. A score on queries you tuned on measures how well you fit those queries, not how well search works.
WANDS judged some pairs more than once. The sample keeps one row per pair, 13,077 in all. When a pair's labels differ, it keeps the lower grade and lists the pair in label_conflicts.csv, which holds 7 pairs. Code that scores a ranking reads the judgments through lib.store.qrels, which returns them as {query_id: {product_id: grade}}. Chapter 2 reads the judgments closely.
Each judgment is one of three labels, defined by the dataset's authors (Chen et al., section 3.2). Exact means the product fully matches the search query. Partial means it "only matches the target entity of the query, but does not satisfy the modifiers for the query." Irrelevant means the product is not relevant to the query. The book's grades are 2, 1 and 0. Of the judged pairs, 3,252 are exact, 7,972 partial and 1,853 irrelevant. In this book, a relevant product is one judged exact for the query, unless a sentence says otherwise.
Three warnings come with the store's data. First, each query's query_class is WANDS's predicted class for it, not a judgment (Chen et al., Table 1): foutains with brick look is classed as Wallpaper. Treat it as a hint. Second, nobody judged every product for every query. That would have taken about 60 million judgments, so WANDS judged candidates gathered from products shoppers clicked or added to their carts and from several search systems, and stopped when few new exact matches turned up (Chen et al., sections 4.2 and 4.3). A product without a judgment for a query is unjudged: unknown, not irrelevant. Third, nearly every product in the sample, 11,917 of 12,000, is judged for at least one of its queries, so the sample holds fewer distractors than a full catalog would: products that compete for a query's top places without matching it.
Working rule: Split your queries into train and test before you change anything. Read test results to understand a ranker, but choose and tune every change on train queries, and report on test. Treat unjudged products as unknown. If you have no judgments yet, collect some before you change the ranking.
BM25で商品を順位付けする
ストアのカタログを検索するには、二つの仕事が必要である。**検索(リトリーバル)**は、カタログ全体から、クエリに合致しうる商品を見つけ出す。ランキングは、検索された商品を、最も適したものから順に並べる。語彙ベースの手法は、クエリの語と各商品のテキストの語とを比較し、その重なりをスコア化することで、この二つを同時に行う。
BM25は、三つの要素からなる語彙ベースのスコア関数である。第一に、商品がクエリの語を含んでいるほどスコアは高くなり、その語が珍しいほど、その度合いは大きくなる。少数の商品にしか現れない語は、それらの商品についてより多くのことを語るからである。第二に、同じ語が繰り返されても加点は次第に小さくなり、やがて上限に達する。BM25の文献ではこれを飽和と呼ぶ。第三に、長いテキストは短いテキストに比べて割り引かれる。長いというだけで、含まれる語が多い分だけ有利になることを防ぐためである。どの程度割り引くかはパラメータbが決め、0(割引なし)から1(完全な割引)までの値をとる(Robertson and Zaragoza, 2009)。第5章では、この式を手作業で組み立てる。
本書のBM25は、PythonのBM25ライブラリであるbm25s 0.3.16で動かす。既定では、Luceneという検索ライブラリが用いるBM25の変種でスコアを計算し、設定値はk1=1.5(飽和の設定)とb=0.75である(bm25sのソースコード)。スコアは教科書の式とは少し異なるが、三つのニュース記事コレクションを用いた再現性の研究では、BM25の各変種のあいだに有効性の有意な差は見られなかった(Kamphuis et al., 2020)。スコア計算の前に、bm25sはテキストをトークンに分割する。トークンは小文字化され、2文字以上の語が残され、andのような英語のストップワードは除去され、語を共通の語幹にまとめる処理は行われない(bm25sのトークナイザ)。本書が使うランカーであるlib.lexical.LexicalSearchは、各商品の名前、クラス、カテゴリ、説明を一つのテキストに連結して索引化する。
ストアのテストクエリclear shower curtainは、BM25の働きをよく示している。これを入力する買い物客が求めているのは透明なカーテンであるが、カタログには透明ではないカーテンが多数あり、同じ語を含むアクセサリもある。BM25の上位10件は次のとおりである。
1"""Searches the store's catalog with BM25 for one test query and prints the top 10 products. The prose's point that BM25 matches words rather than things rests on the names at the bottom of the list."""2from lib.lexical import LexicalSearch3from lib.store import load_products, load_queries45products = load_products()6query = load_queries().at[246, "query"] # a test query7lexical = LexicalSearch(products) # BM25 over name, class, category and description89scores = lexical.search(query, k=10) # the 10 highest scores, best first10print("query:", query)11print()12# names cut to 55 characters so that each row fits on one line13for rank, (product_id, score) in enumerate(scores.items(), start=1):14 print(f"{rank:>2} {product_id:>5} {score:5.2f} {products.at[product_id, 'name'][:55]}")
python first-bm25-search.pyquery: clear shower curtain
1 9752 7.11 rodas vinyl shower curtain
2 20428 6.97 woolley vinyl single shower curtain
3 20429 6.75 woolley vinyl solid color single shower curtain
4 20425 6.65 siniard single shower curtain
5 20430 6.48 simmon vinyl single shower curtain liner
6 3564 6.10 71 '' x71 '' 4pcs shower curtain sets beach theme showe
7 20132 5.95 newburg check 3d vinyl single shower curtain + hooks
8 33346 5.76 gilded pineapple shower curtain hooks
9 3197 5.72 double shower curtain hooks
10 1050 5.68 stainless steel shower curtain hooks
10件の大半はシャワーカーテンかライナーであるが、最後の数件はシャワーカーテンフックである。BM25は、フックの名前に「shower curtain」という語を見つけ、カーテンとほぼ同じ高さのスコアを与えた。BM25が照合するのは物ではなく語であり、フックがカーテンではないということを知らないからである。ここに表示された内容からは、カーテンが透明かどうかも分からない。それを知るには、ストアの判定が必要になる。
実践ルール: まずは、ライブラリの既定値のBM25をベースラインとして使う。BM25は学習データもモデルも必要とせず、誤った結果が出たときには、どの語が原因だったかを確認できる。学習用クエリで変更の効果を測定できるようになるまでは、パラメータには手を加えない。買い物客と商品が同じものを指すのに異なる語を使う場合には、意味ベースの検索を加える。
検索結果を判定と照合する
順位付けは、買い物客が何を求めていたかが分かって初めて意味を持つ。判定は、その情報を一組ずつ与える。この目的では、判定はクリックよりも優れた証拠となる。WANDS の著者らは、「ユーザー行動ログデータは位置バイアスの影響を受け、本番システムに近い順位付けを有利にする」と述べている(Chen et al., section 3.1)。買い物客は最初に表示されたものをクリックするため、クリックは、すでに手元にある順位付けをおおむね追認するにすぎない。
次に、clear shower curtain に対する BM25 の上位 10 件の商品を、それぞれの判定と並べてみる。この検索語に対して誰も判定していない商品は unjudged と表示される。
1"""Puts BM25's top 10 for `clear shower curtain` beside each product's judgment, and counts the labels. The prose's reading of the top 10 rests on the labelled rows and the `in the top 10` lines after them."""2from lib.lexical import LexicalSearch3from lib.store import load_products, load_queries, qrels45LABELS = {2: "exact", 1: "partial", 0: "irrelevant"}67products = load_products()8query_id = 2469query = load_queries().at[query_id, "query"]10judgments = qrels()[query_id] # {product_id: grade} for this query1112top = LexicalSearch(products).search(query, k=10).index13# a product with no judgment for this query is unjudged, not irrelevant14results = [LABELS.get(judgments.get(product_id), "unjudged") for product_id in top]15print("query:", query)16print()17for rank, (product_id, label) in enumerate(zip(top, results), start=1):18 print(f"{rank:>2} {label:<10} {products.at[product_id, 'name'][:55]}")1920print()21for label in ["exact", "partial", "irrelevant", "unjudged"]:22 print(f"{label} in the top 10: {results.count(label)}")23print("products judged for this query:", len(judgments))24print("exact products judged for this query:", sum(grade == 2 for grade in judgments.values()))
python judge-first-results.pyquery: clear shower curtain
1 partial rodas vinyl shower curtain
2 exact woolley vinyl single shower curtain
3 exact woolley vinyl solid color single shower curtain
4 exact siniard single shower curtain
5 exact simmon vinyl single shower curtain liner
6 partial 71 '' x71 '' 4pcs shower curtain sets beach theme showe
7 partial newburg check 3d vinyl single shower curtain + hooks
8 irrelevant gilded pineapple shower curtain hooks
9 irrelevant double shower curtain hooks
10 irrelevant stainless steel shower curtain hooks
exact in the top 10: 4
partial in the top 10: 3
irrelevant in the top 10: 3
unjudged in the top 10: 0
products judged for this query: 253
exact products judged for this query: 12
BM25 の上位 10 件には、exact の商品が 4 件、partial の商品が 3 件、irrelevant の商品(ひっかけ)が 3 件、未判定の商品が 0 件含まれている。1 位は partial である。データセットの定義によれば、この商品は買い物客が求めた対象であるシャワーカーテンには合致しているが、修飾語である clear(透明)には合致していない。
判定からは、理想的な上位 10 件に何が並ぶかも分かる。判定者はこの検索語に対して 253 件の商品にラベルを付けており、そのうち 12 件が exact である。したがって、理想的な順位付けでは 10 の枠すべてを exact の商品で埋められるのに対し、BM25 が埋められたのは 4 件である。この差こそ、指標が測定すべきものである。
このように結果を読むと、ランカーがどのような種類の誤りを犯すかが見えてくる。ここでは、BM25 が付属品の語に一致し、修飾語を取りこぼした。多数の検索語にわたる平均はこの種の誤りを覆い隠してしまうが、目に見えた誤りこそが修正できる誤りである。
実践ルール: 指標を計算する前に、5 件から 10 件の検索語について、上位の結果を判定と並べて読む。付属品、取りこぼされた修飾語、誤ったサイズといったパターンを探す。上位の結果に未判定のものが複数ある場合は、その検索語のスコアを信頼する前に、それらを判定してもらう。
この部分はまだ翻訳されていないため、英語で表示している。
Score one ranking with nDCG@10
To compare rankings, you need one number per ranking. It should reward matching products, and exact ones more than partial ones, and count a product near the top more than one near the bottom, because shoppers read from the top. Normalized discounted cumulative gain at 10, nDCG@10, does all three.
In words: each of the top 10 results earns a gain equal to its grade: 2 for exact, 1 for partial, 0 for irrelevant. The gain is divided by a discount that grows with position: log2 of the position plus one, so the first result counts in full and the third counts half. Adding up the discounted gains gives the discounted cumulative gain, DCG. Dividing by the DCG of the best possible top 10 for that query, the ideal DCG, puts the score between 0 and 1, where 1 means no better top 10 exists. An unjudged product earns 0.
DCG@10 = sum over positions i from 1 to 10 of grade(i) / log2(i + 1)
nDCG@10 = DCG@10 / ideal DCG@10
The WANDS paper scores search with nDCG@10 too, with gains of 1.0, 0.5 and 0 for exact, partial and irrelevant (Chen et al., section 6). The book's grades are twice those gains, which doubles both DCG and ideal DCG, so nDCG doesn't change.
Take BM25's ranking of clear shower curtain: a partial product first, then exact and partial curtains, then three irrelevant hooks. Compute DCG, the ideal DCG and their ratio by hand, then compare with lib.metrics, the shared module of the book's metrics:
1"""Computes nDCG@10 for one test query step by step, then checks it against `lib.metrics`. The prose's point rests on the `ndcg@10` line and on the library line that prints the same value."""2import math34from lib.lexical import LexicalSearch5from lib.metrics import ndcg_at_k6from lib.store import load_products, load_queries, qrels78products = load_products()9query = load_queries().at[246, "query"] # "clear shower curtain"10judgments = qrels("test")[246] # {product_id: grade}11ranking = list(LexicalSearch(products).search(query, k=10).index)1213grades = [judgments.get(product_id, 0) for product_id in ranking] # unjudged counts as 014# positions count from 1, so the first result is discounted by log2(2) = 115dcg = sum(grade / math.log2(position + 1) for position, grade in enumerate(grades, start=1))16best = sorted(judgments.values(), reverse=True)[:10] # the best possible top 1017ideal = sum(grade / math.log2(position + 1) for position, grade in enumerate(best, start=1))1819print("grades:", grades)20print("best grades:", best)21print(f"dcg@10: {dcg:.3f}")22print(f"ideal dcg@10: {ideal:.3f}")23print(f"ndcg@10: {dcg / ideal:.3f}")24print(f"ndcg@10 from lib.metrics: {ndcg_at_k(ranking, judgments, 10):.3f}")
python ndcg-for-one-query.pygrades: [1, 2, 2, 2, 2, 1, 1, 0, 0, 0]
best grades: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
dcg@10: 5.586
ideal dcg@10: 9.087
ndcg@10: 0.615
ndcg@10 from lib.metrics: 0.615
The ranking earns a DCG of 5.586. The best possible top 10 holds only exact products and earns 9.087. Their ratio, 0.615, matches what ndcg_at_k in lib.metrics returns: 0.615. The partial product at position 1 costs the most of any single result, because it holds the place with no discount. Each hook costs less, because it sits lower, but together the hooks cost more.
That one number sums up what the judgments showed: a ranking that found the right kind of product and made two kinds of mistake. You can compute it for any ranking of any judged query, and compare.
Working rule: Use nDCG@10 as your headline metric when your judgments are graded and the first page of results matters most, as it does in a store's search. When you have only yes-or-no labels, or when shoppers look at one result only, another metric fits better. Chapter 3 builds the alternatives and says when to choose each.
すべてのテストクエリを採点する
1つのクエリだけでは逸話にすぎない。ランカーを評価するには、固定したクエリ集合(本書ではテストクエリ)で採点し、その平均をとる。集合内の全クエリに対するランキングをまとめたものをランと呼び、{query_id: [product_id, ...]}の形で、上位から順に書く。lib.metrics.evaluateは、ランを判定と照らし合わせて採点し、クエリごとに1行を返す。
evaluateは、nDCG@10と並べてjudged@10も報告する。これは、上位10件のうち、そのクエリに対する判定が何らかの形で付いているものの割合である。判定のない商品は等級0として扱われるため、judged@10が低いと、スコアは部分的に推測に頼ったものになる。無関係な商品と、関連はあるが誰も判定していない商品とを、区別できないのである。
それでは、すべてのテストクエリに対してBM25を実行し、各クエリの上位100商品を保持して、そのランを採点する。
1"""Scores BM25 on every test query, keeping each query's top 100, and prints the averages and the spread. The prose's point rests on the mean and judged@10 lines and on the three lowest queries printed after them."""2from lib.lexical import LexicalSearch3from lib.metrics import evaluate4from lib.store import load_products, load_queries, qrels56LABELS = {2: "exact", 1: "partial", 0: "irrelevant"}78products, queries, judgments = load_products(), load_queries("test"), qrels("test")9run = LexicalSearch(products).run(queries, k=100) # {query_id: [product_id, ...]}10scores = evaluate(run, judgments) # one row per test query11scores["query"] = queries["query"]1213print("test queries:", len(scores))14print(f"mean ndcg@10: {scores['ndcg@10'].mean():.3f}")15print(f"mean judged@10: {scores['judged@10'].mean():.3f}")16print(f"lowest ndcg@10: {scores['ndcg@10'].min():.3f}")17print(f"median ndcg@10: {scores['ndcg@10'].median():.3f}")18print(f"highest ndcg@10: {scores['ndcg@10'].max():.3f}")19print("queries with ndcg@10 of 1:", (scores["ndcg@10"].round(3) == 1).sum())20print()21lowest = scores.nsmallest(3, "ndcg@10")22print(lowest[["query", "ndcg@10", "judged@10"]].round(3).to_string())23print("lowest query:", lowest["query"].iloc[0])24print(f"judged@10 of the lowest query: {lowest['judged@10'].iloc[0]:.3f}")25print()26# query 133, outdoor light fixtures, is the second-lowest scorer in the table above27print(f"judged@10 for {queries.at[133, 'query']}: {scores.at[133, 'judged@10']:.3f}")28print("bm25 top 5 for", queries.at[133, "query"])29for product_id in run[133][:5]:30 label = LABELS.get(judgments[133].get(product_id), "unjudged")31 print(f" {label:<10} {products.at[product_id, 'name'][:60]}")
python bm25-test-scores.pytest queries: 30
mean ndcg@10: 0.725
mean judged@10: 0.927
lowest ndcg@10: 0.212
median ndcg@10: 0.687
highest ndcg@10: 1.000
queries with ndcg@10 of 1: 4
query ndcg@10 judged@10
query_id
46 beach blue headboard 0.212 0.5
133 outdoor light fixtures 0.286 0.2
292 decorative white pillow 0.467 1.0
lowest query: beach blue headboard
judged@10 of the lowest query: 0.500
judged@10 for outdoor light fixtures: 0.200
bm25 top 5 for outdoor light fixtures
exact malikah 1 -bulb outdoor bulkhead light
unjudged 60 watt equivalent e12 led candle light bulb
unjudged 5w ( 40 watt equivalent ) , b11 led , dimmable light bulb e1
unjudged 60 watt equivalent , a19 led , non-dimmable light bulb , war
unjudged 40 watt equivalent e12 dimmable led edison candle light bulb
30件のテストクエリにわたり、BM25のnDCG@10の平均は0.725、judged@10の平均は0.927である。この平均がストアで最初に得られた測定結果であり、以後のすべてのランカーはこれと比較される。
ただし、平均は大きなばらつきを覆い隠している。スコアは0.212から1.000まで広がり、中央値は0.687であり、4件のクエリが満点の1を取っている。
最もスコアの低いクエリbeach blue headboardのjudged@10は0.500である。スコアの低いもう1つのクエリoutdoor light fixturesのjudged@10は0.200である。BM25の上位5件には、完全に一致する屋外用の照明が1件あり、その後に、クエリと語を共有するものの、このクエリに対して誰も判定していない電球が続く。電球は照明器具ではないため、この場合は等級0がおそらく妥当である。しかし指標にはそれが分からない。別のランカーや別のクエリでは、判定のない商品が良い商品である可能性もある。
実践ルール: テストクエリに対するnDCG@10の平均は、judged@10の平均を併記して報告し、ランを採点するたびに、スコアの低いクエリを必ず読む。あるランカーのjudged@10が別のランカーより低いときは、nDCGを比較する前に理由を調べること。その差は、結果が悪いからではなく、判定が欠けているために生じている可能性がある。
この部分はまだ翻訳されていないため、英語で表示している。
Search by meaning with embeddings
Lexical retrieval fails when the shopper's words and the product's words differ, or when shared words mean different things, as with the hooks that BM25 ranks for clear shower curtain. Semantic retrieval compares the meanings of the query and the product instead of their words. It rests on embeddings. An embedding is a list of numbers, a vector, that a neural network computes for a piece of text. The network is trained so that texts with similar meanings get vectors pointing in similar directions. You embed every product once, ahead of time. At search time, you embed the query and return the products whose vectors are closest to it. With every vector scaled to length 1, closeness is the dot product of two vectors, which equals the cosine of the angle between them.
Embedding the products ahead of time is what makes this fast. In the paper that introduced Sentence-BERT, finding the most similar pair among 10,000 sentences took about 65 hours on a V100 GPU when BERT read every pair. Embedding each sentence once and comparing the embeddings took about 5 seconds, almost all of it spent computing the embeddings: the comparison itself took about 0.01 seconds (Reimers and Gurevych, 2019).
The store's embeddings come from the open model Snowflake/snowflake-arctic-embed-m-v1.5. Examples never call a model, so that every example runs offline and gives the same output each time. Instead, a recording, here the script recordings/embeddings.py, runs the model once and saves its vectors, and the examples read them offline through lib.recorded. We chose this model because it is open and under the Apache 2.0 licence, so anyone can download the pinned version and rerun the recording. The recording adds to each query the instruction that the model's card asks for ("Represent this sentence for searching relevant passages:") and embeds products as they are (model card). The book's semantic retrieval, built as lib.semantic.SemanticSearch, multiplies every product vector by the query vector and sorts the results. Chapter 6 builds it step by step.
Every product is a vector of 768 numbers, and semantic retrieval compares the query's vector with each one; here are the ten closest, with their judgments:
1"""Ranks the store's products for `clear shower curtain` by the similarity of their recorded embeddings to the query's, and prints the top 10 with each judgment. The prose's point rests on the top 10 counts and the similarity spread line."""2from lib.metrics import ndcg_at_k3from lib.recorded import manifest4from lib.semantic import SemanticSearch5from lib.store import load_products, load_queries, qrels67LABELS = {2: "exact", 1: "partial", 0: "irrelevant"}89products = load_products()10query_id = 24611judgments = qrels()[query_id]12semantic = SemanticSearch() # recorded embeddings of every product and query1314print("embedding model:", manifest("embeddings")["model"])15print("dimensions:", semantic.products.shape[1])16print("query:", load_queries().at[query_id, "query"])17print()18# the query's vector against every product's: unit-length vectors, so each dot product is a cosine19similarity = semantic.search(query_id, k=10)20for rank, (product_id, score) in enumerate(similarity.items(), start=1):21 label = LABELS.get(judgments.get(product_id), "unjudged")22 print(f"{rank:>2} {score:.3f} {label:<10} {products.at[product_id, 'name'][:50]}")2324print()25labels = [LABELS.get(judgments.get(product_id), "unjudged") for product_id in similarity.index]26for label in ["exact", "partial", "irrelevant", "unjudged"]:27 print(f"{label} in the top 10: {labels.count(label)}")28print(f"similarity spread in the top 10: {similarity.max() - similarity.min():.3f}")29print(f"ndcg@10: {ndcg_at_k(list(similarity.index), judgments, 10):.3f}")
python first-semantic-search.pyembedding model: Snowflake/snowflake-arctic-embed-m-v1.5
dimensions: 768
query: clear shower curtain
1 0.577 exact woolley vinyl solid color single shower curtain
2 0.572 exact woolley vinyl single shower curtain
3 0.569 partial newburg check 3d vinyl single shower curtain + hoo
4 0.556 partial rodas vinyl shower curtain
5 0.554 exact siniard single shower curtain
6 0.552 partial 71 '' x71 '' 4pcs shower curtain sets beach theme
7 0.550 exact almazan lightweight single shower curtain
8 0.549 exact simmon vinyl single shower curtain liner
9 0.546 partial vinyl striped shower curtain set
10 0.542 partial cindy window vinyl single shower curtain
exact in the top 10: 5
partial in the top 10: 5
irrelevant in the top 10: 0
unjudged in the top 10: 0
similarity spread in the top 10: 0.035
ndcg@10: 0.793
On this query, semantic retrieval does better than BM25. Its top 10 holds 5 exact products, against BM25's 4, and 0 irrelevant ones. Its nDCG@10 is 0.793, against BM25's 0.615. Notice how close the similarities are: the first and the tenth differ by 0.035. Semantic retrieval always returns something, ranked by small differences.
One query can mislead, so compare the two rankers on every test query:
1"""Scores BM25 and semantic retrieval on every test query and counts the queries each one is better on. The prose's point that the test set is too small to show a pattern rests on the `better` and `size in inches` lines."""2from lib.lexical import LexicalSearch3from lib.metrics import evaluate4from lib.semantic import SemanticSearch5from lib.store import load_products, load_queries, qrels67products, queries, judgments = load_products(), load_queries("test"), qrels("test")8bm25 = evaluate(LexicalSearch(products).run(queries, k=100), judgments)9semantic = evaluate(SemanticSearch().run(queries, k=100), judgments)1011for name, scores in [("bm25", bm25), ("semantic", semantic)]:12 print(f"{name} ndcg@10: {scores['ndcg@10'].mean():.3f}")13 print(f"{name} judged@10: {scores['judged@10'].mean():.3f}")1415# per test query, rounded to three decimals: queries that differ only beyond the third place count as tied16difference = (semantic["ndcg@10"] - bm25["ndcg@10"]).round(3)17print("semantic better:", (difference > 0).sum())18print("bm25 better:", (difference < 0).sum())19print("tied:", (difference == 0).sum())20sized = queries["query"].str.contains(r"\d+\s*(?:inch|in\b|\"|'')") # a size in inches21print("test queries with a size in inches:", sized.sum())22print("of those, bm25 better:", (difference[sized] < 0).sum())23print()24print("queries where bm25 is better:")25print(queries.loc[difference[difference < 0].index, "query"].to_string())
python compare-lexical-semantic.pybm25 ndcg@10: 0.725
bm25 judged@10: 0.927
semantic ndcg@10: 0.830
semantic judged@10: 0.990
semantic better: 21
bm25 better: 7
tied: 2
test queries with a size in inches: 2
of those, bm25 better: 2
queries where bm25 is better:
query_id
63 monthly calendar
72 fold in half table
94 kohler whitehaven farmhouse kitchen sink
285 48" sliding single track , barn door for laundry
292 decorative white pillow
293 wood floor protector mat
482 48 inch kitchen hood
Averaged over the test queries, semantic retrieval is ahead: an nDCG@10 of 0.830 against BM25's 0.725. Its judged@10, 0.990, is also higher than BM25's 0.927, so part of BM25's deficit could come from products nobody judged. For outdoor light fixtures, at least, those products are light bulbs, and a score of 0 is fair.
Semantic retrieval is better on 21 queries, BM25 on 7, and 2 are tied. The store has only 30 test queries, so chapter 3 tests whether a gap like this one is larger than chance.
BM25 is better on 2 of the 2 test queries that give a size in inches. Exact tokens such as sizes and model numbers may favour matching words, but a count this small can't show a pattern. On the train queries that contain a digit, BM25 is better on 1 of 5 (Find the queries each retriever wins), and the embedding model matches digits too, as text (Check queries that contain digits).
A theoretical result shows where single vectors fall short. Weller et al. prove that an embedding's dimension limits which combinations of top results a single vector can return. On LIMIT, a dataset they built to test that limit, BM25 finds 93.6% of the relevant items in its top 100, and the best single-vector model 18.9%. On a variant of LIMIT with words replaced by synonyms, BM25's score drops by more than 89% (Weller et al., 2025). Lexical and semantic retrieval fail in different places.
Working rule: Add semantic retrieval when shoppers describe what they want in their own words. Don't assume lexical retrieval wins on exact terms such as sizes, brands and model numbers: before you rely on it there, count which retriever wins the train queries that contain them. On this data, semantic retrieval alone scores highest so far, so it is the ranker to beat.
逆順位融合で二つのランキングを融合する
語彙検索と意味検索は失敗する箇所が異なるため、ハイブリッド検索は双方のランキング、ここではBM25のランキングと意味検索のランキングを組み合わせ、両者の長所を保つことを狙う。両者のスコアは尺度が異なるので、そのまま足し合わせることはできない(その理由は第7章で示す)。逆順位融合(reciprocal rank fusion、RRF)は順位だけを用いることでこの問題を避ける。各商品は、自身を含むランキングごとに、定数と順位の和で1を割った値をスコアとして得る。そして、それらのスコアを合算する。
RRF(product) = sum over rankings r of 1 / (k + rank of product in r), with k = 60
定数kは上位を平坦にする。k = 60のとき、1位は1/61、10位は1/70を得る。したがって、二つのランキングの両方のランキングで上位に近い商品は、一方のランキングでだけ最上位にある商品を上回る。著者らはパイロット研究でk = 60に固定し、「この選択は決定的ではなかった」と報告している(Cormack et al., 2009)。融合の対象としたのは二種類のランで、一つはText REtrieval Conferenceの共通評価であるTRECへの提出ラン、もう一つは一つの検索システムの30通りの構成である。これらの実験では、RRFは平均適合率の平均(mean average precision、MAP)において、最良の個別ランを平均で4%から5%上回った。MAPは、各クエリで関連する結果の位置における適合率を求め、それをクエリ全体で平均したものである。これは語彙検索と意味検索のランキングを一つずつ融合する場合とは設定が異なり、ハイブリッド検索を扱った後続の研究では、正規化したスコアをチューニング済みの重みで足し合わせる方法がRRFを上回ると報告されている(Bruch et al., 2023)。第7章では両者を訓練クエリでチューニングする。ここでは、RRFをチューニングせずに用いる。
RRFは短いので、二つの関数として手で書ける。rrf_scoresは一つのクエリの商品にスコアを付け、reciprocal_rank_fusionはすべてのクエリについて商品を順序付ける。スコアが等しい商品はproduct_idの順に並べ、どちらのランキングも先に渡されたことで同点を制することがないようにする。例hybrid-rrfでは、すべてのテストクエリについてBM25と意味検索の上位100件を融合し、clear shower curtainで最上位になる二つの商品のスコアを確かめたうえで、ハイブリッドのランを採点する。
BM25のスコアは0.725、意味検索のスコアは0.830であり、弱いほうのランカーにも同じ票が与えられる。その票が融合ランを引き下げるのか、それとも両者が互いの取りこぼしを十分に補い合って意味検索を上回るのか。出力を読む前に、次の三つの答えのうち一つを決めておくこと。意味検索より上、両者の間、BM25より下である。
1"""Fuses BM25 and semantic retrieval with reciprocal rank fusion, by hand for one query and then for every test query. The prose's point rests on the hybrid's `ndcg@10` line and on the two scores printed for the first product, which agree."""2from lib.lexical import LexicalSearch3from lib.metrics import evaluate4from lib.semantic import SemanticSearch5from lib.store import load_products, load_queries, qrels678def rrf_scores(rankings, k=60):9 """Each product scores the sum of 1 / (k + rank) over the rankings that contain it."""10 scores = {}11 for ranking in rankings:12 for rank, product_id in enumerate(ranking, start=1):13 scores[product_id] = scores.get(product_id, 0) + 1 / (k + rank)14 return scores151617def reciprocal_rank_fusion(runs, k=60, depth=100):18 """For each query, products in order of their RRF scores, best first; equal scores by product_id."""19 fused = {}20 for query_id in runs[0]:21 scores = rrf_scores([run[query_id] for run in runs], k)22 # equal scores fall back to product_id, so neither ranking wins ties by being passed first23 fused[query_id] = sorted(scores, key=lambda product_id: (-scores[product_id], product_id))[:depth]24 return fused252627products, queries, judgments = load_products(), load_queries("test"), qrels("test")28bm25, semantic = LexicalSearch(products).run(queries, k=100), SemanticSearch().run(queries, k=100)29hybrid = reciprocal_rank_fusion([bm25, semantic])3031for place, product_id in zip(["first", "second"], hybrid[246]): # query 246, "clear shower curtain"32 # list.index counts from 0, and a rank counts from 133 bm25_rank, semantic_rank = bm25[246].index(product_id) + 1, semantic[246].index(product_id) + 134 print(f"{place} product: {products.at[product_id, 'name']}")35 print(f"{place} product's bm25 rank: {bm25_rank}")36 print(f"{place} product's semantic rank: {semantic_rank}")37 # the formula with the two ranks in it, where k = 6038 print(f"{place} product's score by hand: {1 / (60 + bm25_rank) + 1 / (60 + semantic_rank):.5f}")39 print(f"{place} product's score from rrf_scores: {rrf_scores([bm25[246], semantic[246]])[product_id]:.5f}")4041hybrid_scores, semantic_scores = evaluate(hybrid, judgments), evaluate(semantic, judgments)42print(f"hybrid ndcg@10: {hybrid_scores['ndcg@10'].mean():.3f}")43print(f"hybrid judged@10: {hybrid_scores['judged@10'].mean():.3f}")44difference = (hybrid_scores["ndcg@10"] - semantic_scores["ndcg@10"]).round(3)45print("better than semantic:", (difference > 0).sum())46print("worse than semantic:", (difference < 0).sum())47print("tied with semantic:", (difference == 0).sum())
python hybrid-rrf.pyfirst product: woolley vinyl solid color single shower curtain
first product's bm25 rank: 3
first product's semantic rank: 1
first product's score by hand: 0.03227
first product's score from rrf_scores: 0.03227
second product: woolley vinyl single shower curtain
second product's bm25 rank: 2
second product's semantic rank: 2
second product's score by hand: 0.03226
second product's score from rrf_scores: 0.03226
hybrid ndcg@10: 0.812
hybrid judged@10: 0.980
better than semantic: 9
worse than semantic: 14
tied with semantic: 7
融合後の最初の商品woolley vinyl solid color single shower curtainは、BM25のランキングでは3位、意味検索のランキングでは1位にある。そのスコアは各ランキングから一項ずつ加えた1/(60 + 3) + 1/(60 + 1)であり、手計算では0.03227となって、rrf_scoresが返す値と一致する。
二番目のwoolley vinyl single shower curtainは、BM25のランキングでは2位、意味検索のランキングでは2位にあり、スコアは0.03226となるため、2位になる。
ハイブリッドのランのスコアは0.812で、BM25は上回るものの、意味検索単独には及ばない。クエリごとに見ると、意味検索を上回るクエリが9件、下回るクエリが14件、並ぶクエリが7件である。judged@10は0.980である。
つまり、ここでは融合しても意味検索単独を上回れなかった。これは検索が悪化したという意味ではない。なぜ改善しなかったのかは第7章で扱う。第7章では、融合の前に各検索器を調べ、訓練クエリで配合をチューニングする。
意味検索より上と答えた場合、そこから得られる教訓は、二つのランキングを組み合わせても向上が保証されるわけではないということである。融合も他の変更と同じ変更の一つであり、測定しなければならない。
実践ルール: 融合する前に、各検索器を単独で測定する。RRFはk = 60をチューニングなしの既定値として用い、融合したランキングは、保持しておいたクエリで最良の単独検索器を上回る場合にだけ採用する。一方の検索器がはるかに弱い場合は、同じ票を与えるのではなく、ランキングに重みを付けるか、訓練クエリでkをチューニングすることを試す。第7章ではこの店のデータで両方を試すが、テストクエリで報告されるチューニング済みの配合のうち、意味検索を上回るものはない(テストクエリでチューニング済みの配合を報告する)。
上位50件をクロスエンコーダで再ランキングする
ここまでの段階はすべて検索であり、検索はクエリごとにカタログ内のすべての商品を採点しなければならないため、軽量でなければならない。再ランキング(reranking)は、検索で得た短い候補リストを、より低速なモデルで並べ替える処理である。見る商品は数十件にすぎないため、モデルはクエリと各商品を一緒に読む余裕を持てる。
再ランキングモデルの一種にクロスエンコーダ(cross-encoder)がある。クロスエンコーダは、クエリと商品テキストを一つの入力として一緒に読み、その組に対して一つの関連度スコアを出力する。各組は互いに独立に採点される(Nogueira and Cho, 2019)。埋め込みモデルは商品だけを読むので、そのベクトルは事前に計算できる。クロスエンコーダはクエリを必要とするため、事前に計算できるものが何もなく、すべての組に対して実行すると時間がかかる。Sentence-BERTの比較で遅い側だったのは、BERTがクロスエンコーダとしてすべての文の組を読む方式である。そのためクロスエンコーダは、より安価な第一段階が取得した候補リストを再ランキングする(Nogueira and Cho、2節、Retrieve & Re-Rank)。このコストと引き換えに、クロスエンコーダはアテンション(attention)を通じて、クエリのすべての単語を商品のすべての単語と関連づけることができる。アテンションとは、入力中の各単語が他の単語を参照できるようにするモデルの仕組みである。Reimers and Gurevych(2019、4.3節)は、BERTがアテンションによって二つの文を直接比較できると述べている。2019年、MS MARCOのパッセージベンチマークで、BM25の上位1,000件のパッセージをこの方法で再ランキングしたところ、最初の関連パッセージがどれだけ上位に来るかを表す指標MRR@10が、それまでの最良の結果に対して相対的に27%改善した(Nogueira and Cho)。
クロスエンコーダは言語モデルであるが、**大規模言語モデル(LLM)**ではない。LLMとは、大量のテキストで訓練され、プロンプトに応じてテキストを生成するモデルである。後続の章では、判定、書き換え、再ランキングにLLMを使う。クロスエンコーダは何も生成せず、一つの数値を出力する。
このストアのクロスエンコーダはオープンモデルのAlibaba-NLP/gte-reranker-modernbert-baseである。選んだ理由は埋め込みモデルと同じで、オープンかつApache 2.0ライセンスであるため、誰でも記録を再実行できるからである。その記録であるrecordings/cross_encoder.pyは、各クエリについてBM25と意味検索の上位100件の和集合に含まれるすべての商品に対するモデルのスコアを一度だけ保存したものであり、ハイブリッドの上位50件のすべての商品にスコアが付く。再ランキングの段階では、BM25と意味検索をRRFで融合したハイブリッドの実行結果の上位50件をそのスコアで並べ替え、残りはそのままの位置に置き、結果を採点する。本書ではこれを再ランキング済みハイブリッドと呼ぶ。
1"""Reorders the top 50 of the hybrid run by cross-encoder score, keeps the rest in place, and scores the result. The prose's point rests on the reranked nDCG@10 line, set beside the hybrid's score, and on the better and worse counts."""2from lib.fusion import reciprocal_rank_fusion3from lib.lexical import LexicalSearch4from lib.metrics import evaluate5from lib.recorded import cross_encoder_scores, manifest6from lib.semantic import SemanticSearch7from lib.store import load_products, load_queries, qrels89products, queries, judgments = load_products(), load_queries("test"), qrels("test")10bm25 = LexicalSearch(products).run(queries, k=100)11semantic = SemanticSearch().run(queries, k=100)12hybrid = reciprocal_rank_fusion([bm25, semantic]) # the same function as in the hybrid section1314recorded = cross_encoder_scores() # one score per (query, product) pair15score = {(query_id, product_id): value for query_id, product_id, value in recorded.itertuples(index=False)}16print("cross-encoder model:", manifest("cross-encoder")["model"])1718depth = 50 # rerank the top 5019reranked = {}20for query_id, ranking in hybrid.items():21 # the top 50 are reordered by score; equal scores keep the hybrid's order22 top = sorted(ranking[:depth], key=lambda product_id: score[(query_id, product_id)], reverse=True)23 # products below the top 50 keep their hybrid order24 reranked[query_id] = top + ranking[depth:]2526before, after = evaluate(hybrid, judgments), evaluate(reranked, judgments)27print(f"reranked ndcg@10: {after['ndcg@10'].mean():.3f}")28print(f"reranked judged@10: {after['judged@10'].mean():.3f}")29difference = (after["ndcg@10"] - before["ndcg@10"]).round(3)30print("better than hybrid:", (difference > 0).sum())31print("worse than hybrid:", (difference < 0).sum())
python cross-encoder-rerank.pycross-encoder model: Alibaba-NLP/gte-reranker-modernbert-base
reranked ndcg@10: 0.798
reranked judged@10: 0.980
better than hybrid: 11
worse than hybrid: 12
ここでは再ランキングは効果を上げていない。スコアは0.798で、元になったハイブリッドの実行結果の0.812を下回る。改善したクエリは11件、悪化したクエリは12件である。この章全体では、テストクエリでの結果は次のとおりである。
| ランカー | nDCG@10 | judged@10 |
|---|---|---|
| BM25 | 0.725 | 0.927 |
| 意味検索 | 0.830 | 0.990 |
| ハイブリッド(RRF、k = 60) | 0.812 | 0.980 |
| 再ランキング済みハイブリッド(上位50件) | 0.798 | 0.980 |
悪化したクエリの一つであるrefrigerator with ice an water in doorは、再ランキングがどのように順位を落とすかを示している。
1"""Shows the hybrid and reranked top 5 for one query whose nDCG@10 the reranker lowered, with each product's cross-encoder score and judgment. The prose's point rests on the two rank lines and the two nDCG@10 lines."""2import re34from lib.fusion import reciprocal_rank_fusion5from lib.lexical import LexicalSearch6from lib.metrics import ndcg_at_k7from lib.recorded import cross_encoder_scores8from lib.semantic import SemanticSearch9from lib.store import load_products, load_queries, product_text, qrels1011LABELS = {2: "exact", 1: "partial", 0: "irrelevant"}1213products = load_products()14query_id = 40615query = load_queries().at[query_id, "query"]16judgments = qrels()[query_id]17recorded = cross_encoder_scores()18score = recorded[recorded["query_id"] == query_id].set_index("product_id")["score"]1920bm25 = {query_id: list(LexicalSearch(products).search(query, k=100).index)}21semantic = {query_id: list(SemanticSearch().search(query_id, k=100).index)}22hybrid = reciprocal_rank_fusion([bm25, semantic])[query_id]23# the top 50 are reordered by score; the rest stay in the hybrid's order24reranked = sorted(hybrid[:50], key=score.get, reverse=True) + hybrid[50:]2526print("query:", query)27for name, ranking in [("hybrid", hybrid), ("reranked", reranked)]:28 first_exact = next(rank for rank, product_id in enumerate(ranking, start=1) if judgments.get(product_id) == 2)29 print()30 print(f"{name} ndcg@10: {ndcg_at_k(ranking, judgments, 10):.3f}")31 print(f"{name} rank of the first exact product: {first_exact}")32 for product_id in ranking[:5]:33 label = LABELS.get(judgments.get(product_id), "unjudged")34 print(f" {score[product_id]:.2f} {label:<10} {products.at[product_id, 'name']}")353637exact = next(product_id for product_id in hybrid if judgments.get(product_id) == 2)38words = set(re.findall(r"\w+", product_text(products).at[exact].lower())) # name, class, category, description39print()40print("hybrid's first exact product:", products.at[exact, "name"])41print("its text says ice or water:", "yes" if {"ice", "water"} & words else "no")
python rerank-one-query.pyquery: refrigerator with ice an water in door
hybrid ndcg@10: 0.660
hybrid rank of the first exact product: 3
1.95 partial apec water icemaker-kit-38-14-ro refrigerator/icemaker installation accessory
2.06 partial 36 '' french door 26.1 cu . ft. smart energy star refrigerator with interior ice maker
1.44 exact 36 '' french door refrigerator 27 cu . ft. energy star refrigerator
2.19 partial 36 '' energy star counter-depth french door 22.6 cu . ft. refrigerator with ice maker
2.19 partial 800 series 21 cu . ft. smart energy star counter depth french door refrigerator with internal water dispenser
reranked ndcg@10: 0.533
reranked rank of the first exact product: 9
2.20 partial smeg classic 36 '' french door 22 cu . ft. refrigerator with ice maker
2.19 partial 36 '' energy star counter-depth french door 22.6 cu . ft. refrigerator with ice maker
2.19 partial 800 series 21 cu . ft. smart energy star counter depth french door refrigerator with internal water dispenser
2.10 partial 28 '' energy star counter depth top freezer 12.56 cu . ft. refrigerator with auto ice maker
2.06 partial 36 '' french door 26.1 cu . ft. smart energy star refrigerator with interior ice maker
hybrid's first exact product: 36 '' french door refrigerator 27 cu . ft. energy star refrigerator
its text says ice or water: no
クロスエンコーダは最初の完全一致の商品を埋もれさせ、順位を3位から9位に下げて、このクエリのnDCG@10を0.660から0.533に落としている。再ランキング後の上位5件は、名称にice makerやwater dispenserを含む冷蔵庫であり、判定者はこれらを部分一致と判定した。求められている対象である冷蔵庫には合致するが、修飾語である、ドアに付いた氷と水には合致しないからである。ハイブリッドの実行結果で最初の完全一致であったフレンチドア式の冷蔵庫は、ハイブリッドの上位5件の中でクロスエンコーダのスコアが最も低い。
判定者はその冷蔵庫を完全一致と判定したので、データセットの定義ではクエリに完全に合致する。しかしそのテキストには氷も水も記されておらず、テキストだけを読むモデルでは、その修飾語に基づいて順位づけすることはできない。WANDSの判定者は、商品名に加えて各商品の画像とウェブページも見ており(アノテーションガイドライン)、テキストに書かれていないことをおそらくそこから読み取れた。汎用の再ランカーは、このストアの判定を一度も見たことがない。9章では、訓練クエリの判定を使ってランカーを訓練する。
実践ルール: 組ごとにコストが増えるので、候補リスト(ここでは50件の商品)を再ランキングする。再ランキングを採用するのは、保持したクエリで、検索単独の最良の結果を上回る場合に限る。この再ランカーはハイブリッドの実行結果にも意味検索にも及ばなかったため、このストアの現時点で最良のパイプラインは意味検索単独である。再ランキングをあきらめる前に、深さを変えるか、自分の判定で訓練したランカーを試すとよい。なお、9章のテストクエリでは、深さを変えてもLambdaMARTを使っても意味検索を上回らない(予算から再ランキングの深さを決める、テストクエリでLambdaMARTを報告する)。
この部分はまだ翻訳されていないため、英語で表示している。
What goes wrong in production
The tokenizer drops words without telling you. bm25s's default tokenizer keeps only tokens of two or more characters and doesn't stem words (bm25s tokenizer). Run it on a train query and a test query, and count the products it can't match:
1"""Tokenizes one train query, one test query and the products' text with bm25s, and counts the products that have `chairs` or only `chair`. The prose's points rest on the printed token lists and on the two product counts."""2import bm25s34from lib.store import load_products, product_text567def tokenize(texts):8 """The tokenizer lib.lexical uses for products and queries, with bm25s's default settings."""9 # stopwords="en" removes English words such as "and"; no stemmer is set, so "chairs" and "chair" stay different tokens10 return bm25s.tokenize(texts, stopwords="en", return_ids=False, show_progress=False)111213for query in ["ge top loading washer 4.5", "bistro table and chairs"]:14 print(f"{query!r} -> {tokenize([query])[0]}")1516products = tokenize(product_text(load_products()).tolist())17print()18print("products with the token chairs:", sum("chairs" in tokens for tokens in products))19print("products with chair but not chairs:", sum("chair" in tokens and "chairs" not in tokens for tokens in products))
python tokenizer-drops-terms.py'ge top loading washer 4.5' -> ['ge', 'top', 'loading', 'washer']
'bistro table and chairs' -> ['bistro', 'table', 'chairs']
products with the token chairs: 895
products with chair but not chairs: 359
The 4.5 in ge top loading washer 4.5 disappears, because 4 and 5 are one character each, so that number plays no part in the ranking. And chairs matches only products that say chairs: 895 products do, while 359 say chair and never chairs, and none of those can match that word of bistro table and chairs. Neither case raises an error. Chapter 5 shows both problems and adds stemming.
Unjudged results look like failures. A ranker that surfaces products nobody judged gets lower scores than it may deserve, and a ranker that surfaces the judged ones gets an advantage. Report judged@10 with every score, and have new products judged when it drops.
Scores from a sample are probably optimistic. The sample keeps 12,000 products, nearly all judged for some query. The full WANDS catalog has 42,994 (repository), and a store's catalog may be far larger, with more near misses competing for the top 10. Nothing in this chapter measures that, but expect lower scores on a full catalog. Don't compare the scores here with the WANDS paper's either: it ran the BM25 of Solr, a search server, over product titles and descriptions (Chen et al.).
Model outputs belong to one model version. Product and query embeddings must come from the same model at the same version, or their similarities aren't comparable. Change the model and you re-embed the whole catalog. Each folder in examples/data/recorded/ has a manifest.json that pins the model and its version.
Reranking costs time on every query. Product embeddings are computed once. A cross-encoder runs on every pair, for every query, while the shopper waits. In this chapter, a recording script computes the scores ahead of time on a GPU, which hides that cost. Chapter 9 counts what each rerank depth costs (Set the rerank depth from a budget).
Working rule: Check the tokens your queries become, track judged@10, and record the model version next to every vector you store.
この章で下した決定
これらの既定値は、後の章がいずれかを train クエリで検証するまで維持される。
- test で報告し、train で調整する。 この章のスコアはすべて、30 件の test クエリに対するものである。この章では何も調整しない。後の章では、50 件の train クエリのみを用いて調整する。
- 主要指標は nDCG@10 とし、judged@10 を併記する。 等級を利得として用い、未判定の商品は等級 0 として数える。judged@10 は、この仮定が結果に大きく影響する場合にそれを示す。
- ベースラインは、bm25s の既定値の BM25 とする。 すなわち
k1=1.5およびb=0.75であり、各商品の名称、クラス、カテゴリ、説明文を対象とする。調整は、train クエリで測定できるようになるまで行わない。 - 意味検索は、単一のオープンモデルの記録済み埋め込みを用いる。 単位長ベクトルの内積で比較するため、すべての例がオフラインで動作し、毎回同じ出力が得られる。モデル間の比較選択は後で扱う問題である。
- ハイブリッド検索は、k = 60、等しい重みの RRF とし、調整は行わない。 考案者が用いた設定のままである。
- 再ランキングの深さは、ハイブリッド検索の上位 50 件とする。 記録済みのクロスエンコーダでスコアを付けるため、再ランキングされたすべての商品に記録済みのスコアがある。実際のストアでは、深さは品質だけでなくコストにかかわる判断でもある。
- 打ち負かすべきランカーは、意味検索単独である。 このデータでは、融合も今回の再ランカーも、意味検索単独を上回らなかったためである。第3章では、評価ハーネスを用いて、こうした差が偶然による差より大きいかどうかを検証する。
- この章で示されたこと: 有効であるはずの段階、すなわち融合や再ランキングが、このデータでは意味検索を上回らなかった。したがって、変更はすべて、採用する前に測定する。
この版における本章
第2026.11.10版2026年11月19日時点で例が通過この章の11 例件のうち11件が合格
英語版の書籍(版2026.11.10)から翻訳した。