測試變更

閱讀約需 67 分鐘 分鐘,12 節 中共有 11 個範例。

版次 2026.11.10 範例於 2026年11 月 19 通過測試 132 個範例中有 132 個通過 變更內容

由 AI 翻譯。經人工以英文驗證。 我們如何製作書籍

譯自英文書,版次 2026.11.10。 閱讀原文

讀完本章後,你能夠判斷一項搜尋變更是否應該上線:逐一查詢比對兩個排序器的結果、避免測試查詢讓變更看起來比實際更好、估算 A/B 測試所需的規模,以及透過交錯(interleaving)排序結果來比較兩個排序器。

本書一路追蹤的商店是一家販售家具與家居用品的線上零售商(第 1 章),其搜尋框目前仍以 BM25 作為基準線。前幾章的離線工作已讓語意檢索相對於 BM25 取得確立的領先(第 3 章)。換用語意檢索是一項變更,之後的每一次調整也是:更便宜的嵌入、混合權重、重排序器。每項變更都會引出同樣四個問題。平均值上升了嗎?上升幅度是否超過雜訊?哪些查詢變差了?相關性判斷能否為新的結果評分?購物者的行為會如同相關性判斷所預測的嗎?本章依此順序回答這些問題。商店的 30 筆測試查詢成為其迴歸測試集,也就是每項變更都要通過的固定查詢,而每一項選擇都以其 50 筆訓練查詢為依據。商店沒有點擊記錄(click log),因此線上各節以模擬的購物者進行,並在每項模擬旁註明其假設。

本章在測試查詢上規劃了一項比較:語意檢索對上 BM25。依循第 3 章,一項規劃好的比較可保留本書完整的 0.05 顯著水準,因此在此處差異低於 0.05 即視為成立。本章中測試查詢上的其他所有分數,都屬於探索性結果。

逐一查詢比較兩次執行結果

最近一次變動於第 2026.11.10 版

前兩個問題,也就是平均值是否上升,以及哪些查詢變差,要在迴歸測試集上回答:這是一組固定的查詢,附有相關性判斷,每項變更在上線前都要對它執行。商店目前使用的排序器是基準,加入變更後的排序器則是候選排序器。兩者各自產生一次執行結果,也就是測試集中每個查詢的排名。只比較兩次執行的平均值並不夠,因為變更可能拉高平均值,卻仍讓部分查詢變差。TREC(Text REtrieval Conference)是搜尋系統的共同評測活動,它在 2013 年的 Web track 中針對這項風險設計了一項任務,逐一查詢計算各系統相對於基準的勝負(Collins-Thompson et al., 2014)。因此要對兩次執行做差異比較:每個查詢一列,列出基準的分數、候選的分數與變化量。接著統計勝、負與平手的數量,並逐一閱讀變差的查詢。

基準是 BM25,候選是語意檢索,兩者都在測試查詢上以 nDCG@10 評分。本範例以 pandas 建立差異表,檢定則來自 lib.significance,該模組由第 3 章親手建立。這些檢定包括排列檢定與成對 t 檢定。旁邊另有一個自助法區間,其信賴水準與門檻相符。自助法與排列檢定都以隨機方式重抽樣,因此 lib.significance 以 rng 設定 SciPy 的亂數種子(第 3 章)。

diff-semantic-against-bm25.py Python 3.12.15 · bm25s 0.3.16 · numpy 2.5.5 · pandas 3.1.1 · scipy 1.18.1 通過
"""Scores each test query under BM25 and semantic retrieval, then runs the chapter's one planned comparison on the difference. The verdict rests on the 'permutation test p' and 'established' lines, read against 'threshold'."""import pandas as pdfrom lib.lexical import LexicalSearchfrom lib.metrics import evaluatefrom lib.semantic import SemanticSearchfrom lib.significance import comparefrom lib.store import load_products, load_queries, qrelsPLANNED_COMPARISONS = 1                      # this chapter's tests on the test queriesthreshold = 0.05 / PLANNED_COMPARISONS       # Bonferroni: one comparison keeps 0.05products, queries, judgments = load_products(), load_queries("test"), qrels("test")baseline = evaluate(LexicalSearch(products).run(queries, k=100), judgments)      # what the store runscandidate = evaluate(SemanticSearch().run(queries, k=100), judgments)            # the changediff = pd.DataFrame({"query": queries["query"], "bm25": baseline["ndcg@10"], "semantic": candidate["ndcg@10"]})# rounded to 3 decimals, as lib.significance rounds before it counts wins, losses and tiesdiff["change"] = (diff["semantic"] - diff["bm25"]).round(3)        # one row per test queryprint(f"bm25 ndcg@10: {diff['bm25'].mean():.3f}")print(f"semantic ndcg@10: {diff['semantic'].mean():.3f}")result = compare(candidate["ndcg@10"], baseline["ndcg@10"], confidence=1 - threshold)    # chapter 3's comparisonprint(f"mean change: {result['mean difference']:.3f}")print(f"threshold: {threshold:g}")print(f"permutation test p: {result['permutation p']:.3f}")print(f"paired t-test p: {result['t-test p']:.3f}")print(f"{(1 - threshold) * 100:g}% interval: {result['ci low']:.3f} to {result['ci high']:.3f}")print("established:", "yes" if result["permutation p"] < threshold else "no")print("wins:", (diff["change"] > 0).sum())print("losses:", (diff["change"] < 0).sum())print("ties:", (diff["change"] == 0).sum())print(f"largest loss: {diff['change'].min():.3f}")print()print(diff[diff["change"] < 0].sort_values("change").round(3).to_string())
輸出python diff-semantic-against-bm25.py
bm25 ndcg@10: 0.725
semantic ndcg@10: 0.830
mean change: 0.105
threshold: 0.05
permutation test p: 0.001
paired t-test p: 0.003
95% interval: 0.055 to 0.185
established: yes
wins: 21
losses: 7
ties: 2
largest loss: -0.092

                                                     query   bm25  semantic  change
query_id
292                                decorative white pillow  0.467     0.375  -0.092
293                               wood floor protector mat  0.653     0.568  -0.084
482                                   48 inch kitchen hood  1.000     0.921  -0.079
63                                        monthly calendar  1.000     0.931  -0.069
285       48" sliding single track , barn door for laundry  0.592     0.555  -0.037
72                                      fold in half table  1.000     0.965  -0.035
94                kohler whitehaven farmhouse kitchen sink  0.694     0.690  -0.004

語意檢索將 nDCG@10 的平均值從 0.725 提高到 0.830,變化量為 0.105。對照 0.05 的門檻,排列檢定得到 0.001。這項變化是否成立?yes。此外,成對 t 檢定得到 0.003,95% 區間為 0.055 to 0.185。

從變差的查詢中才能學到東西。語意檢索在 21 個查詢上獲勝,在 7 個查詢上落敗,2 個查詢平手,最大的退步是 -0.092。其中兩個退步的查詢含有以英寸表示的尺寸,即 48 inch kitchen hood 與 48" sliding single track , barn door for laundry:這只是兩個查詢,還不能算是規律。第 6 章會對所有含數字的查詢檢驗這項規律。

實用原則: 保留一組經過判斷的迴歸測試查詢,且絕不以它進行調校,並讓每個候選都對照基準在此集合上執行。先列出計畫中的比較項目,再為每一項報告其排列檢定 p 值、t 檢定與區間。統計勝、負與平手的數量,並在上線前閱讀每一個退步的查詢。當退步的查詢看似有共同規律時,先在訓練查詢上檢驗,再採取行動,然後修正這類查詢,或將它們交給基準處理。

以 URisk 讓損失的權重高於獲益

最近一次變動於第 2026.11.8 版

逐查詢差異會計算損失的數量,但平均變化仍把一個變差 0.1 的查詢與一個變好 0.1 的查詢視為互相抵銷。商店未必這麼看:購物者昨天找得到的商品,今天卻找不到,就是遇到了退步,其他地方稍微好一點的排序無法彌補。風險敏感(risk-sensitive)評估對損失的計重高於獲益。

TREC 2013 Web track 的風險敏感指標是 URisk。對每個查詢 q,令 Δ(q) 為候選系統的分數減去基準系統的分數。將變好的查詢上的獲益加總,減去變差的查詢上的損失(計 α + 1 倍),再除以查詢數 N:

URisk = (1 / N) × [ sum of Δ(q) over improved queries  −  (α + 1) × sum of |Δ(q)| over hurt queries ]

該 track 將此描述為「損失的權重是成功的 α + 1 倍」,而 α = 0 時得到的就是一般的平均變化(Collins-Thompson et al.,第 4.3 節)。該 track 的概述在損失項中直接印出 Δ(q),但這在變差的查詢上是負值。我們採用其大小 |Δ(q)|,這是唯一能讓 α = 0 時得到平均值(如概述所言)的讀法。α 是一種選擇,而不是事實。我們使用 α = 1,因此每個損失都算兩倍。

