変更のテスト

読了まで約61 分分、12 節 節の 11 例 例。

第2026.11.10版 2026年11月19日時点で例が通過 132 例中 132 例が合格 変更点

AIによる翻訳。英語版は人による検証済みである。 当社の書籍の作り方

英語版の書籍(版2026.11.10)から翻訳した。 原文を読む

この章を読み終えると、検索への変更を本番に出すべきかどうかを判断できるようになる。2つのランカーの結果をクエリごとに比較し、テストクエリが変更を実際以上によく見せないようにし、A/Bテストの規模を見積もり、結果をインターリーブして2つのランカーを比較する。

この本が追うストアは、家具とホームグッズのオンライン小売業者である(第1章)。検索ボックスでは、いまも基準として BM25 が動いている。前の章までのオフライン作業により、セマンティック検索は BM25 に対する優位を確立した(第3章)。BM25 からの切り替えは1つの変更であり、その後に続くあらゆる調整もそれぞれ1つの変更である。より安価な埋め込み、ブレンドの重み、リランカーがその例である。どの変更も、同じ4つの問いを生む。平均はノイズを超えて上がったか。どのクエリが悪化したか。判定データは新しい結果をそもそも採点できるか。買い物客は判定データが予測するとおりに行動するか。この章ではこの順に答えていく。ストアの 30 件のテストクエリは回帰セットとなる。回帰セットとは、あらゆる変更をテストする際に用いる固定のクエリである。あらゆる選択は 50 件の訓練クエリに基づいて行う。ストアには click ログがないため、オンラインに関する節では買い物客をシミュレートし、各シミュレーションの前提をその横に明記する。

この章では、テストクエリに対する比較を1つだけ計画する。セマンティック検索と BM25 の比較である。第3章に従い、計画した比較が1つだけの場合は、この本全体の 0.05 をそのまま使う。したがって、ここでは p 値が 0.05 を下回ったときに、差が確立したと言える。この章でテストクエリに対して算出するそれ以外のスコアは、すべて探索的なものである。

2つのランを問い合わせごとに比較する

最終変更:版2026.11.10

最初の2つの問い、すなわち平均が上がったかどうか、そしてどの問い合わせが悪化したかは、回帰セットで答える。回帰セットとは、判定付きの固定された問い合わせの集まりであり、あらゆる変更は出荷前にこれに対して実行される。ストアが現在動かしているランカーがベースラインであり、変更を加えたランカーが候補ランカーである。それぞれがセット内の全問い合わせに対する順位付けであるランを生成する。ランの平均どうしを比べるだけでは不十分である。変更によって平均が上がっても、一部の問い合わせが悪化することがあるからだ。検索システムの共有評価であるTREC(Text REtrieval Conference)は、2013年のWeb trackでこのリスクを課題に据え、各システムの勝ちと負けをベースラインとの比較で問い合わせごとに採点した(Collins-Thompson et al., 2014)。そこで2つのランの差分を取る。問い合わせごとに1行とし、ベースラインのスコア、候補のスコア、その変化を並べる。そのうえで勝ち、負け、引き分けを数え、負けを読む。

ベースラインは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に対して、並べ替え検定のp値は0.001である。この変化は確立されたといえるか。yes。これと並べると、対応のあるt検定のp値は0.003であり、95%区間は0.055 to 0.185である。

学びが得られるのは負けの部分である。セマンティック検索は21件の問い合わせで勝ち、7件で負け、2件で引き分け、最大の負けは-0.092である。負けのうち2件はインチ単位の寸法を含み、48 inch kitchen hoodと48" sliding single track , barn door for laundryである。ただしこれは2件の問い合わせにすぎず、パターンとはいえない。第6章では、数字を含むすべての問い合わせについてこのパターンを検証する。

実践ルール: 何の調整にも使わない判定付き問い合わせの回帰セットを保持し、すべての候補をそのセットでベースラインと比べる。計画した比較を先に列挙し、それぞれを並べ替え検定のp値、t検定、区間とともに報告する。勝ち、負け、引き分けを数え、出荷前にすべての負けを読む。負けに共通のパターンがありそうなときは、対処する前に訓練用の問い合わせで確かめ、そのうえでその種の問い合わせを修正するか、ベースラインに回す。