我們以 BM25 為基準,比較兩個候選系統。第一個是完整的語意檢索,使用 Snowflake/snowflake-arctic-embed-m-v1.5 為每個嵌入產生的全部 768 個數值。第二個只保留前 128 個數值,也就是六分之一的記憶體。這低於該模型的模型卡所記載的 256 維,而且第 6 章已在訓練查詢上否決了 128。我們使用它,是因為在測試查詢上,它以某些查詢的獲益換取另一些查詢的損失,而這正是 URisk 的用途。它是依其在測試集上的表現而選出的,因此屬於探索性比較,而不是事先規劃的比較。URisk 只需幾行程式;對兩個候選系統都執行它:

urisk-of-two-candidates.py Python 3.12.15 · bm25s 0.3.16 · numpy 2.5.5 · pandas 3.1.1 · scipy 1.18.1 通過
"""URisk for full semantic retrieval and for the 128-number version, each against BM25, with every loss counted alpha + 1 times. The prose's point rests on the 'semantic 128 urisk with alpha 1' line, read against its mean change."""from lib.lexical import LexicalSearchfrom lib.metrics import evaluatefrom lib.semantic import SemanticSearchfrom lib.significance import comparefrom lib.store import load_products, load_queries, qrelsALPHA = 1                                   # each loss counts alpha + 1 times: here, doubledef urisk(change, alpha):    """Mean change per query, with every loss counted alpha + 1 times (TREC 2013 Web track)."""    # gains are the positive changes; losses are the negative ones, made positive    wins, losses = change.clip(lower=0).sum(), -change.clip(upper=0).sum()    return (wins - (alpha + 1) * losses) / len(change)products, queries, judgments = load_products(), load_queries("test"), qrels("test")baseline = evaluate(LexicalSearch(products).run(queries, k=100), judgments)candidates = {"semantic": SemanticSearch(), "semantic 128": SemanticSearch(dims=128)}   # all 768 numbers, or the first 128print(f"bm25 judged@10: {baseline['judged@10'].mean():.3f}")evaluated = {name: evaluate(search.run(queries, k=100), judgments) for name, search in candidates.items()}for name, scores in evaluated.items():    # rounded to 3 decimals, so the wins and losses count the printed changes    change = (scores["ndcg@10"] - baseline["ndcg@10"]).round(3)    print(f"{name} judged@10: {scores['judged@10'].mean():.3f}")    print(f"{name} mean change: {change.mean():.3f}")    print(f"{name} wins: {(change > 0).sum()}")    print(f"{name} losses: {(change < 0).sum()}")    print(f"{name} largest loss: {change.min():.3f}")    print(f"{name} urisk with alpha {ALPHA}: {urisk(change, ALPHA):.3f}")# a demonstration, chosen for how it behaves on test: its tests describe it, and it is never establishedresult = compare(evaluated["semantic 128"]["ndcg@10"], baseline["ndcg@10"], confidence=0.95)print(f"semantic 128 permutation test p: {result['permutation p']:.3f}")print(f"semantic 128 paired t-test p: {result['t-test p']:.3f}")print(f"semantic 128 interval: {result['ci low']:.3f} to {result['ci high']:.3f}")
輸出python urisk-of-two-candidates.py
bm25 judged@10: 0.927
semantic judged@10: 0.990
semantic mean change: 0.105
semantic wins: 21
semantic losses: 7
semantic largest loss: -0.092
semantic urisk with alpha 1: 0.092
semantic 128 judged@10: 0.920
semantic 128 mean change: 0.017
semantic 128 wins: 15
semantic 128 losses: 13
semantic 128 largest loss: -0.253
semantic 128 urisk with alpha 1: -0.033
semantic 128 permutation test p: 0.592
semantic 128 paired t-test p: 0.597
semantic 128 interval: -0.036 to 0.088

完整語意檢索的平均變化是 0.105,URisk 是 0.092。它的 7 個損失都很小,最大為 -0.092,因此加倍計算後代價不大。

較便宜的排序器,其平均變化是 0.017,但損失以兩倍計算後,URisk 為 -0.033。它在 15 個查詢上獲勝,在 13 個查詢上落敗,最大損失為 -0.253。它的平均值掩蓋了這項取捨:某些查詢的結果變好,代價是另一些查詢的結果變差。

它的排列檢定(permutation test)得到 0.592,成對 t 檢定得到 0.597,95% 區間為 -0.036 to 0.088。

它的部分損失可能是無人判斷過的商品,因為它的 judged@10 是 0.920,而 BM25 為 0.927,完整語意檢索為 0.990。下一節會加以檢查。

URisk 描述風險,但不對風險做檢定。Dinçer 等人定義了相關的指標 TRisk,它「是 t 統計量的線性轉換」,因此可以像成對 t 檢定一樣進行檢定(Dinçer et al., 2014)。

實用原則: 為每個候選系統在平均變化旁報告 α = 1 的 URisk。無論平均值如何,都不要上線 URisk 為負的候選系統,並閱讀其損失以找出原因。當失敗的代價高昂時,提高 α,並另外報告商店最常見查詢上的 URisk。只有當某個查詢上的損失不比另一個查詢上的獲益更糟時,才使用 α = 0。

評判新排序器浮現的商品

最近一次變動於第 2026.11.10 版

新排序器的失分,例如URisk 範例中較便宜的排序器,可能來自相關性判斷的缺口,因為這些判斷只涵蓋先前系統找到的商品。WANDS 是這家商店相關性判斷的來源,它只評判了先前系統找到的商品(第 2 章)。與這些系統不同的排序器,會浮現無人評判過的商品,而指標會給每個這類商品 等級 0,因此它的分數可能偏低,也可能剛好正確。在有人評判之前,你無從得知是哪一種。WANDS 的作者警告,這類缺口會削弱評估:「incompleteness in Product Search dataset does negatively impact the discriminative power of the evaluation」(Chen et al., 2022)。

第 2 章用 judged@10 計算未評判的商品數。若要測試一項改動,還有一個步驟有幫助:敏感度檢查。它在兩種情境下重新為兩次執行評分,每種情境各偏向一方。其中一種情境假設基準版前 10 名中所有未評判的商品都是完全相關;另一種則假設候選版前 10 名中所有未評判的商品都是完全相關。在每種情境下,兩次執行都使用相同的判斷來評分,因為 nDCG 的理想排序是由該查詢的所有判斷建立的:一個被判為完全相關的商品會提高理想值,因此會降低每一個沒有呈現該商品的執行的分數。這兩種情境並不是上下界,因為真實的判斷可能混合兩者。如果領先者在兩種情境之間改變,就表示目前的判斷還無法做出決定。

URisk 範例中較便宜的語意檢索,每個嵌入向量 768 個數值中只保留 128 個,在這家商店的測試查詢中對 BM25 輸了 13 個。在你從這些失分解讀出任何意義之前,先執行這項檢查:

unjudged-score-range.py Python 3.12.15 · bm25s 0.3.16 · numpy 2.5.5 · pandas 3.1.1 · scipy 1.18.1 通過
"""Mean nDCG@10 for BM25, the cheaper ranker and full semantic retrieval, when each run's unjudged top-10 products are judged exact in turn. The prose's point rests on the 'leader changes' line for semantic 128 against BM25, read against the scores printed before it."""import numpy as npfrom lib.lexical import LexicalSearchfrom lib.metrics import ndcg_at_kfrom lib.semantic import SemanticSearchfrom lib.store import load_products, load_queries, qrelsproducts, queries, judgments = load_products(), load_queries("test"), qrels("test")runs = {"bm25": LexicalSearch(products).run(queries, k=100),        "semantic 128": SemanticSearch(dims=128).run(queries, k=100),        "semantic": SemanticSearch().run(queries, k=100)}def unjudged(run):    """(query_id, product_id) pairs in a run's top 10 that nobody judged."""    return {(query_id, product_id) for query_id in judgments for product_id in run[query_id][:10]            if product_id not in judgments[query_id]}def score(run, exact=()):    """Mean nDCG@10 with the given unjudged pairs judged exact, for every run alike: the ideal moves too."""    # a copy of the judgments, so each scenario changes only its own exact pairs    scenario = {query_id: dict(grades) for query_id, grades in judgments.items()}    # grade 2 is exact, the top grade    for query_id, product_id in exact:        scenario[query_id][product_id] = 2    return np.mean([ndcg_at_k(run[query_id], scenario[query_id], 10) for query_id in scenario])for name in ["bm25", "semantic 128"]:    print(f"unjudged pairs in the top 10, {name}: {len(unjudged(runs[name]))}")# the empty set is the judgments as they arescenarios = {"as judged": set(), **{f"{name}'s unjudged exact": unjudged(runs[name]) for name in runs}}scores = {(scenario, name): score(run, exact) for scenario, exact in scenarios.items() for name, run in runs.items()}for scenario, name in [("as judged", "bm25"), ("as judged", "semantic 128"), ("bm25's unjudged exact", "bm25"),                       ("bm25's unjudged exact", "semantic 128"), ("bm25's unjudged exact", "semantic"),                       ("semantic 128's unjudged exact", "bm25"), ("semantic 128's unjudged exact", "semantic 128")]:    print(f"{scenario}, {name}: {scores[scenario, name]:.3f}")for candidate in ["semantic 128", "semantic"]:    # a set holding both True and False means the leader changes between scenarios    leaders = {scores[s, candidate] > scores[s, "bm25"] for s in scenarios}    print(f"leader changes, {candidate} against bm25:", "yes" if len(leaders) > 1 else "no")# | is the union: pairs either run shows, each counted onceprint("pairs to judge, semantic 128 against bm25:", len(unjudged(runs["bm25"]) | unjudged(runs["semantic 128"])))
輸出python unjudged-score-range.py
unjudged pairs in the top 10, bm25: 22
unjudged pairs in the top 10, semantic 128: 24
as judged, bm25: 0.725
as judged, semantic 128: 0.742
bm25's unjudged exact, bm25: 0.788
bm25's unjudged exact, semantic 128: 0.738
bm25's unjudged exact, semantic: 0.829
semantic 128's unjudged exact, bm25: 0.718
semantic 128's unjudged exact, semantic 128: 0.807
leader changes, semantic 128 against bm25: yes
leader changes, semantic against bm25: no
pairs to judge, semantic 128 against bm25: 46

領先者有改變嗎?yes。因此,目前的判斷還無法對這項比較做出定論。依現有判斷來看,較便宜的排序器領先,0.742 對 0.725。

如果 BM25 未評判的商品都是完全相關,BM25 會領先,0.788 對 0.738。如果較便宜排序器未評判的商品都是完全相關,它會領先,0.807 對 0.718。

BM25 的前 10 名中有 22 個未評判的配對,較便宜排序器的前 10 名中有 24 個。這項比較要等 46 筆判斷完成,相較於上線錯誤排序器的代價,這是一筆小開銷。

不要猜測評判者會怎麼說。在一個舊的 TREC 集合上,Voorhees 等人評判了來自神經模型與 BM25 執行的新文件池,發現絕大多數新文件並不相關(Voorhees et al., 2022)。但該集合是從許多系統深入建池而來,而 WANDS 的建構方式不同。人工判斷是參照標準。大型語言模型(LLM)的判斷成本較低。第 4 章以它們填補這家商店未評判的配對,作為診斷之用,並且在填補後的等級改變了某個結論或兩個排序器的順序時,交由人來評判這些配對。Thomas 等人提出一項在測試改動時很重要的風險:由 LLM 產生的標籤可能偏袒本身使用 LLM 的排序器(Thomas et al., 2024)。

實用原則: 對每個候選版,計算兩次執行的 judged@10,並在兩種情境下重新評分。當領先者改變時,先評判未評判的配對再進行比較,並將新的判斷永久加入回歸集,使它涵蓋你測試過的每個排序器。當領先者在兩種情境下都不變時,未評判的商品不太可能逆轉這項比較。

此部分尚未翻譯,因此以英文呈現。

Keep the test queries out of every choice

最近一次變動於第 2026.11.8 版

The test queries in the regression set are held out, and held-out queries give an honest score only if nothing was chosen by looking at them. Training on test queries is the obvious mistake. Choosing on them is the subtle one: try several settings, keep the one that scores best on them, and report that score. The winner is partly the best setting and partly the luckiest on those particular queries, so its score is too high. Dwork et al. state the risk: "Reusing a holdout set adaptively multiple times can easily lead to overfitting to the holdout set itself" (Dwork et al., 2015). The damage can be smaller than feared. When ImageNet's test set was rebuilt, classifiers lost accuracy, but Recht et al.'s results suggest that adaptivity doesn't cause the drops: the new images were harder (Recht et al., 2019). In our judgement, a set of 30 queries leaves little room, and every look counts.

The change is a blend of BM25 and semantic retrieval with one weight, the share given to semantic retrieval. Chapter 7 calls it α, a different α from URisk's, and tunes it on the train queries with weighted reciprocal rank fusion, over 0, 0.1, … 1. Choose the semantic weight both ways, the right way on train queries and the wrong way on test queries, and report each choice on the test queries. These test scores show the bias; they are exploratory, not a planned comparison. Then measure how much choosing on the reported queries inflates their score, without touching the test queries again: split the train queries at random, 1,000 times, into 30 to choose on and 20 to report on, and compare the 20 reported queries' score when the weight is chosen on the 30 with their score when it is chosen on the 20 themselves.

tuning-on-test-inflates.py Python 3.12.15 · bm25s 0.3.16 · numpy 2.5.5 · pandas 3.1.1 · scipy 1.18.1 通過
"""Chooses the blend's semantic weight on train queries and on test queries, then measures how much choosing on the queries you report inflates their score. The prose's point rests on the 'average inflation' line, read against the two 'test ndcg@10' lines."""import numpy as npfrom lib.blend import best_alpha, scores_by_alpha, weighted_rrffrom lib.lexical import LexicalSearchfrom lib.semantic import SemanticSearchfrom lib.store import load_products, load_queries, qrelsqueries, judgments = load_queries(), qrels()                  # all 80 queries, train and testbm25 = LexicalSearch(load_products()).run(queries, k=100)semantic = SemanticSearch().run(queries, k=100)per_query = scores_by_alpha(lambda weight: weighted_rrf(bm25, semantic, weight), judgments)   # nDCG@10, a column per weighttrain = per_query.loc[load_queries("train").index]test = per_query.loc[load_queries("test").index]# best_alpha breaks ties toward the smaller weightchosen_on_train, chosen_on_test = best_alpha(train), best_alpha(test)print("settings tried:", per_query.shape[1])print(f"semantic alone, test ndcg@10: {test[1.0].mean():.3f}")print("semantic weight chosen on train:", chosen_on_train)print(f"test ndcg@10, weight chosen on train: {test[chosen_on_train].mean():.3f}")print("semantic weight chosen on test:", chosen_on_test)print(f"test ndcg@10, weight chosen on test: {test[chosen_on_test].mean():.3f}")# How much does choosing on the queries you report inflate the score? Split the train queries# at random, 30 to choose on and 20 to report on, and compare the two ways of choosing.# a fixed seed, so the random splits are the same on every runrng = np.random.default_rng(2026)scores = train.to_numpy()inflation = []for _ in range(1000):    order = rng.permutation(len(scores))    # the first 30 of the shuffled queries choose the weight; the other 20 report it    choose, report = scores[order[:30]].mean(axis=0), scores[order[30:]].mean(axis=0)    # argmax takes the first of equal means, the smaller weight, as best_alpha does    inflation.append(report.max() - report[choose.argmax()])print(f"average inflation, 20 reported queries: {np.mean(inflation):.3f}")
輸出python tuning-on-test-inflates.py
settings tried: 11
semantic alone, test ndcg@10: 0.830
semantic weight chosen on train: 0.6
test ndcg@10, weight chosen on train: 0.825
semantic weight chosen on test: 0.8
test ndcg@10, weight chosen on test: 0.835
average inflation, 20 reported queries: 0.007

Choosing the weight on the test queries flatters the blend. Chosen there, the semantic weight is 0.8, and the blend scores 0.835.

Chosen on train, it is 0.6, and the blend scores 0.825 on the test queries, against 0.830 for semantic retrieval alone. Only that train-chosen score fairly estimates how the blend does on queries it wasn't chosen on. Chapter 7 tests the train-chosen blend against semantic retrieval and finds no improvement.

The random splits put a number on the bias. On report sets of 20 queries, choosing on the queries you report adds 0.007 to nDCG@10 on average, with 11 settings to choose from. That gain appears in the report and nowhere else. Each extra setting you try is another chance for a lucky winner.

Working rule: Choose every setting on train queries, including which candidate to take forward. Look at the test queries once per decision, and log each look: what you compared and what you chose. When a test set has guided many decisions, move it to the train side and judge a fresh set of test queries.

執行 A/B 測試

最近一次變動於第 2026.11.10 版

離線測試是對照人工判斷來衡量排序結果,但商店的收益來自購物者。A/B 測試,或稱受控實驗,會將使用者隨機分配到現行系統或變更後的系統,並比較在測試開始前就選定的指標(Kohavi et al., 2009)。現行系統是對照組(control),變更後的系統是實驗組(treatment)。