URiskで勝ちよりも負けを重く扱う

最終変更:版2026.11.8

クエリごとの差分は負けの数を数えるが、平均変化は依然として、0.1悪化したクエリと0.1改善したクエリを互いに相殺するものとして扱う。ストアの側ではそうは考えないかもしれない。昨日は商品を見つけられた買い物客が今日は見つけられなくなれば、それは退行に遭遇したということであり、他の場所で順位が少し良くなっても埋め合わせにはならない。リスク感応型の評価は、負けを勝ちよりも重く数える。

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 ]

このトラックは、これを「損失を成功のα + 1倍の重みで扱う」ものと説明しており、α = 0では単純な平均変化になる(Collins-Thompsonら、4.3節)。トラックの概要では損失項にΔ(q)そのものが使われているが、悪化したクエリではこれは負の値になる。ここでは大きさ|Δ(q)|を用いる。概要が述べるとおりα = 0で平均になるのは、この読み方だけだからである。αは事実ではなく選択である。ここではα = 1を用い、負けを1件につき2倍に数える。

BM25に対して2つの候補を比較する。1つ目は完全なセマンティック検索で、Snowflake/snowflake-arctic-embed-m-v1.5による各埋め込みの768個の数値をすべて使う。2つ目は先頭の128個の数値だけを残すもので、メモリは6分の1になる。これはモデルカードに記載されている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なので、2倍にしてもコストはほとんど増えない。

より安価なランカーの平均変化は0.017だが、負けを2倍に数えるとURiskは-0.033になる。勝ちは15クエリ、負けは13クエリで、最大の負けは-0.253である。平均はこのトレードオフを隠している。あるクエリでは結果が良くなり、その代償として別のクエリでは結果が悪くなっている。

その並べ替え検定は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ら、2014)。

実践ルール: すべての候補について、平均変化と並べてα = 1でのURiskを報告する。平均がどうであれ、URiskが負の候補は出荷せず、その負けを読んで原因を調べる。失敗のコストが大きいときはαを上げ、ストアで最も頻度の高いクエリについてはURiskを別に報告する。あるクエリでの負けが別のクエリでの勝ちより悪くないと言える場合にのみ、α = 0を用いる。

新しいランカーが表示する商品を判定する

最終変更:版2026.11.10

新しいランカーの敗北は、URiskの例における安価なランカーの敗北のように、判定の欠落に由来する場合がある。判定は、以前のシステムが見つけた商品だけを対象としているからである。この店舗の判定の出典であるWANDSは、以前のシステムが見つけたものだけを判定した(第2章)。それらと異なるランカーは、誰も判定していない商品を表示する。指標はそうした商品のそれぞれにグレード0を与えるため、そのスコアは低すぎるかもしれず、あるいは正しいのかもしれない。誰かが判定するまでは、どちらであるかを見分けることはできない。WANDSの著者らは、このような欠落が評価を弱めると警告している。「Product Searchデータセットの不完全性は、評価の識別力に悪影響を及ぼす」(Chen et al., 2022)。

第2章では、judged@10によって未判定の商品を数えた。変更を検証する際には、さらにもう一つの手順が役に立つ。感度チェックである。これは、双方に有利な二つのシナリオの下で、両方の実行結果を再採点するものである。一方のシナリオでは、ベースラインの上位10件に含まれる未判定の商品がすべて exact であるとする。もう一方では、候補の上位10件に含まれる未判定の商品がすべて exact であるとする。各シナリオでは、両方の実行結果を同じ判定で採点する。nDCGの理想的なランキングは、そのクエリに対するすべての判定から作られるためである。exact と判定された商品があれば理想値が上がり、その商品を表示しないすべての実行結果のスコアが下がる。これらのシナリオは上下限ではない。真の判定は二つのシナリオを混ぜたものになりうるからである。二つのシナリオの間で首位が入れ替わるなら、判定だけではまだ決着がつかない。