三項檢查可以讓結果值得信賴。第一,A/A 測試是兩組都使用相同系統的測試,在 95% 信賴水準下,應有約 5% 的機率拒絕虛無假設(Kohavi et al., 2009)。若遠高於 5%,表示實驗設置有問題。第二,只在規劃的樣本規模下讀取一次結果。一看到顯著就停止測試,稱為偷看(peeking),會大幅推高第一型錯誤率(Kohavi et al., 2022)。第三,檢查各組的規模是否符合規劃。樣本比例不匹配(sample ratio mismatch,SRM)表示某一組的使用者流失,或被不均勻地加入,而「在不知道根本原因的情況下忽略 SRM,可能使一項不良的產品修改看起來是好的」(Fabijan et al., 2019)。

對於轉換率指標,也就是購買的購物者比例,測試會比較兩個比例。設每組各有 n 位購物者,比率分別為 p_A 與 p_B,p̄ 為兩者的平均:

z = (p_B − p_A) / sqrt( p̄ × (1 − p̄) × 2 / n ),   p-value = 2 × P(Z > |z|)

為了觀察偷看的影響,我們在明列的假設下模擬 2,000 次 A/A 測試:每組每天 2,000 位購物者,購買率為 5%,每次測試規劃 14 天。每次測試都在規劃的結束日讀取結果,也每天讀取一次,並在 p 值第一次低於 0.05 時停止。接著檢查一次分組是否有不匹配。

aa-tests-with-peeking.py Python 3.12.15 · numpy 2.5.5 · scipy 1.18.1 通過
"""Simulates A/A tests, where both groups get the same search, read at the planned end and every day, and checks one split for a mismatch. The prose's point rests on the 'significant at the planned end' and 'significant on some day' lines, and on the sample ratio mismatch line."""import numpy as npfrom scipy import stats# Assumptions for the simulation, not the store's data: 2,000 shoppers a day in each group,# 5% of them buy, and the test is planned to run 14 days. Both groups get the same search (an A/A test).TESTS, DAYS, SHOPPERS_PER_DAY, CONVERSION = 2000, 14, 2000, 0.05# a fixed seed, so the simulated tests are the same on every runrng = np.random.default_rng(2026)buyers = rng.binomial(SHOPPERS_PER_DAY, CONVERSION, size=(TESTS, DAYS, 2)).cumsum(axis=1)   # running totalsshoppers = SHOPPERS_PER_DAY * np.arange(1, DAYS + 1)[None, :]                               # per group, by dayrate_a, rate_b = buyers[..., 0] / shoppers, buyers[..., 1] / shopperspooled = (rate_a + rate_b) / 2# two-proportion z for each day, using the pooled rate of the two groupsz = (rate_b - rate_a) / np.sqrt(pooled * (1 - pooled) * 2 / shoppers)# two-sided: a gap in either direction countsp_value = 2 * stats.norm.sf(np.abs(z))print(f"simulated A/A tests: {TESTS:,}")# the last day is the planned end, day 14print(f"significant at the planned end: {(p_value[:, -1] < 0.05).mean():.3f}")print(f"significant on some day, checked daily: {(p_value < 0.05).any(axis=1).mean():.3f}")# A sample ratio mismatch: the split was planned 50/50, but the groups came out unequal.control, treatment = 28_000, 27_100# the default expected share is one half, as in a 50/50 splitp = stats.binomtest(treatment, control + treatment).pvalueprint(f"sample ratio mismatch p: {p:.3f}" if p >= 0.001 else "sample ratio mismatch p: below 0.001")
輸出python aa-tests-with-peeking.py
simulated A/A tests: 2,000
significant at the planned end: 0.053
significant on some day, checked daily: 0.231
sample ratio mismatch p: below 0.001

每天檢查會讓遠多得多的 A/A 測試看起來顯著。在規劃的結束日讀取時,呈現顯著的比例為 0.053,接近門檻所保證的 0.05。每天檢查時,在某一天看起來顯著的比例升至 0.231,但兩組的搜尋都沒有改變。對於規劃為 50/50、結果卻是 28,000 對 27,100 的分組,以二項檢定檢驗 55,100 位購物者中的 27,100 位相對於二分之一,得到的 p 值為 below 0.001:這樣大的差距幾乎不可能由隨機因素產生。

p 值常被誤解:0.05 並不代表結果有 5% 的機率是偽陽性;Kohavi et al.(2022)稱這是「非常常見的誤解」。p 值是在變更沒有任何作用的情況下,出現至少這麼極端的資料的機率。

實用原則: 測試之前,先選定主要指標以及不得惡化的護欄指標,並決定測試規模(含檢定力)。先在相同的設置上執行 A/A 測試。在讀取任何結果之前,先檢查樣本比例,並且只在規劃的規模下讀取一次結果。若必須在測試進行中監看,請使用為持續監測而設計的序列方法,例如隨時有效 p 值(always-valid p-values,Johari et al., 2015)。

以檢定力決定測試規模

最近一次變動於第 2026.11.8 版

要在規劃好的樣本數下只讀取一次 A/B 測試 的結果,就得先依測試的檢定力(power)規劃這個樣本數。檢定力是測試偵測出某個特定大小之真實變化的機率。檢定力不足的測試會漏掉真實的變化;即使結果達到顯著,也往往會誇大效果:「檢定力偏低而達到統計顯著的發現,很可能大幅誇大效果的大小」(Kohavi et al., 2022)。因此,應在測試開始前,根據兩個數字決定規模:指標在使用者之間的變異程度,以及值得偵測的最小變化。變異越大,需要的使用者越多。變化越小,需要的使用者多出許多,因為變化量是以平方的形式進入公式。

對於兩組、95% 信賴水準與 80% 檢定力的情況,Kohavi et al. 給出一個經驗法則,其中 σ² 為指標的變異數,Δ 為要偵測的變化量(Kohavi et al., 2009):

users per group ≈ 16 × σ² / Δ²

16 來自常態分布:2 × (97.5% 對應的 z 值 + 80% 對應的 z 值)²,約為 2 × (1.96 + 0.84)²。若檢定力為 90%,他們以 21 取代 16。scipy 會計算這個係數,程式碼則以他們的兩個實算範例檢驗此法則:平均為 $3.75、標準差為 $30 的每位使用者營收,以及 5% 的轉換率,兩者都要偵測 5% 的相對變化。商店的資料來自 WANDS,沒有銷售數字,因此程式碼假設商店的轉換率同樣為 5%。

sample-size-from-power.py Python 3.12.15 · scipy 1.18.1 通過
"""Kohavi et al.'s rule of thumb for users per group, its coefficient, and the users the store would need for smaller changes, assuming its 5% conversion rate. The prose's point rests on the two 'users per group for a change' lines, read against the coefficient line."""from scipy import statsSIGNIFICANCE, POWER = 0.05, 0.80z = stats.norm.ppf(1 - SIGNIFICANCE / 2) + stats.norm.ppf(POWER)    # 1.96 + 0.84print(f"coefficient for two groups: {2 * z ** 2:.1f}")                # rounds to the 16 of the rule of thumbdef users_per_group(variance, change):    """Kohavi et al.'s rule of thumb: about 16 * variance / change**2 users in each group."""    return 16 * variance / change ** 2# Their worked examples: revenue per user (mean $3.75, standard deviation $30), and a 5% conversion rate,# each with a 5% relative change to detect.print(f"users per group, revenue: {users_per_group(30 ** 2, 0.05 * 3.75):,.0f}")# a conversion rate's variance is p times (1 - p), here with p = 5%; the change is 5% of that rateprint(f"users per group, conversion: {users_per_group(0.05 * 0.95, 0.05 * 0.05):,.0f}")# The store, assuming a 5% conversion rate like theirs: smaller changes need far more users.for relative in [0.02, 0.01]:    # the change in conversion, as an absolute rate: a relative change of this size in the 5% rate    print(f"users per group for a {relative:.0%} change: {users_per_group(0.05 * 0.95, 0.05 * relative):,.0f}")
輸出python sample-size-from-power.py
coefficient for two groups: 15.7
users per group, revenue: 409,600
users per group, conversion: 121,600
users per group for a 2% change: 760,000
users per group for a 1% change: 3,040,000

變化減半,所需的使用者就變成四倍:在商店假設的 5% 轉換率下,2% 的變化每組需要 760,000 位使用者,1% 的變化則需要 3,040,000 位。

係數為 15.7,營收與轉換率兩個範例每組分別需要 409,600 與 121,600 位使用者,與論文中超過 409,000 與不到 122,000 的數字相符。

同樣的算法也能說明迴歸測試集可以偵測到什麼。兩個排序器對同一批查詢評分,所以這項測試處理的是單一一組逐查詢差異的樣本,而不是兩組,係數因此減半,成為 7.8。將 σ 取為兩個相近排序器之間這些差異的離散程度:語意檢索,以及將它與 BM25 融合的混合執行結果。

queries-needed-for-power.py Python 3.12.15 · bm25s 0.3.16 · numpy 2.5.5 · pandas 3.1.1 · scipy 1.18.1 通過
"""The smallest change the regression set detects with 80% power, from the spread of per-query changes, and a simulation that checks the power formula. The prose's point rests on the 'smallest change 30 queries detect' line and the simulated power lines."""import numpy as npfrom scipy import statsfrom lib.fusion import reciprocal_rank_fusionfrom lib.lexical import LexicalSearchfrom lib.metrics import evaluatefrom lib.semantic import SemanticSearchfrom lib.store import load_products, load_queries, qrelsSIGNIFICANCE, POWER = 0.05, 0.80queries, judgments = load_queries("test"), qrels("test")bm25 = LexicalSearch(load_products()).run(queries, k=100)semantic = SemanticSearch().run(queries, k=100)hybrid = reciprocal_rank_fusion([bm25, semantic])change = evaluate(hybrid, judgments)["ndcg@10"] - evaluate(semantic, judgments)["ndcg@10"]spread = change.std()                                     # of the per-query differencesz = stats.norm.ppf(1 - SIGNIFICANCE / 2) + stats.norm.ppf(POWER)print(f"spread of per-query changes: {spread:.3f}")print(f"coefficient for paired queries: {z ** 2:.1f}")     # one sample of differences, so half of 16# z standard errors of the mean change: the smallest change the test can detectdetectable = z * spread / np.sqrt(len(change))print(f"smallest change 30 queries detect: {detectable:.3f}")# n = z squared times spread squared, over the change squared, solved for nprint(f"queries needed for a change of 0.01: {z ** 2 * spread ** 2 / 0.01 ** 2:.0f}")# Check the arithmetic by simulation: draw 30 normally distributed changes with that mean and spread,# 10,000 times, and test each. The real differences aren't normal, so this checks the formula, not the data.rng = np.random.default_rng(2026)# ttest_1samp tests each draw against popmean 0, the no-change nullpower = stats.power(stats.ttest_1samp, lambda size: rng.normal(detectable, spread, size=size), (len(change),),                    significance=SIGNIFICANCE, kwargs={"popmean": 0})# .item() takes the single value out of the result, which holds one simulated powerprint(f"simulated power at that change: {power.power.item():.3f}")print("simulated power below the planned 0.8:", "yes" if power.power.item() < POWER else "no")
輸出python queries-needed-for-power.py
spread of per-query changes: 0.062
coefficient for paired queries: 7.8
smallest change 30 queries detect: 0.032
queries needed for a change of 0.01: 300
simulated power at that change: 0.779
simulated power below the planned 0.8: yes

逐查詢變化的離散程度為 0.062,因此在 30 個測試查詢下,迴歸測試集能以 80% 的檢定力偵測到 nDCG@10 上 0.032 的變化。若要偵測 0.01 的變化,則需要 300 個查詢。

scipy.stats.power 以模擬檢驗這項算術,方法是抽取呈常態分布的差異:在該變化量下,成對 t 檢定的模擬檢定力為 0.779。這是否低於規劃的 0.8?yes,因為公式使用的是常態分布,而針對測試查詢的 t 檢定使用的是較寬的 t 分布。真實的差異並非常態,所以模擬檢驗的是公式,而不是資料。增加查詢時,應大量增加,並讓每個查詢只做淺層判定:Webber et al. 發現,在相同的判定工作量下,大量淺層判定的查詢比少量深層判定的查詢能提供更高的統計檢定力(Webber et al., 2008)。

實用原則: 每個 A/B 測試都要在開始前先決定規模。如果所需的使用者比商店數週內的流量還多,可以測試更大的變化、使用變異較小的指標,或以每位使用者在測試前的資料來調整指標。在 Bing 的實驗中,Deng et al. 報告這種做法「可將變異數降低約 50%」(Deng et al., 2013);能節省多少,取決於使用者過去的行為對該指標的預測能力。離線時,計算迴歸測試集可偵測的最小變化,當你的改動更小時就增加查詢。事先固定這個數量:不斷增加查詢直到檢定力估計顯示足夠為止,會使你偏向找到顯著性(Webber et al.)。

以 team draft 交錯兩種排名

最近一次變動於第 2026.11.10 版

A/B 測試會讓每一組使用者看到不同的排名,因此購物者之間的差異會帶來雜訊。交錯比較(interleaving)則讓每位購物者看到一份混合兩個排序器結果的清單。Joachims 設計這種方法時,目標是讓「合併後的排名對兩個搜尋引擎帶來(幾乎)相等的呈現偏誤」(Joachims, 2003):任一排序器的商品都不會系統性地排得較高。商品獲得較多點擊的排序器,就贏得該次搜尋。交錯比較回答的問題比 A/B 測試更窄:它只能得知使用者偏好兩種排名中的哪一種,而不是任一種排名的絕對數值(Hofmann et al., 2016)。

Team draft 交錯兩個排序器的清單,做法就像為比賽挑選隊員(Radlinski et al., 2008,Algorithm 2)。挑選次數較少的隊伍先選,兩隊次數相同時則以擲硬幣決定。每次挑選的是該隊排名最高且尚未顯示的商品。點擊會算給挑選該商品的那一隊。Radlinski 等人證明,在 team draft 之下,「隨機點擊的使用者在期望值上,對 A 與對 B 產生的偏好次數總是相等」,而較早的方法無法保證這一點。

以測試查詢 clear shower curtain 為例,交錯本店的語意檢索與 BM25 的結果。Team draft 只需寥寥數行程式碼,擲硬幣使用設定了種子的產生器,程式碼並會檢查 lib.experiments 是否傳回相同的清單:

team-draft-one-query.py Python 3.12.15 · bm25s 0.3.16 · numpy 2.5.5 · pandas 3.1.1 · scipy 1.18.1 通過
"""Team draft over one query's semantic and BM25 rankings: the interleaved list, and the team that picked each place. The prose's point rests on the BM25 pick at the bottom of the list, and on the 'same list' line that checks lib.experiments."""import numpy as npfrom lib import experimentsfrom lib.lexical import LexicalSearchfrom lib.semantic import SemanticSearchfrom lib.store import load_products, load_queries, qrelsLABELS = {2: "exact", 1: "partial", 0: "irrelevant"}def team_draft(ranking_a, ranking_b, rng, length=10):    """Like picking teams: the team with fewer picks goes next, a coin flip decides when they're level,    and each team adds its best product that isn't shown yet."""    shown, teams = [], []    while len(shown) < length:        picks_a, picks_b = teams.count("a"), teams.count("b")        # the coin is drawn only when the teams are level        a_picks = picks_a < picks_b or (picks_a == picks_b and rng.random() < 0.5)        ranking, team = (ranking_a, "a") if a_picks else (ranking_b, "b")        # the team's best product that isn't shown yet, from its own ranking        shown.append(next(p for p in ranking if p not in shown))        teams.append(team)    return shown, teamsproducts, queries, judgments = load_products(), load_queries("test"), qrels("test")[246]   # clear shower curtainsemantic = list(SemanticSearch().search(246, k=100).index)bm25 = list(LexicalSearch(products).search(queries.at[246, "query"], k=100).index)shown, teams = team_draft(semantic, bm25, np.random.default_rng(7))# judgments.get returns None for a product nobody judged, and LABELS.get then gives 'unjudged'# names are cut at 45 characters to keep the columns alignedfor position, (product_id, team) in enumerate(zip(shown, teams), start=1):    name = {"a": "semantic", "b": "bm25"}[team]    print(f"{position:>2}  {name:<8}  {LABELS.get(judgments.get(product_id), 'unjudged'):<10}  {products.at[product_id, 'name'][:45]}")# lib.experiments holds the same function, which the simulations useprint("same list from lib.experiments:", "yes" if experiments.team_draft(semantic, bm25, np.random.default_rng(7)) == (shown, teams) else "no")
輸出python team-draft-one-query.py
 1  bm25      partial     rodas vinyl shower curtain
 2  semantic  exact       woolley vinyl solid color single shower curta
 3  bm25      exact       woolley vinyl single shower curtain
 4  semantic  partial     newburg check 3d vinyl single shower curtain
 5  bm25      exact       siniard single shower curtain
 6  semantic  partial     71 '' x71 '' 4pcs shower curtain sets beach t
 7  semantic  exact       almazan lightweight single shower curtain
 8  bm25      exact       simmon vinyl single shower curtain liner
 9  semantic  partial     vinyl striped shower curtain set