URiskの例の安価なセマンティック検索は、各埋め込みの768個の数値のうち128個を保持するもので、店舗のテストクエリのうち13件でBM25に負けた。これらの敗北に何らかの意味を読み取る前に、チェックを実行する。

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の未判定の商品が exact であれば、BM25が0.788対0.738で優位に立つ。安価なランカーの未判定の商品が exact であれば、安価なランカーが0.807対0.718で優位に立つ。

BM25の上位10件には未判定のペアが22件あり、安価なランカーの上位10件には24件ある。比較は46件の判定を待っている。誤ったランカーを出荷するコストに比べれば、小さな出費である。

判定者が何と言うかを推測してはならない。古いTREC コレクションで、Voorhees らはニューラルとBM25の実行結果から文書の新しいプールを判定し、新たに判定された文書の大半が関連していなかったことを見いだした(Voorhees et al., 2022)。しかし、そのコレクションは多くのシステムから深くプールされたものであり、WANDSは異なる方法で構築された。人間による判定が基準である。大規模言語モデル(LLM)による判定はより安価である。第4章では、診断として、店舗の未判定のペアをLLMの判定で埋める。補完されたグレードが判定結果や二つのランカーの順序を変えるたびに、人間がそのペアを判定する。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)。現行のシステムをコントロール、変更後のシステムをトリートメントと呼ぶ。