10  bm25      irrelevant  gilded pineapple shower curtain hooks
same list from lib.experiments: yes

Team draft 一律讓每個排序器在十個位置的清單中各占 5 個位置,由擲硬幣決定是哪幾個位置。兩個排序器都排得很前面的商品只會出現一次,並算給最先選走它的那一隊,因此同一件商品不會讓任一排序器重複得分。對這個查詢而言,BM25 排出的其中一個浴簾掛鉤(第 1 章)會出現在清單最底部,作為 BM25 的最後一個挑選。購物者點擊語意檢索挑選的商品,算給語意檢索;點擊 BM25 挑選的商品,則算給 BM25;點擊較多的一隊贏得該次搜尋。

實用原則: 當你需要知道使用者偏好哪一個排序器,並希望以比 A/B 測試更少的搜尋次數線上比較兩個排序器時,請使用 team-draft 交錯比較。若你需要的是絕對數值(例如營收),或變更的對象不在排名上,則改用 A/B 測試。依我們的推論,交錯後的清單無法呈現延遲、頁面版面或結果數量不同所造成的影響。

以模擬購物者預演交錯測試

最近一次變動於第 2026.11.8 版

WANDS 是商店資料的來源,其中沒有點擊紀錄,因此商店無法對真實購物者執行團隊選取式交錯測試(team-draft interleaving),但可以用模擬的購物者來預演。點擊模型(click model)是一種機率模型,描述使用者如何瀏覽並點擊結果清單,既用來建構指標,也用來模擬使用者(Chuklin et al., 2015)。級聯模型(cascade model)認為使用者從頂端開始閱讀,並在「一看到有價值的文件就離開」(Craswell et al., 2008;參見第 2 章)。標準的模擬方式依循此模型:均勻隨機抽出一個查詢,沿著它的清單往下走,依各商品的等級以對應機率點擊該商品,點擊之後再依等級以另一個機率離開(Oosterhuis and de Rijke, 2018)。交錯測試的研究也以這種方式檢驗其方法,點擊是由已標註的資料模擬而來(Hofmann et al., 2011)。

這些機率是假設值。Oosterhuis 與 de Rijke 的表 2 針對五個等級給出一種「導航型」(navigational)使用者,也就是只尋找單一高度相關結果的使用者,我們稱之為導航型購物者。我們把不相關、部分相關與完全相關對應到該使用者最低、中間與最高的等級,如同各項指標的做法,將未經判定的商品視為不相關,且每個查詢被抽中的次數相同。這些數值集中放在同一處,即 lib.experiments:

等級 點擊 點擊後停止
完全相關 0.95 0.9
部分相關 0.5 0.5
不相關 0.05 0.2

讓一位這樣的購物者,以手動方式瀏覽 clear shower curtain 的團隊選取式清單:

one-simulated-shopper.py Python 3.12.15 · bm25s 0.3.16 · numpy 2.5.5 · pandas 3.1.1 · scipy 1.18.1 通過
"""One simulated navigational shopper walks the team-draft list for clear shower curtain, clicking and leaving by the cascade model. The prose's point rests on the two 'clicks for' lines and the verdict line, and on the 'same clicks' line that checks lib.experiments."""import numpy as npfrom lib.experiments import NAVIGATIONAL, cascade_clicks, team_draftfrom lib.lexical import LexicalSearchfrom lib.semantic import SemanticSearchfrom lib.store import load_products, load_queries, qrelsLABELS = {2: "exact", 1: "partial", 0: "irrelevant"}products, queries, judgments = load_products(), load_queries("test"), qrels("test")[246]   # clear shower curtainsemantic = list(SemanticSearch().search(246, k=100).index)bm25 = list(LexicalSearch(products).search(queries.at[246, "query"], k=100).index)shown, teams = team_draft(semantic, bm25, np.random.default_rng(7))       # the team-draft example's listteam_names = {"a": "semantic", "b": "bm25"}# the same seed as the check at the end, so both draw the same clicksrng = np.random.default_rng(2026)clicks = []for position, product_id in enumerate(shown):    grade = judgments.get(product_id, 0)                                  # unjudged counts as 0    # click and stop probabilities for the grade: 0 irrelevant, 1 partial, 2 exact    clicked = rng.random() < NAVIGATIONAL["click"][grade]    # the second draw happens only after a click, the order cascade_clicks uses    leaves = clicked and rng.random() < NAVIGATIONAL["stop"][grade]        # only a click can end the visit    label = LABELS.get(judgments.get(product_id), "unjudged")    print(f"{position + 1:>2}  {team_names[teams[position]]:<8}  {label:<10}  {'clicks' if clicked else '':<6}  {'leaves' if leaves else ''}")    if clicked:        clicks.append(position)    if leaves:        breakcredited = [team_names[teams[position]] for position in clicks]       # each click counts for the team that picked itfor_semantic, for_bm25 = credited.count("semantic"), credited.count("bm25")print("clicks for semantic:", for_semantic)print("clicks for bm25:", for_bm25)print("this search goes to:", "semantic" if for_semantic > for_bm25 else "bm25" if for_bm25 > for_semantic else "neither, a tie")print("same clicks from lib.experiments:", "yes" if cascade_clicks(shown, judgments, np.random.default_rng(2026)) == clicks else "no")
輸出python one-simulated-shopper.py
 1  bm25      partial     clicks
 2  semantic  exact       clicks  leaves
clicks for semantic: 1
clicks for bm25: 1
this search goes to: neither, a tie
same clicks from lib.experiments: yes

這位購物者的點擊在語意檢索得到 1,在 BM25 得到 1,因此這次搜尋的判定結果是 neither, a tie。以固定的隨機種子模擬 10,000 次交錯搜尋,比較兩組:語意檢索對 BM25,以及混合執行對語意檢索。符號檢定(sign test)檢驗勝場是否比敗場多出超過機遇所能解釋的程度;Radlinski et al. 使用「二項符號檢定」,並排除平手。分別在 100、1,000 與 10,000 次搜尋時讀取判定結果:

simulated-interleaving-verdict.py Python 3.12.15 · bm25s 0.3.16 · numpy 2.5.5 · pandas 3.1.1 · scipy 1.18.1 通過
"""Sign tests on simulated interleaved searches, at 100, 1,000 and 10,000 searches, for two pairs of rankers and a third pair with BM25's ties reversed. The prose's point rests on the 'verdict changes' line and the 100-search lines for the hybrid against semantic retrieval."""import numpy as npfrom scipy import statsfrom lib.experiments import NAVIGATIONAL, simulate_interleavingfrom lib.fusion import reciprocal_rank_fusionfrom lib.lexical import LexicalSearchfrom lib.semantic import SemanticSearchfrom lib.store import load_products, load_queries, qrelsfor grade, label in [(2, "exact"), (1, "partial"), (0, "irrelevant")]:      # the assumptions, from lib.experiments    print(f"{label} click probability: {NAVIGATIONAL['click'][grade]}")    print(f"{label} stop probability: {NAVIGATIONAL['stop'][grade]}")# lexsort's last key sorts first: the score, highest first, then the product_id, highest first among tiesdef ties_reversed(scores):              # BM25's ranking, with equal scores in descending product_id order instead    return scores.index[np.lexsort((-scores.index.to_numpy(), -scores.to_numpy()))].tolist()queries, judgments = load_queries("test"), qrels("test")lexical = LexicalSearch(load_products())bm25 = lexical.run(queries, k=100)                                        # equal scores by product_idsemantic = SemanticSearch().run(queries, k=100)hybrid = reciprocal_rank_fusion([bm25, semantic])bm25_reversed = {q: ties_reversed(lexical.search(query, k=100)) for q, query in queries["query"].items()}pairs = {"semantic against bm25": (semantic, bm25), "hybrid against semantic": (hybrid, semantic),         "hybrid with bm25 ties reversed against semantic": (reciprocal_rank_fusion([bm25_reversed, semantic]), semantic)}below = {}for name, (run_a, run_b) in pairs.items():    # a fresh seed for each pair, so every pair sees the same 10,000 queries    outcomes = simulate_interleaving(run_a, run_b, judgments, 10_000, np.random.default_rng(2026))    for searches in [100, 1_000, 10_000]:        # the first 100, 1,000 or 10,000 of the same searches, so the three verdicts share data        wins, losses = (outcomes[:searches] == 1).sum(), (outcomes[:searches] == -1).sum()        p = stats.binomtest(wins, wins + losses).pvalue                  # sign test; ties left out        below[name, searches] = p < 0.05        shown = f"{p:.3f}" if p >= 0.001 else "below 0.001"        print(f"{name}, {searches:,} searches: {wins} wins, {losses} losses, p {shown}")changes = below["hybrid against semantic", 100] != below["hybrid with bm25 ties reversed against semantic", 100]print("hybrid against semantic, verdict at 100 searches changes with bm25 ties reversed:", "yes" if changes else "no")
輸出python simulated-interleaving-verdict.py
exact click probability: 0.95
exact stop probability: 0.9
partial click probability: 0.5
partial stop probability: 0.5
irrelevant click probability: 0.05
irrelevant stop probability: 0.2
semantic against bm25, 100 searches: 51 wins, 36 losses, p 0.133
semantic against bm25, 1,000 searches: 519 wins, 347 losses, p below 0.001
semantic against bm25, 10,000 searches: 5222 wins, 3552 losses, p below 0.001
hybrid against semantic, 100 searches: 32 wins, 51 losses, p 0.048
hybrid against semantic, 1,000 searches: 413 wins, 447 losses, p 0.260
hybrid against semantic, 10,000 searches: 4180 wins, 4593 losses, p below 0.001
hybrid with bm25 ties reversed against semantic, 100 searches: 35 wins, 48 losses, p 0.187
hybrid with bm25 ties reversed against semantic, 1,000 searches: 410 wins, 463 losses, p 0.078
hybrid with bm25 ties reversed against semantic, 10,000 searches: 4174 wins, 4560 losses, p below 0.001
hybrid against semantic, verdict at 100 searches changes with bm25 ties reversed: yes

小樣本會大幅擺盪。語意檢索對 BM25 在離線時差距很大,判定結果在 100 次搜尋時為 51 wins, 36 losses, p 0.133,在 1,000 次時為 519 wins, 347 losses, p below 0.001。混合對語意檢索,在 100 次搜尋時為 32 wins, 51 losses, p 0.048,在 1,000 次時為 413 wins, 447 losses, p 0.260,這正是搜尋次數必須在測試開始前就固定的原因。

在 10,000 次搜尋時,混合的判定結果為 4180 wins, 4593 losses, p below 0.001。這並未推翻第 3 章「未能確立差異」的發現:在同樣的 30 個查詢上累積愈來愈多模擬點擊,符號檢定衡量的只是點擊雜訊,因此任何固定的差距都會變得顯著。

混合在 100 次搜尋時的判定結果,還取決於一個不帶任何資訊的細節。混合會融合 BM25,而 lib.lexical 以 product_id 排序 BM25 分數相同的商品。若改以相反方向排序,這是同樣任意的規則,相同的隨機種子在 100 次搜尋時的結果會變成 35 wins, 48 losses, p 0.187。在 0.05 的水準下判定結果是否改變?yes。反轉 BM25 的平手順序會改變混合的部分清單,使模擬購物者看到其他商品,而第一份改變的清單之後的每一次隨機抽取都可能隨之偏移。一個會被平手規則翻轉的判定結果只是運氣,並非關於排序器的發現。

有三項限制使這個流程只是預演。第一,點擊來自 nDCG@10 所用的同一組等級,所以交錯測試往往與 nDCG@10 一致,對排序器並未增添任何證據。第二,每次搜尋都來自同樣的 30 個查詢,因此符號檢定只能代表這些查詢。第三,真實購物者並不等同於這個模型。Deffayet et al. 研究了產生點擊紀錄的排序器改變時會發生什麼事,發現點擊模型對這種改變很敏感(Deffayet et al., 2023)。在三個搜尋引擎的真實流量上,只要兩者皆達顯著,交錯測試便與專家判斷一致,且所需資料「比絕對指標少約 1 至 2 個數量級」(Chapelle et al., 2012)。依我們的推論,模擬無法顯示這項優勢,因為其中的購物者行為全都相同。

實用原則: 以模擬預演交錯測試,用來檢查你的程式碼與符號檢定。對於它所建議的搜尋次數,其可信度不會高於所假設的購物者;在解讀模擬的判定結果之前,先以相反的平手規則重跑一次。切勿把模擬的判定結果當成排序器的證據來報告。面對真實流量時,事先固定搜尋次數,並以符號檢定做出決定。

當離線與線上結果不一致時,找出原因

最近一次變動於第 2026.11.8 版

模擬購物者依照 nDCG@10 所用的相同等級進行點擊,因此傾向與它一致;真實的購物者則不必然如此。離線指標有時能相當準確地預測線上結果。在一項涵蓋 36 種離線指標的電子商務研究中,表現最好的指標在判斷兩個排序模型何者較佳時,以某項商業指標衡量,與線上結果的一致率最高達 97%(Wang et al., 2023)。另一個電子商務團隊則發現,離線排序指標「可能與線上表現出現顯著不一致,甚至可能產生誤導」(Huzhang et al., 2020)。這兩項都是業界以自家流量進行的研究,外部人員無法重現。當兩個系統的表現大致相當時,不同的指標往往彼此不一致(Hofmann et al., 2016)。

不一致是有原因的,而且可以檢查。評審判斷可能漏掉線上勝出者所呈現的商品,這正是敏感度檢查所要找的。變更也可能作用於排序之外,例如速度或版面配置。又或者,線上指標衡量的可能根本不是成功。在一個學術搜尋引擎上,Radlinski et al. (2008)發現,每次查詢的點擊數與另外七項絕對使用量指標一樣,在他們所研究的樣本規模下,無法可靠地反映檢索品質。

商店可以用交錯測試演練中的導航型購物者來模擬 A/B 測試:以 BM25 作為對照組進行 5,000 次搜尋,以語意檢索作為實驗組進行 5,000 次搜尋,全部使用測試查詢。衡量每次搜尋的點擊數,以及點擊到完全符合商品的搜尋所占比例。接著,以表 2 的「完美」使用者,也就是完美購物者,採用相同的對應方式重複一次:他會閱讀全部十筆結果,點擊每一個完全符合的商品,且絕不提早離開。你預期哪一種排序器每次搜尋能獲得較多點擊?每一位購物者的結果會一致嗎?