結果を信頼できるものにするために、三つの確認が必要である。第一に、両方のグループに同じシステムを与えるA/Aテストは、信頼水準95%において、帰無仮説を約5%の頻度で棄却するはずである(Kohavi et al., 2009)。5%を大きく上回る場合は、セットアップに不備があることを示す。第二に、結果は計画したサイズに達した時点で一度だけ読む。有意に見えた瞬間にテストを止めること、すなわちピーキングは、第一種の過誤の率を大幅に押し上げる(Kohavi et al., 2022)。第三に、各グループが計画どおりの大きさになったかを確認する。サンプル比のずれ(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テストをシミュレートする。各グループで1日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値を用いる(Johari et al., 2015)。

検出力でテストの規模を決める

最終変更:版2026.11.8

A/Bテストを計画した規模で一度だけ読むということは、まずその規模を、テストの検出力から計画しておくということである。検出力とは、ある大きさの実際の変化を検出できる確率である。検出力が低いテストは実際の変化を見逃す。そして有意という結果が出た場合でも、効果を誇張しやすい。「検出力が低いにもかかわらず統計的に有意となった知見は、効果の大きさを大きく誇張している可能性が高い」(Kohavi et al., 2022)。したがって、テストの開始前に規模を決めておく。決める根拠は二つの数値、すなわち指標がユーザー間でどれだけ変動するかと、検出する価値のある最小の変化である。分散が大きいほど多くのユーザーが必要になる。変化が小さいほど、必要なユーザーははるかに多くなる。変化は二乗の形で式に入るからである。

2群、信頼度95%、検出力80%の場合について、Kohaviらは経験則を示している。σ²は指標の分散、Δは検出したい変化である(Kohavi et al., 2009)。

users per group ≈ 16 × σ² / Δ²

16という値は正規分布から得られる。2 × (97.5%点のz + 80%点のz)²、約2 × (1.96 + 0.84)²である(16に近い値となる)。検出力を90%にする場合は、16を21に置き換える。SciPyでこの係数を計算し、コードでこの経験則をKohaviらの二つの計算例で確かめる。一つは平均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

変化を半分にすると、必要なユーザー数は4倍になる。ストアのコンバージョン率を5%と仮定した場合、2%の変化の検出には1群あたり760,000人、1%の変化の検出には3,040,000人が必要である。

係数は15.7であり、収益の例とコンバージョンの例で必要な1群あたりのユーザー数は409,600人と121,600人となる。これは論文の数値である409,000人超と122,000人未満に一致する。

同じ計算から、回帰テストセットで検出できる変化の大きさもわかる。二つのランカーは同じクエリを採点するので、このテストは2群ではなく、クエリごとの差という一つの標本を扱う。そのため係数は半分になり、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らは、判定にかける労力が同じなら、浅く判定した多数のクエリのほうが、深く判定した少数のクエリよりも統計的検出力が高くなることを見いだしている(Webber et al., 2008)。

実践ルール: あらゆるA/Bテストは、開始前に規模を決める。必要なユーザー数がストアの数週間分のユーザー数を超える場合は、より大きな変化をテストするか、変動の小さい指標を用いるか、テスト前の各ユーザーのデータで指標を調整する。Bingの実験について、Dengらはこの調整が「分散を約50%削減できる」と報告している(Deng et al., 2013)。どれだけ削減できるかは、ユーザーの過去の行動が指標をどれだけうまく予測するかに依存する。オフラインでは、回帰テストセットが検出できる最小の変化を計算し、変更がそれより小さい場合はクエリを追加する。件数は事前に固定する。検出力の推定値が十分だと示すまでクエリを追加し続けると、有意な結果を見つける方向に偏りが生じる(Webberら)。

チームドラフトによる2つのランキングのインターリーブ

最終変更:版2026.11.10

A/Bテストでは各グループに異なるランキングを見せるため、買い物客どうしの違いがノイズとなる。インターリーブは、2つのランカーの結果を混ぜた1つのリストを各買い物客に見せる手法である。Joachimsはこの手法を、「合成されたランキングが両方の検索エンジンにほぼ等しい提示バイアスを与える」ように設計した(Joachims, 2003)。どちらのランカーの商品も、系統的に上位に置かれることはない。商品がより多くのクリックを集めたランカーが、その検索の勝者となる。インターリーブが答えるのはA/Bテストよりも狭い問いであり、2つのランキングのうちユーザーがどちらを好むかであって、どちらかの絶対的な数値ではない(Hofmann et al., 2016)。

チームドラフトは、ゲームでチームを選ぶときのように、2つのランカーのリストをインターリーブする(Radlinski et al., 2008、Algorithm 2)。指名数の少ないチームが次に指名し、両チームの指名数が同じときはコイントスで決める。各指名では、そのチームの順位で、まだ表示されていない商品のうち最も高いものを選ぶ。クリックは、その商品を指名したチームに加算される。Radlinskiらは、チームドラフトでは「無作為にクリックするユーザーは、期待値としてAに対してもBに対しても同数の選好を必ず生む」ことを示している。これは従来の手法では保証されなかった性質である。

テストクエリ clear shower curtain について、ストアのセマンティック検索とBM25をインターリーブする。チームドラフトは、コイントス用のシード付き乱数生成器を使えば数行で書ける。次のコードは、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

チームドラフトでは、10件のリストのうち5件を必ず各ランカーに割り当てる。コイントスが決めるのは、どの位置がどちらに割り当てられるかである。両方のランカーが上位に置いた商品は1回だけ現れ、先に指名したチームに加算されるため、同じ商品でどちらかのランカーが二重に評価されることはない。このクエリでは、BM25が順位付けするシャワーカーテンフックの1つ(第1章)が、BM25の最後の指名として最下位に入る。セマンティック検索の指名した商品へのクリックはセマンティック検索に、BM25の指名した商品へのクリックはBM25に加算され、クリックの多いチームがその検索に勝つ。

実践ルール: どちらのランカーをユーザーが好むかを知りたいときは、A/Bテストより少ない検索回数で比較できるチームドラフト・インターリーブを使う。収益のような絶対的な数値が必要な場合や、変更がランキングに関するものでない場合は、代わりにA/Bテストを使う。我々の考えでは、インターリーブされたリストでは、レイテンシ、ページレイアウト、結果件数の違いによる影響は示せない。

シミュレートした購買者でインターリービングを予行演習する

最終変更:版2026.11.8

このストアのデータの出所である WANDS にはクリックデータがないため、実際の購買者に対してチームドラフト・インターリービングを実施することはできないが、シミュレートした購買者で予行演習をすることはできる。クリックモデルとは、ユーザーが結果リストをどのように走査しクリックするかを表す確率モデルであり、指標の構築とユーザーのシミュレーションの両方に用いられる(Chuklin et al., 2015)。カスケードモデルは、ユーザーが上から順に読み、「価値のある文書を見つけた時点で離脱する」と考える(Craswell et al., 2008。第2章を参照)。標準的なシミュレーションはこのモデルに従う。クエリを一様ランダムに選び、そのリストを上から順にたどり、各商品を評価等級に応じた確率でクリックし、クリックの後は同じく等級に応じた別の確率で離脱する(Oosterhuis and de Rijke, 2018)。インターリービングの研究では、ラベル付きデータからクリックをシミュレートして手法を検証している(Hofmann et al., 2011)。

これらの確率は仮定である。Oosterhuis and de Rijke の Table 2 には、5段階の等級に対する「ナビゲーショナル」なユーザー、すなわち高度に関連する結果を1件だけ探すユーザーが示されている。これをナビゲーショナルな購買者と呼ぶ。ここでは、無関係・部分一致・完全一致を、このユーザーの最低・中間・最高の等級に対応させる。評価のない商品は、指標の場合と同様に無関係として数え、すべてのクエリを同じ頻度で選ぶ。値は1か所、lib.experimentsにまとめてある。

等級 クリック クリック後の離脱
完全一致 0.95 0.9
部分一致 0.5 0.5
無関係 0.05 0.2

このような購買者を1人、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となる。2組それぞれについて、固定したシードで、インターリーブした検索を10,000回シミュレートする。対象はセマンティック検索と BM25、およびハイブリッドの実行結果とセマンティック検索である。符号検定により、勝ちの数が負けの数を偶然以上に上回るかどうかを調べる。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は BM25 のスコアが等しい商品をproduct_idの順に並べる。これを逆順に並べても、同じく恣意的な規則であり、同じシードで100回の時点の判定は35 wins, 48 losses, p 0.187となる。0.05 での判定は変わるだろうか。yes。BM25 の同点を逆順にすると、ハイブリッドのリストの一部が変わるため、シミュレートされた購買者は別の商品を目にし、最初に変わったリスト以降のすべての乱数の引きがずれうる。同点処理の規則で反転しうる判定は、ランカーに関する知見ではなく、運である。

次の3つの限界があるため、これはあくまで予行演習にとどまる。第一に、クリックは nDCG@10 が用いるのと同じ評価等級から生成されるため、インターリービングは nDCG@10 と一致しやすく、ランカーに関する新たな証拠は加わらない。第二に、すべての検索が同じ30件のクエリに由来するため、符号検定はこれらのクエリについてしか語れない。第三に、実際の購買者はこのモデルとは異なる。Deffayet et al. は、クリックログを生成したランカーが変わった場合に何が起こるかを調べ、クリックモデルがその変化に敏感であることを見いだした(Deffayet et al., 2023)。3つの検索エンジンの実トラフィックでは、インターリービングは、両者が有意であるときは常に専門家の判断と一致し、必要なデータ量は「絶対指標より約1〜2桁少ない」ものだった(Chapelle et al., 2012)。ここでの推論によれば、シミュレーションの購買者はみな同じように振る舞うため、この利点をシミュレーションで示すことはできない。

実践ルール: インターリービングのテストは、コードと符号検定を確認するためにシミュレーションで予行演習する。そこから示唆される検索回数は、仮定した購買者の妥当性の範囲でしか信頼できないものとして扱い、シミュレーションの判定は、同点を逆順に処理して再実行してから解釈する。シミュレーションの判定をランカーに関する証拠として報告してはならない。実トラフィックでは、検索回数をあらかじめ固定し、符号検定で判断する。

オフラインとオンラインの結果が食い違うときは原因を探す

最終変更:版2026.11.8

シミュレートされた買い物客は nDCG@10 が用いるのと同じ等級に従ってクリックするため、nDCG@10 と一致しやすい。実際の買い物客はそうとは限らない。オフライン指標がオンラインの結果をうまく予測することもある。あるEコマースの研究では、36 種類のオフライン指標のうち最良のものが、二つのランキングモデルのどちらが優れているかについて、ビジネス指標で見たオンラインの結果と最大 97% の確率で一致した(Wang et al., 2023)。別のEコマースのチームは、オフラインのランキング指標が「オンラインの性能と著しく食い違うことがあり、誤解を招くことすらある」ことを見いだした(Huzhang et al., 2020)。どちらも自社のトラフィックを対象とした業界の研究であり、外部の者が再現することはできない。二つのシステムの性能がほぼ等しいときには、指標どうしが食い違うことが多い(Hofmann et al., 2016)。

食い違いには、確かめられる原因がある。判定がオンラインの勝者の示す商品を取りこぼしている場合があり、感度チェックはこの点を調べる。変更がランキングの外、つまり速度やレイアウトに作用している場合もある。あるいは、オンライン指標が成功とは別のものを測っている場合もある。学術検索エンジンについて、Radlinski et al. (2008)は、クエリあたりのクリック数は、他の七つの絶対的な利用指標と同様に、彼らが調べた標本サイズでは検索品質を確実には反映しないことを見いだした。

ストアは、インターリーブのリハーサルに登場したナビゲーショナルな買い物客を使ってA/Bテストをシミュレートできる。対照群として BM25 で 5,000 回、処理群として意味検索で 5,000 回の検索を行い、すべてテスト用クエリを用いる。検索あたりのクリック数と、完全一致の商品がクリックされた検索の割合を測る。続いて、表2の「完全」ユーザー、すなわち完璧な買い物客を同じ方法で対応づけて繰り返す。この買い物客は 10 件の結果をすべて読み、完全一致の商品をすべてクリックし、途中で離脱しない。検索あたりのクリック数はどちらのランカーが多く獲得すると予想されるか。また、どの買い物客でも同じ結果になるだろうか。

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 コレクション上で10年以上にわたり発表された改善を調べたところ、「ベースラインは概して弱く、元の TREC システムの中央値を下回ることも多い」と報告している(Armstrong et al., 2009)。
  2. 損失を読むこと、そして α = 1 の URisk が負でないこと(URisk)。
  3. 両方の実行をカバーする判定。 どちらの実行の未判定の商品を正解として数えても首位が変わらないこと。変わる場合は新たに判定を取る(未判定の商品)。
  4. LLM ベースのランカーの主要な(見出しとなる)スコアに対する人手の評価(第4章)。
  5. 予算内のレイテンシとコスト(第9章)。
  6. 訓練クエリで選んだすべての設定。 テストクエリを見た回数はすべて記録する(ホールドアウトクエリ)。
  7. 事前に書いたオンラインの計画。 主要指標とガードレール、検出力の計算から求めた規模、A/A テスト、サンプル比のチェック、途中経過を覗かないこと(A/B テスト)。インターリービングで先に候補を絞り込むこともできる(チームドラフト)。

ストアのセマンティック検索への切り替えについて、最初の3項目を確かめる。項目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

ストアは、変更を一つ加えるたびにライブトラフィックで検証する。シミュレートした買い物客の代わりに実際の買い物客を用い、どの段階でも同じ回帰テスト用データセットを使う。

ダッシュボードは途中経過の確認を誘う。 実験プラットフォームは毎日結果を表示する。結果が初めて有意に見えた時点で実験を止めるチームは、A/Aシミュレーションが示すとおり、偽陽性の割合が5%をはるかに上回る。サンプルサイズは事前に固定するか、逐次的な手法を用いる。

グループ分けが計画と一致しない。 Fabijan et al.は、複数の企業から集めたサンプル比のずれ(sample ratio mismatch)の原因を分類体系にまとめた。結果を読む前にグループの分割を確認し、比率がずれている理由が分かるまでは結果を信用しない。

回帰テスト用データセットは使うほど摩耗する。 テストクエリを見て判断を下すたびに、そのクエリの独立性は少しずつ失われる(Dwork et al., 2015)。確認のたびに記録を残し、記録が長くなったら、新しいクエリと判定でテストセットを更新する。

LLM判定者が関門になる。 LLMによる判定は安価であるため、すべての候補にスコアを付けられる。Otero et al.は、LLMの判定に対する有意性検定が「統計的差異に関して極めて高い偽陽性率」を示したと報告している(Otero et al., 2025)。LLMで判定した改善をリリースする前に、人間による判定で確認する(4章)。

同点がランキング結果を動かす。 スコアが等しい商品は、ライブラリの選択処理がたまたま残した順序で返る(3章)。そのため、スコアに一切触れない変更でも結果は動きうる。BM25の同点順を逆にすると、ストアの100回検索のインターリービング判定は変わるのか。yes。すべてのランカーで同点はIDによって解消し、閾値に近い結果は、対応を取る前に同点順を逆にして再実行する。

インターリービングはページ全体を捉えられない。 より遅いランカーや、表示される結果の件数を変えるランカーは、インターリービングのテストに勝っても買い物客を失いかねないと考えられる。このような変更にはA/Bテストを実施する。

実践ルール: A/Aテスト、サンプル比の確認、テストサイズの固定は実験プラットフォームで自動化し、テストクエリを確認した記録をすべて残し、同点はIDで解消し、LLMで判定した改善は人間による判定で確認する。

この章で下した判断

最終変更:版2026.11.8

各既定値の理由は、リンク先の節に書かれている。

  • 回帰セットは、判定付きのテストクエリ30件とする。 すべての選択には訓練クエリ50件を用いる(保留クエリ)。
  • テストクエリでの比較は、意味検索と BM25 の1件に絞る。 順列検定の p 値が0.05を下回ることによってのみ立証され、t 検定と95%区間を併記する(クエリ単位の差分)。128次元のランカーは探索的な位置づけであり、テストでの挙動を見て選んだものである(URisk)。
  • すべての候補についてクエリ単位の差分を求め、その損失を手作業で読む。
  • URisk では α = 1 とするので、損失は2倍に数えられる。 これは回帰がどれだけの損失になるかについての判断であり、失敗の代償が大きい店舗ではこの値を引き上げるべきである(URisk)。
  • 判定のない2つのシナリオの間で首位が入れ替わった場合は、比較の前に判定を行い、 新しい判定を回帰セットに残す(判定のない商品)。
  • テストクエリは判断1回につき1度だけ見て、 見るたびに記録を残す(保留クエリ)。
  • A/B テストは、開始前に 16σ²/Δ² でサイズを決め、 そのサイズに達した時点で1度だけ読み、事前に A/A テストとサンプル比率の検査を行う(検出力)。
  • インターリーブには、チームドラフトと符号検定を用いる(チームドラフト)。
  • 模擬購買者は、3段階の評価に対応づけたナビゲーショナルなカスケードモデルに従う。 クエリ頻度は一様とし、確率は仮定としてlib.experimentsに明記し、どのシミュレーションでも乱数シードを固定する。その結果は手法の予行演習であり、証拠には数えない(予行演習)。
  • 検索1回あたりのクリック数は、それだけでは成功指標にならない。 購入のような成功の尺度を用いる(オフラインとオンライン)。
  • この章が示したこと: 見る前に何があれば考えを改めるのかを決めておき、そのうえで1度だけ見る。

この版における本章

第2026.11.10版2026年11月19日時点で例が通過この章の11 例件のうち11件が合格

英語版の書籍(版2026.11.10)から翻訳した。

この節を引用する

形式

いずれの形式も、本訳書が従う英語版の書籍を出典として示す。

いずれの形式もこの版を明示している。そのリンクは現行版を開き、節の見出しには本文が最後に変更された日付が示される。アクセス日と取得日は、これを開いた日である。

このページの内容

全11章中の第11章: 変更のテスト

  1. 2つのランを問い合わせごとに比較する
  2. URiskで勝ちよりも負けを重く扱う
  3. 新しいランカーが表示する商品を判定する
  4. Keep the test queries out of every choice
  5. A/Bテストを実施する
  6. 検出力でテストの規模を決める
  7. チームドラフトによる2つのランキングのインターリーブ
  8. シミュレートした購買者でインターリービングを予行演習する
  9. オフラインとオンラインの結果が食い違うときは原因を探す
  10. リリースするかどうかを決める
  11. 本番環境で何がうまくいかなくなるか
  12. この章で下した判断

ページの先頭に戻るすべての章