clicks-per-search-misleads.py Python 3.12.15 · bm25s 0.3.16 · numpy 2.5.5 · pandas 3.1.1 · scipy 1.18.1 通過
"""Clicks per search and the share of searches with an exact click, for BM25 and semantic retrieval run as simulated A/B arms, for the navigational and the perfect shopper. The prose's point rests on the two 'reverses between shoppers' lines, read with the means and p-values printed before them."""import numpy as npfrom scipy import statsfrom lib.experiments import SHOPPERS, simulate_searchesfrom lib.lexical import LexicalSearchfrom lib.semantic import SemanticSearchfrom lib.store import load_products, load_queries, qrelsqueries, judgments = load_queries("test"), qrels("test")arms = {"bm25": LexicalSearch(load_products()).run(queries, k=100),     # control        "semantic": SemanticSearch().run(queries, k=100)}               # treatmentmetrics = {"clicks per search": "clicks", "share of searches with an exact click": "exact_click"}significant_leaders = {label: set() for label in metrics}      # rankers ahead at p below 0.05for shopper_name, shopper in SHOPPERS.items():                         # navigational, then perfect    # one seed per shopper: the two rankers draw from it in turn, bm25 first    rng = np.random.default_rng(2026)    searches = {name: simulate_searches(run, judgments, 5_000, rng, shopper) for name, run in arms.items()}    for label, column in metrics.items():        means = {name: table[column].mean() for name, table in searches.items()}        for name, mean in means.items():            print(f"{shopper_name} shopper, {name} {label}: {mean:.3f}")        # exact_click holds True and False; as floats they are 1 and 0 for the t-test        p = stats.ttest_ind(searches["semantic"][column].astype(float), searches["bm25"][column].astype(float)).pvalue        print(f"{shopper_name} shopper, {label} p: " + (f"{p:.3f}" if p >= 0.001 else "below 0.001"))        if p < 0.05:            significant_leaders[label].add(max(means, key=means.get))for label in metrics:    print(f"{label} reverses between shoppers:", "yes" if len(significant_leaders[label]) > 1 else "no")
輸出python clicks-per-search-misleads.py
navigational shopper, bm25 clicks per search: 1.362
navigational shopper, semantic clicks per search: 1.269
navigational shopper, clicks per search p: below 0.001
navigational shopper, bm25 share of searches with an exact click: 0.695
navigational shopper, semantic share of searches with an exact click: 0.799
navigational shopper, share of searches with an exact click p: below 0.001
perfect shopper, bm25 clicks per search: 6.443
perfect shopper, semantic clicks per search: 7.451
perfect shopper, clicks per search p: below 0.001
perfect shopper, bm25 share of searches with an exact click: 0.898
perfect shopper, semantic share of searches with an exact click: 0.895
perfect shopper, share of searches with an exact click p: 0.646
clicks per search reverses between shoppers: yes
share of searches with an exact click reverses between shoppers: no

每次搜尋的點擊數在不同購物者之間會反轉嗎?yes。它的正負方向取決於購物者的行為,因此單靠它無法衡量成功。導航型購物者在 BM25 上每次搜尋的點擊數為 1.362,在語意檢索上為 1.269,p 值為 below 0.001;而完美購物者在語意檢索上為 7.451,BM25 則為 6.443。找到完全符合商品且排在前段的購物者,會點擊該商品並通常就離開;而看到的是部分符合商品的購物者,則會點擊好幾個,仍在繼續尋找。

點擊到完全符合商品的搜尋比例,在不同購物者之間會反轉嗎?no。對導航型購物者而言,它偏向語意檢索,為 0.799,對比 0.695;對完美購物者而言則沒有明顯差異,p 值為 0.646,因為只要前 10 筆中有完全符合的商品,該購物者就會點擊,BM25 的搜尋中有 0.898 如此,語意檢索的搜尋中則有 0.895。

若每位購物者都得到同一個答案,點擊就能當作品質的衡量。但點擊衡量的是行為,而行為各有不同。

實用原則: 當離線與線上結果不一致時,先找出原因,再決定相信哪一方。確認線上指標衡量的是成功,例如購買,而不是活動量。檢查線上勝出者結果的 judged@10,並對缺少的部分進行評審。然後依據你事先選定的指標之線上結果做出決定,並將查詢或評審判斷加入迴歸測試集,讓它下次能預測得更準確。

決定是否上線

最近一次變動於第 2026.11.8 版

上線決策結合了離線與線上檢查。請在看到任何結果之前先寫下檢查清單,如此就不會有單一數字說服你做出變更。我們建議以下項目,每一項都附上說明它的節:

  1. 在迴歸測試集上確立的離線增益,依據預先規劃的比較規則,並附上其 t 檢定與區間(逐查詢差異),且以你手上最強的系統作為對照。Armstrong 等人發現,在 TREC 資料集上十多年來發表的增益中,「基準系統通常偏弱,往往低於原始 TREC 系統的中位數」(Armstrong et al., 2009)。
  2. 已閱讀退步的案例,且 α = 1 時的 URisk 不為負(URisk)。
  3. 涵蓋兩個執行結果的判斷: 當任一執行結果中未經判斷的商品被視為完全相符時,領先者仍維持不變;若不然,則需要新的判斷(未經判斷的商品)。
  4. 針對以 LLM 為基礎的排序器,其主要分數需有人工評分(第 4 章)。
  5. 延遲與成本在預算之內(第 9 章)。
  6. 所有設定都是在訓練查詢上選定的,且每一次查看測試查詢都有記錄(保留查詢)。
  7. 預先寫好的線上計畫: 主要指標與護欄指標、由檢定力計算得出的樣本數、A/A 測試、樣本比例檢查,以及不中途偷看結果(A/B 測試)。交錯測試可以先篩選候選系統(團隊輪選)。

以商店改用語意檢索為例,來看前三項。第 1 項要求確立的增益,而排列檢定的回答是yes,平均變化為0.105,95% 區間為0.055 to 0.185。第 2 項,α = 1 時的 URisk,為0.092。

第 3 項,涵蓋兩個執行結果的判斷:若 BM25 未經判斷的商品全部都完全相符,BM25 的分數會是0.788,語意檢索則是0.829。領先者會改變嗎?no。線上項目則要等待流量。

實用原則: 當所有離線項目都通過,且事先決定樣本數的線上測試在主要指標上顯示顯著增益、同時沒有任何護欄指標變差時,才上線。當某個離線項目未通過,請先修正再上線,因為線上測試會耗用購物者的時間。當線上測試在預定樣本數下仍無定論時,請保留基準系統。

正式環境中會出什麼問題

最近一次變動於第 2026.11.8 版

商店在真實流量上一個接一個地測試變更,使用的是真實的購物者,而非模擬的購物者,且每一步都使用同一組迴歸測試集。

儀表板會誘使人提前查看結果。 實驗平台每天都會顯示結果,而團隊只要在結果第一次看似顯著時就停止實驗,偽陽性率就會遠高於 5%,如 A/A 模擬所示。請事先固定樣本數,或改用序貫方法。

各組的分配與計畫不符。 Fabijan 等人將數家公司出現樣本比例失衡(sample ratio mismatch)的原因,整理成一套分類。在解讀任何結果之前,先檢查分流是否正確;在弄清楚分流為何出現偏差之前,不要相信該結果。

迴歸測試集會被用到失效。 每一次根據測試查詢做出的決定,都會消耗它們的一部分獨立性(Dwork 等人,2015)。請記錄每一次查看,並在記錄變長時,以新的查詢與判斷來更新測試集。

LLM 評審成為把關者。 LLM 的判斷成本低到足以為每個候選方案評分。Otero 等人發現,對 LLM 判斷進行顯著性檢定時,出現了「在統計差異方面極高的偽陽性率」(Otero 等人,2025)。在依據 LLM 評審得出的提升而上線之前,請先以人工判斷加以確認(第 4 章)。

同分會改變結果。 分數相同的商品,會依函式庫的選取方式留下的順序回傳(第 3 章),因此即使變更不涉及任何分數,結果仍可能改變。將 BM25 的同分順序反轉,會改變商店的 100 次搜尋交錯測試結論嗎?yes。請在每個排序器中以 ID 打破同分,並在採取行動之前,將接近門檻的結果在同分順序反轉的情況下重新執行。

交錯測試看不到整個頁面。 我們認為,速度較慢或改變結果數量的排序器,可能在交錯測試中獲勝,卻仍然流失購物者。此類變更請進行 A/B 測試。

實用原則: 在實驗平台中將 A/A 測試、樣本比例檢查與固定的測試樣本數自動化,記錄每一次對測試查詢的查看,以 ID 打破同分,並以人工判斷確認 LLM 評審得出的提升。

本章做出的決定

最近一次變動於第 2026.11.8 版

每項預設值的理由,都在其連結所指的節中。

  • **迴歸測試集是附有相關性判斷的 30 筆測試查詢,**所有選擇都使用 50 筆訓練查詢(保留查詢)。
  • **在測試查詢上只做一次事先規劃的比較,**即語意檢索對 BM25,只有當排列檢定的 p 值低於 0.05 時才算成立,並在旁附上 t 檢定與 95% 信賴區間(逐查詢差異)。128 維排序器屬於探索性質,是依其在測試集上的表現挑選出來的(URisk)。
  • **每個候選方案都要做逐查詢差異分析,**並以人工逐一檢視其退步的案例。
  • **URisk 使用 α = 1,**因此每一次退步都算作兩倍。這是對退步代價有多大的判斷;失敗代價高昂的商店應該調高此值(URisk)。
  • **當領先者在兩種未經判斷的情境之間改變時,先做判斷再比較,**並將新的判斷保留在迴歸測試集中(未判斷的商品)。
  • **每做一次決定,測試查詢只看一次,**而且每次查看都要記錄下來(保留查詢)。
  • **A/B 測試在開始前先以 16σ²/Δ² 決定樣本規模,**只在達到該規模時讀取一次結果,並且事先做 A/A 測試與樣本比例檢查(檢定力)。
  • 交錯測試使用團隊輪選(team draft)與符號檢定(團隊輪選)。
  • **模擬購物者遵循對應到三個等級的導覽式級聯模型,**查詢頻率一律均等,各項機率在 lib.experiments 中明列為假設,且每次模擬都使用固定的隨機種子。其結果只用來演練方法,絕不視為證據(演練)。
  • **每次搜尋的點擊數本身不是成功指標。**請使用成功的衡量方式,例如購買(離線與線上)。
  • **本章的啟示:**先決定什麼會改變你的看法,再去看資料,而且只看一次。

本章,於本版次中

版次 2026.11.10範例於 2026年11 月 19 通過測試本章 11 個範例 個範例中有 11 個通過

譯自英文書,版次 2026.11.10。

引用本節

格式

各種格式皆引用英文原書,本譯本即依循該原書。

每種格式都會標示本版。其連結會開啟目前版次,節標題會說明該節內文最後一次變動的時間。存取日期與擷取日期即為你開啟此頁的當日。

本頁內容

第 11 章,共 11 章: 測試變更

  1. 逐一查詢比較兩次執行結果
  2. 以 URisk 讓損失的權重高於獲益
  3. 評判新排序器浮現的商品
  4. Keep the test queries out of every choice
  5. 執行 A/B 測試
  6. 以檢定力決定測試規模
  7. 以 team draft 交錯兩種排名
  8. 以模擬購物者預演交錯測試
  9. 當離線與線上結果不一致時,找出原因
  10. 決定是否上線
  11. 正式環境中會出什麼問題
  12. 本章做出的決定

返回頂端所有章節