검색 측정하기
읽는 데 약 62분분 걸린다, 13절에 12개 예제이(가) 있음.
AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식
영어판 2026.11.10판을 번역한 것이다. 원문 읽기
이 페이지의 내용
- Count the relevant products in the top k
- Score the first relevant result with reciprocal rank
- 할인된 이득으로 nDCG 만들기
- scikit-learn의
ndcg_score와 맞춰 보기 - 비교하기 전에 지표를 선택한다
- Read per-query differences, not only the mean
- 순열 검정으로 격차를 검정하라
- 쌍체 t-검정으로 p-값 구하기
- Report how big the gap is
- 무엇을 확립된 결과로 볼지 미리 정한다
- Compare runs in an evaluation harness
- 운영 환경에서 문제가 되는 것
- 이 장이 내린 결정
이 장을 마치면 표준 순위 지표를 처음부터 직접 계산하고, scikit-learn으로 그 결과를 검증하고, 순위 모델을 비교하기 전에 지표 하나를 고르고, 테스트 질의에서 두 순위 모델 사이의 차이가 확립된 것인지 우연일 수 있는지 판단할 수 있다.
1장은 하나의 순서로 끝났고, 이겨야 할 순위 모델은 의미 기반 검색이었다. 상점의 테스트 질의, 즉 어떤 순위 모델도 튜닝에 사용하지 않은 검색에서 BM25의 nDCG@10은 0.725, 의미 기반 검색은 0.830, 하이브리드는 0.812, 재순위화한 하이브리드는 0.798이다. 이 순서를 신뢰하기 전에 두 가지 질문에 답해야 한다. 지표는 구매자에게 중요한 것을 측정하는가, 그리고 올바르게 계산되었는가? 또한 그 차이는 실제인가, 아니면 30개의 질의에서 우연히 생길 수도 있는가? 이 장은 두 질문에 모두 답하고, 이 책이 정한 확립된 차이의 규칙과 그 규칙을 적용하는 하네스로 끝난다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Count the relevant products in the top k
Most ranking metrics start from one question: how many of the results a shopper sees are relevant? Precision at k, written precision@k, is the share of the top k results that are relevant. Recall at k, recall@k, is the share of all relevant products that appear in the top k. Manning and colleagues describe precision as the share of retrieved documents that are relevant and recall as the share of relevant documents that are retrieved, and they note that raising one usually costs the other (Manning et al., 2008, section 8.3). Both need a yes-or-no idea of relevant. In this book a product is relevant to a query when its judgment is exact, grade 2. A product nobody judged for the query counts as not relevant.
BM25's top 10 for the store's test query clear shower curtain mixes clear curtains, curtains that aren't clear, and shower curtain hooks. How many of those ten are exact, and what is the most any test query could score? The example answers both by hand and checks the count against lib.metrics:
1"""Counts the exact products in BM25's top 10 for one query, computes precision and recall by hand, and checks them against lib.metrics, then finds the best score each test query could reach. The prose's point rests on the "exact in the top 10" and "exact products judged" lines, and on the ceiling lines after the blank line."""2import pandas as pd34from lib.lexical import LexicalSearch5from lib.metrics import precision_at_k, recall_at_k6from lib.store import load_products, load_queries, qrels78queries, judgments = load_queries("test"), qrels("test")9ranking = list(LexicalSearch(load_products()).search(queries.at[246, "query"], k=10).index) # clear shower curtain10# grade 2 is exact; a product the judges never graded is absent from this dict, so it is not exact11exact = {product_id for product_id, grade in judgments[246].items() if grade == 2}1213found = sum(product_id in exact for product_id in ranking[:10])14print("exact in the top 10:", found)15print("exact products judged:", len(exact))16print(f"precision@10 by hand: {found / 10:.3f}")17print(f"recall@10 by hand: {found / len(exact):.3f}")18print(f"precision@10 from lib.metrics: {precision_at_k(ranking, judgments[246], 10):.3f}")19print(f"recall@10 from lib.metrics: {recall_at_k(ranking, judgments[246], 10):.3f}")2021# the best any ranking can do: a top 10 that holds as many exact products as the query has22exact_counts = pd.Series({query_id: sum(grade == 2 for grade in per_query.values())23 for query_id, per_query in judgments.items()})24# a top 10 can hold at most 10 exact products, and no more than the query has25best_precision = exact_counts.clip(upper=10) / 1026# only 10 results are shown, so at most 10 of a query's exact products can be retrieved27best_recall = exact_counts.clip(upper=10) / exact_counts28print()29print("queries where precision@10 can't reach 1:", (best_precision < 1).sum())30print("fewest exact products for a query:", exact_counts.min())31print("queries with that few:", (exact_counts == exact_counts.min()).sum())32print(f"best precision@10 for those queries: {best_precision.min():.3f}")33print("queries where recall@10 can't reach 1:", (best_recall < 1).sum())34most = exact_counts.idxmax()35print("query with the most exact products:", queries.at[most, "query"])36print("its exact products:", exact_counts[most])37print(f"its best recall@10: {best_recall[most]:.3f}")
python precision-recall-by-hand.pyexact in the top 10: 4
exact products judged: 12
precision@10 by hand: 0.400
recall@10 by hand: 0.333
precision@10 from lib.metrics: 0.400
recall@10 from lib.metrics: 0.333
queries where precision@10 can't reach 1: 7
fewest exact products for a query: 4
queries with that few: 4
best precision@10 for those queries: 0.400
queries where recall@10 can't reach 1: 22
query with the most exact products: outdoor light fixtures
its exact products: 170
its best recall@10: 0.059
lib.metrics agrees with the hand count. Of the top 10, 4 are exact, so precision@10 is 0.400. Against the 12 exact products the judges marked for this query, recall@10 is 0.333. precision_at_k and recall_at_k give the same two values.
Neither metric has one ceiling for every query. A query with fewer than 10 exact products can't fill its top 10 with them, so precision@10 can't reach 1. 7 test queries are like that, and the 4 with only 4 exact products can reach a precision@10 of 0.400 at best.
A query with more than 10 exact products can't reach full recall in 10 results. That holds for 22 of the test queries. The query with the most, outdoor light fixtures, has 170 exact products, so its recall@10 tops out at 0.059. A mean over the test queries mixes queries that can score 1 with queries that can't.
Recall has a second problem, because its denominator counts only the exact products the judges found. WANDS judged candidates gathered for each query, not the whole catalog (chapter 1), so some exact products were never judged. Zobel found that judgments gathered this way overestimate recall (Know where the judgments came from).
Working rule: Use precision@10 when you care how much of the first page is right, and read it next to each query's ceiling. Don't make recall@10 a headline in product search, where a query can have more than a hundred relevant products, as outdoor light fixtures has. We recommend recall at a deep cutoff, such as the top 100, for one job only: checking that retrieval passes enough relevant products to a reranker. Even then, read it as an overestimate.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Score the first relevant result with reciprocal rank
Precision counts a whole page, but some shoppers want one product: a replacement part, or a model they already know. For them, what matters is how far down the first good result sits. Reciprocal rank (RR) scores a query as 1 divided by the position of the first relevant result, or 0 if there is none, and the mean of RR over queries is the mean reciprocal rank (MRR). TREC, the Text REtrieval Conference, runs shared evaluations of search systems. MRR was the official measure of its question-answering track at TREC-8, where each question scored the reciprocal of the rank of the first correct answer, or 0 when none of the five answers was correct. The track chose it partly because it stays between 0 and 1 and averages well (Voorhees, 1999).
Averaging RR is disputed. Fuhr points out that under RR "the difference between ranks 1 and 2 is the same as that between ranks 2 and ∞", so RR isn't an interval scale, one on which equal steps mean equal differences, and he argues that its mean shouldn't be computed (Fuhr, 2017, section 2.1). Sakai sees no reason to forbid it (Sakai, 2020). Moffat argues that such metrics are more meaningful in their current form than in the intervalized versions proposed for them (Moffat, 2022). We use MRR with that caveat: it is a coarse summary.
RR depends on where you draw the line for relevant, so score BM25's ranking for clear shower curtain twice: once counting only exact products, once counting partial ones too. Then compute MRR for BM25 and semantic retrieval over the test queries:
1"""Writes reciprocal rank by hand for one query under two grade thresholds, then computes MRR for BM25 and semantic retrieval and checks it against lib.metrics. The prose's point rests on the two rr lines for clear shower curtain and the two MRR lines."""2import pandas as pd34from lib.lexical import LexicalSearch5from lib.metrics import evaluate6from lib.semantic import SemanticSearch7from lib.store import load_products, load_queries, qrels8910# relevant=2 counts only exact products; relevant=1 counts partial ones too11def reciprocal_rank(ranking, judgments, relevant=2):12 """1 / the position of the first relevant product, or 0 if the ranking has none."""13 # positions count from 1, as a shopper counts results14 for position, product_id in enumerate(ranking, start=1):15 # a product nobody judged has grade 0, so it never counts as relevant16 if judgments.get(product_id, 0) >= relevant:17 return 1 / position18 return 0.0192021queries, judgments = load_queries("test"), qrels("test")22# each run goes 100 products deep, so RR can look past the top 10 for the first exact product23runs = {"bm25": LexicalSearch(load_products()).run(queries, k=100), "semantic": SemanticSearch().run(queries, k=100)}2425ranking = runs["bm25"][246] # clear shower curtain26print(f"rr, exact counts as relevant: {reciprocal_rank(ranking, judgments[246]):.3f}")27print(f"rr, partial or better counts: {reciprocal_rank(ranking, judgments[246], relevant=1):.3f}")2829for name, run in runs.items():30 rr = pd.Series({query_id: reciprocal_rank(run[query_id], judgments[query_id]) for query_id in judgments})31 print(f"{name} mrr: {rr.mean():.3f}")32 print(f"{name} mrr from lib.metrics: {evaluate(run, judgments)['rr'].mean():.3f}")33 print(f"{name} queries with rr of 1:", (rr == 1).sum())
python reciprocal-rank-by-hand.pyrr, exact counts as relevant: 0.500
rr, partial or better counts: 1.000
bm25 mrr: 0.650
bm25 mrr from lib.metrics: 0.650
bm25 queries with rr of 1: 16
semantic mrr: 0.787
semantic mrr from lib.metrics: 0.787
semantic queries with rr of 1: 22
The grade threshold changes RR for this one query. BM25's first result for clear shower curtain is a partial match and its second is exact, so RR is 0.500 when only exact products count, and 1.000 when partial ones count too. Whenever you quote RR, say which grades count. The mean over the test queries matches the rr column of lib.metrics.evaluate: BM25 scores 0.650 and semantic retrieval 0.787. That column looks for the first exact product anywhere in the run, not only in the top 10.
RR has a blind spot. It is 1 for 22 test queries under semantic retrieval and for 16 under BM25, and on those queries it sees nothing below the first result. A ranker that puts one exact product first and nine irrelevant ones after it scores the same as a perfect top 10.
Working rule: Report MRR as the headline only when shoppers need one right product, as for a model number or a named product such as kohler whitehaven farmhouse kitchen sink. For queries where shoppers browse a page of options, such as wooden chair outdoor, use nDCG@10 as the headline and report MRR beside it.
할인된 이득으로 nDCG 만들기
정밀도나 RR과 달리, 1장에서 하나의 순위를 채점하는 데 쓴 nDCG@10은 등급을 읽는다. 각 결과는 자신의 등급을 이득으로 기여하며, 이 이득은 위치가 내려갈수록 커지는 할인으로 줄어든다. 이렇게 더한 합이 할인 누적 이득(discounted cumulative gain, DCG)이다. 정규화 DCG(nDCG)는 어떤 순위의 DCG를 이상적인 순위의 DCG로 나눈 값이다. 이 중 두 부분은 여러 버전이 있으며, 버전에 따라 값이 달라진다. 첫째는 이상적인 순위다. DCG를 처음 제안한 Järvelin과 Kekäläinen은 이상적인 순위를 "어떤 IR 기법의 결과가 아니라 검색 주제의 재현율 기반"에 둔다(Järvelin and Kekäläinen, 2002). 실제로는 랭커가 반환한 상품만이 아니라, 그 질의에 대해 판정된 모든 상품의 최선의 순서를 뜻한다. 둘째는 할인이다. 이들은 문서의 점수를 그 순위의 로그로 나누는 방식을 제안했는데, 버전마다 어떤 로그를 쓰는지, 그리고 어느 순위부터 적용하는지가 다르다.
lib.metrics의 공식은 다음과 같다. 여기서 grade(i)는 위치 i에 있는 상품의 등급이다.
DCG@k = sum over positions i from 1 to k of grade(i) / log2(i + 1)
nDCG@k = DCG@k / DCG@k of the ideal ranking
이것이 쓰이는 유일한 버전은 아니다. Järvelin과 Kekäläinen은 로그의 밑보다 낮은 순위에는 할인을 적용하지 않았으므로, 밑이 2이면 처음 두 위치는 온전히 반영된다. Burges 등은 2^grade − 1이라는 지수 이득과 log(1 + rank) 할인을 사용했다(Burges et al., 2005). 평가 도구도 서로 다르다. ir-measures 문서는 pytrec_eval과 gdeval에 대해 서로 다른 nDCG 옵션을 나열한다(ir-measures). 따라서 nDCG를 인용할 때는 항상 어떤 변형인지 밝혀야 한다.
DCG와 nDCG를 처음부터 직접 작성하고, 1장의 BM25, 시맨틱, 하이브리드 실행 결과에 대해 lib.metrics와 비교해 검증한다. 그중 한 점수는 너무 좋아서 믿기 어려워 보인다.
1"""Writes DCG and nDCG from scratch and checks them against lib.metrics on every test query of three runs, then prints one query's grades beside its best possible grades. The prose's point rests on the largest-difference line and on the ndcg@10 line for luau string lights, read with the grade lines above it."""2import math34from lib.fusion import reciprocal_rank_fusion5from lib.lexical import LexicalSearch6from lib.metrics import ndcg_at_k7from lib.semantic import SemanticSearch8from lib.store import load_products, load_queries, qrels91011def dcg(grades, k):12 """Each grade divided by log2 of its position plus one, added up over the top k."""13 # positions count from 1, so the first result is divided by log2(2)14 return sum(grade / math.log2(position + 1) for position, grade in enumerate(grades[:k], start=1))151617def ndcg(ranking, judgments, k=10):18 """DCG of the ranking over DCG of the best order of every judged product (unjudged counts as 0)."""19 # the ideal ranking: every judged product, best grade first20 ideal = dcg(sorted(judgments.values(), reverse=True), k)21 # a product nobody judged counts as grade 0 in the ranking22 return dcg([judgments.get(product_id, 0) for product_id in ranking], k) / ideal232425queries, judgments = load_queries("test"), qrels("test")26bm25 = LexicalSearch(load_products()).run(queries, k=100)27semantic = SemanticSearch().run(queries, k=100)28runs = {"bm25": bm25, "semantic": semantic, "hybrid": reciprocal_rank_fusion([bm25, semantic])}2930gaps = [abs(ndcg(run[query_id], judgments[query_id]) - ndcg_at_k(run[query_id], judgments[query_id], 10))31 for run in runs.values() for query_id in judgments]32print("rankings checked:", len(gaps))33print(f"largest difference from lib.metrics: {max(gaps):.3f}")3435ranking, per_query = bm25[461], judgments[461] # luau string lights36print()37print("query:", queries.at[461, "query"])38print("grades in the top 10:", [per_query.get(product_id, 0) for product_id in ranking[:10]])39print("best possible grades:", sorted(per_query.values(), reverse=True)[:10])40print("exact products judged:", sum(grade == 2 for grade in per_query.values()))41print("exact in the top 10:", sum(per_query.get(product_id, 0) == 2 for product_id in ranking[:10]))42print(f"ndcg@10: {ndcg(ranking, per_query):.3f}")
python ndcg-from-scratch.pyrankings checked: 90
largest difference from lib.metrics: 0.000
query: luau string lights
grades in the top 10: [2, 2, 2, 2, 1, 1, 1, 1, 1, 1]
best possible grades: [2, 2, 2, 2, 1, 1, 1, 1, 1, 1]
exact products judged: 4
exact in the top 10: 4
ndcg@10: 1.000
90개의 모든 순위에서, 직접 작성한 버전은 lib.metrics와 0.000보다 큰 차이를 보이지 않는다.
luau string lights의 경우 BM25의 상위 10개에는 정확한 상품이 4개 있으며 점수는 1.000이다. 이것은 오류가 아니다. 이 질의에는 정확한 상품이 4개만 판정되어 있으므로, 가능한 최선의 상위 10개는 그 상품들을 담은 다음 부분 일치 상품들로 채워지며, BM25는 그 순서를 찾아냈다. nDCG@10이 1이라는 것은 "판정된 상품의 최선의 순서만큼 좋다"는 뜻이지, "정확한 상품이 열 개"라는 뜻이 아니다.
작업 규칙: 컷오프 10에서 선형 이득과 log2(i + 1) 형태를 사용하고, 이상적인 순위는 판정된 모든 상품으로 만들며, 수치를 인용할 때마다 그 변형을 밝힌다. nDCG는 같은 판정으로 채점한 실행 결과끼리만 비교한다. 판정이 새로 바뀌면 이상적인 순위가 바뀌고, 그에 따라 모든 점수도 바뀐다.
scikit-learn의 ndcg_score와 맞춰 보기
지표를 독립적으로 계산하는 라이브러리와 대조하여 검증한다. scikit-learn 1.9.1에서 ndcg_score는 lib.metrics와 같은 변형을 사용한다. 등급이 곧 이득(gain)이고, 각 이득을 log2(순위 + 1)로 나누며, 정규화에 쓰는 DCG는 같은 등급을 최선의 순서로 정렬해 k에서 자른 것이다(scikit-learn 소스). 문서는 Järvelin과 Kekäläinen을 인용하지만, 코드는 이후에 나온 순위 + 1 형태를 구현한다(scikit-learn 문서). 세 가지 세부 사항 때문에 단순한 호출은 직접 계산한 값과 어긋난다.
- 전달한 제품만 채점하므로, 이상적인 순위도 그 제품들만으로 만든다.
- 기본적으로 점수가 같은 제품들의 이득은 평균을 취한다. 이는 동점 제품들의 가능한 모든 순서에 대한 평균과 같다(McSherry and Najork, 2008).
- 질의마다 한 행을 받으며 모든 행의 길이가 같아야 하고, 행들에 대한 평균을 반환한다(scikit-learn 소스).
먼저 단순한 호출을 본다. ndcg_score에 clear shower curtain에 대한 BM25 상위 10개의 등급을 넘기되, BM25의 순서가 되도록 점수를 준다. 그런 다음 lib.metrics가 질의를 보는 방식대로 각 질의의 행을 만들고, 세 가지 실행을 모두 비교한다.
1"""Compares scikit-learn's ndcg_score with lib.metrics for one query, first with only the top 10 passed and then with every judged product in the row, and then on every test query of three runs. The prose's point rests on the ndcg@10 lines for clear shower curtain and on the 5-product lines."""2from sklearn.metrics import ndcg_score34from lib.fusion import reciprocal_rank_fusion5from lib.lexical import LexicalSearch6from lib.metrics import ndcg_at_k7from lib.semantic import SemanticSearch8from lib.store import load_products, load_queries, qrels91011def sklearn_ndcg(ranking, judgments, k=10):12 """One row for one query: every judged product, plus any retrieved product nobody judged."""13 # every judged product once, then the retrieved products nobody judged14 products = list(dict.fromkeys([*judgments, *ranking]))15 position = {product_id: i for i, product_id in enumerate(ranking)}16 grades = [[judgments.get(product_id, 0) for product_id in products]]17 # ndcg_score ranks by score, so the negated position puts rank 1 highest18 scores = [[-position.get(product_id, len(ranking)) for product_id in products]] # not retrieved: below all19 return ndcg_score(grades, scores, k=k)202122queries, judgments = load_queries("test"), qrels("test")23bm25 = LexicalSearch(load_products()).run(queries, k=100)24semantic = SemanticSearch().run(queries, k=100)25runs = {"bm25": bm25, "semantic": semantic, "hybrid": reciprocal_rank_fusion([bm25, semantic])}2627top = bm25[246][:10] # clear shower curtain28# scores 10 down to 1 put the top 10 in BM25's order, so the first product scores highest29naive = ndcg_score([[judgments[246].get(product_id, 0) for product_id in top]], [list(range(10, 0, -1))], k=10)30print(f"ndcg@10, only the top 10 passed: {naive:.3f}")31print(f"ndcg@10 from lib.metrics: {ndcg_at_k(top, judgments[246], 10):.3f}")32print(f"ndcg@10, every judged product passed: {sklearn_ndcg(top, judgments[246]):.3f}")3334gaps = [abs(sklearn_ndcg(run[query_id], judgments[query_id]) - ndcg_at_k(run[query_id], judgments[query_id], 10))35 for run in runs.values() for query_id in judgments]36print("rankings compared:", len(gaps))37print(f"largest difference: {max(gaps):.3f}")3839short = bm25[246][:5] # a ranking shorter than k40print(f"5-product ranking, lib.metrics: {ndcg_at_k(short, judgments[246], 10):.3f}")41print(f"5-product ranking, scikit-learn: {sklearn_ndcg(short, judgments[246]):.3f}")
python ndcg-matches-scikit-learn.pyndcg@10, only the top 10 passed: 0.901
ndcg@10 from lib.metrics: 0.615
ndcg@10, every judged product passed: 0.615
rankings compared: 90
largest difference: 0.000
5-product ranking, lib.metrics: 0.539
5-product ranking, scikit-learn: 0.629
상위 10개만 넘기면 ndcg_score는 0.901을 반환하고, lib.metrics의 값은 0.615이다. 이는 그 열 개 제품만의 최선 순서로 나누기 때문에, BM25가 놓친 정확한 제품을 볼 수 없어서다. lib.metrics는 해당 질의에 대해 판정된 제품 253개 전체의 최선 순서로 나눈다. 예제의 sklearn_ndcg는 한 가지 방법으로 이를 바로잡는다. 각 행은 판정된 모든 제품과, 검색되었으나 아무도 판정하지 않은 제품을 등급 0으로 담는다. 이 방법은 검색된 제품에는 순위에 따라 점수를 주고, 그 밖의 모든 제품에는 그들 모두보다 낮은 점수 하나를 준다. 이렇게 하면 두 값은 90개 순위 전부에서 일치한다(최대 차이 0.000). 질의마다 행의 길이가 다르므로, ndcg_score는 질의마다 한 번씩 호출하고 결과의 평균은 직접 구한다.
이 방법에는 한계가 하나 있으며, 짧은 실행에서 드러난다. ndcg_score는 실행이 검색하지 못한 제품들을 상위 k 안의 빈자리를 두고 동점인 것으로 보고, 그 자리에 평균 이득을 부여한다. lib.metrics는 빈자리에 아무것도 주지 않는데, 쇼핑객에게는 그 자리에 아무것도 보이지 않기 때문이다. BM25의 순위를 5개 제품으로 자르면 두 값은 어긋난다. lib.metrics는 0.539이고 ndcg_score는 0.629이다. 짧은 실행은 실제로 나타난다. LexicalSearch는 점수가 0보다 큰 제품만 반환한다.
작업 규칙: nDCG는 직접 계산한 값을 보고하고, ndcg_score는 독립적인 검증에 사용하되, 각 질의의 행에 판정된 모든 제품을 넣고 점수는 순위에서 가져온다. 둘을 비교하기 전에 모든 실행이 최소 k개의 제품을 담고 있는지 확인한다. 순위기의 원점수를 대신 넘긴다면, 먼저 product_id 등으로 정해진 순서에 따라 동점을 깨야 한다. 그렇지 않으면 점수가 같은 곳마다 두 값이 어긋난다.
비교하기 전에 지표를 선택한다
모든 지표는 쇼핑객의 모형이다. Precision@10은 쇼핑객이 첫 페이지 전체를 살펴본다고 가정하고, 그 페이지에 있는 좋은 상품의 수를 센다. RR은 쇼핑객이 첫 번째 좋은 상품에서 멈춘다고 가정한다. nDCG@10은 페이지 아래로 내려갈수록 주의가 줄어든다고 가정하며, 정확한 상품이 부분적으로 맞는 상품보다 더 가치 있다고 본다. 이 책의 등급을 쓰면 두 배의 가치이다. Burges et al. (2005)처럼 지수 이득 2^grade − 1을 쓰면 등급이 0, 1, 3의 이득으로 바뀌므로 정확한 상품은 부분적으로 맞는 상품 세 개와 같은 가치를 갖는다. 경험칙으로, 이 모형들은 두 랭커가 크게 차이 날 때는 서로 일치한다. 랭커들이 가까울 때는 지표가 승자를 정할 수 있으며, 그래서 결과를 보기 전에 지표를 선택해야 한다. Fuhr는 "우리는 지표 X를 사용하여 방법 A와 B를 비교하고자 한다"라는 형식으로 가설을 미리 진술할 것을 요구한다(Fuhr, 2017, section 2.6).
이겨야 할 랭커인 시맨틱 검색과, 1장에서 시맨틱 검색과 구별하지 못한 하이브리드를 살펴보자. 지표를 선택하는 일은 평가를 조정하는 일의 일부이므로, 그 선택은 50개의 학습 질의에서 하고 테스트 질의는 보고용으로 남겨 둔다. 두 랭커를 네 가지 방식으로 채점한다.
1"""Scores semantic retrieval and the hybrid four ways on the train queries and names the higher scorer for each metric. The prose's point rests on the "higher" lines, the count of metrics each ranker wins, and the largest gap."""2from lib.fusion import reciprocal_rank_fusion3from lib.lexical import LexicalSearch4from lib.metrics import evaluate5from lib.semantic import SemanticSearch6from lib.store import load_products, load_queries, qrels78queries, judgments = load_queries("train"), qrels("train") # choosing a metric is tuning: use train9bm25 = LexicalSearch(load_products()).run(queries, k=100)10semantic = SemanticSearch().run(queries, k=100)11runs = {"semantic": semantic, "hybrid": reciprocal_rank_fusion([bm25, semantic])}1213exponential = {query_id: {product_id: 2 ** grade - 1 for product_id, grade in per_query.items()}14 for query_id, per_query in judgments.items()} # gains 0, 1, 3 instead of 0, 1, 215means = {}16for name, run in runs.items():17 scores = evaluate(run, judgments)18 means[name] = {"precision@10": scores["precision@10"].mean(), "mrr": scores["rr"].mean(),19 "ndcg@10": scores["ndcg@10"].mean(),20 "ndcg@10 with exponential gains": evaluate(run, exponential)["ndcg@10"].mean()}2122print("train queries:", len(judgments))23winners = []24for metric in means["semantic"]:25 for name in runs:26 print(f"{name} {metric}: {means[name][metric]:.3f}")27 # max keeps the first name it meets, so on an exact tie the order of runs decides28 winners.append(max(runs, key=lambda name: means[name][metric]))29 print(f"higher {metric}: {winners[-1]}")30for name in runs:31 print(f"metrics won by {name}:", winners.count(name))32print(f"largest gap: {max(abs(means['semantic'][m] - means['hybrid'][m]) for m in means['semantic']):.3f}")
python metric-choice-on-train.pytrain queries: 50
semantic precision@10: 0.502
hybrid precision@10: 0.488
higher precision@10: semantic
semantic mrr: 0.673
hybrid mrr: 0.710
higher mrr: hybrid
semantic ndcg@10: 0.772
hybrid ndcg@10: 0.774
higher ndcg@10: hybrid
semantic ndcg@10 with exponential gains: 0.709
hybrid ndcg@10 with exponential gains: 0.708
higher ndcg@10 with exponential gains: semantic
metrics won by semantic: 2
metrics won by hybrid: 2
largest gap: 0.037
네 지표는 승자에 대해 일치하지 않는다. 시맨틱 검색은 그중 2개에서 앞서고 하이브리드는 2개에서 앞서며, 두 랭커 사이의 차이는 어느 것도 0.037보다 크지 않다. 두 랭커가 이렇게 가까울 때는 지표가 차이가 어느 쪽으로 기울지를 결정한다. 1장에서 선택한 대표 지표인 nDCG@10은 hybrid을 유리하게 본다. 이는 학습 질의이므로, 이 결과 어느 것도 어느 랭커가 더 나은지를 말해 주지 않는다.
따라서 선택은 결과가 아니라 쇼핑객을 따라야 한다. 이 상점은 상품 페이지를 보여 주고 판정은 등급이 있으므로, 1장에서 선택한 대로 선형 이득의 nDCG@10을 대표 지표로 유지하고 precision@10과 MRR을 함께 둔다.
작업 규칙: 랭커를 비교하기 전에 대표 지표 하나와 그 이득, 절단 순위를 선택하고 기록해 둔다. 판정에 등급이 있고 쇼핑객이 한 페이지를 훑어본다면 선형 이득의 nDCG@10을 권장한다. 꼭 맞아야 하는 예비 부품처럼 정확히 일치하는 상품이 근접한 상품보다 훨씬 더 가치 있다면 지수 이득으로 바꾸고, 대부분의 질의에 정답이 하나라면 MRR로 바꾼다. 다른 지표들도 대표 지표와 함께 보고하며, 대표 지표가 어느 랭커를 유리하게 보는지 확인한 뒤에는 절대 대표 지표를 바꾸지 않는다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Read per-query differences, not only the mean
A mean of the headline metric over queries is a summary for the store, but a shopper sees one query's results. The TREC Robust track was built on that point. Its organizers found that tuning for the average can improve queries that already do well, sometimes at the expense of the poor performers (Voorhees, 2004). So before you trust a change in the mean, look at the per-query differences: one number per query, the new ranker's score minus the old one's. They are also the evidence that the significance tests use.
On average, the store's hybrid run from chapter 1 scores well above BM25. Compare the two query by query on nDCG@10:
1"""Compares the hybrid and BM25 query by query on nDCG@10, then lists the three largest losses and the largest gain with its judged@10. The prose's point rests on the mean and median difference lines and on the largest-gain lines."""2from lib.fusion import reciprocal_rank_fusion3from lib.lexical import LexicalSearch4from lib.metrics import evaluate5from lib.semantic import SemanticSearch6from lib.store import load_products, load_queries, qrels78queries, judgments = load_queries("test"), qrels("test")9bm25 = LexicalSearch(load_products()).run(queries, k=100)10hybrid = reciprocal_rank_fusion([bm25, SemanticSearch().run(queries, k=100)])11before, after = evaluate(bm25, judgments), evaluate(hybrid, judgments)1213# rounded to three decimals first, so a difference that rounds to 0 counts as a tie; sorted from the largest loss up14difference = (after["ndcg@10"] - before["ndcg@10"]).round(3).sort_values() # one value per test query15print(f"mean difference: {difference.mean():.3f}")16print(f"median difference: {difference.median():.3f}")17print("hybrid better:", (difference > 0).sum())18print("bm25 better:", (difference < 0).sum())19print("tied:", (difference == 0).sum())2021print("\nhybrid's three largest losses:")22print(queries.loc[difference.index[:3], "query"].to_frame().assign(difference=difference[:3]).to_string())23# the last one after sorting: the largest gain24largest = difference.index[-1]25print("\nlargest gain:", queries.at[largest, "query"])26print(f"its gain: {difference[largest]:.3f}")27print(f"its bm25 judged@10: {before.at[largest, 'judged@10']:.3f}")28print(f"share of the mean gain from this query: {difference[largest] / difference.sum():.3f}")2930relative = after["ndcg@10"] / before["ndcg@10"] - 1 # per-query relative gains31print(f"\nrelative gain of the means: {after['ndcg@10'].mean() / before['ndcg@10'].mean() - 1:.3f}")32print(f"mean of per-query relative gains: {relative.mean():.3f}")33print(f"its bm25 ndcg@10: {before.at[largest, 'ndcg@10']:.3f}")34print(f"its relative gain: {relative[largest]:.3f}")35print(f"mean of per-query relative gains without it: {relative.drop(largest).mean():.3f}")
python per-query-hybrid-versus-bm25.pymean difference: 0.087
median difference: 0.057
hybrid better: 17
bm25 better: 7
tied: 6
hybrid's three largest losses:
query difference
query_id
293 wood floor protector mat -0.072
292 decorative white pillow -0.069
249 bistro table and chairs -0.066
largest gain: outdoor light fixtures
its gain: 0.714
its bm25 judged@10: 0.200
share of the mean gain from this query: 0.274
relative gain of the means: 0.120
mean of per-query relative gains: 0.218
its bm25 ndcg@10: 0.286
its relative gain: 2.492
mean of per-query relative gains without it: 0.140
The mean gain is 0.087, but the median is 0.057. The hybrid wins on more queries than it loses, 17 to 7, and ties on 6.
One query does much of the work. outdoor light fixtures gains 0.714, a share of 0.274 of the total gain, and BM25's judged@10 on it is 0.200. For this query BM25's top 10 is mostly light bulbs nobody judged, and chapter 1 argues that their grade of 0 is fair, so the gain holds. For another query, the unjudged products a ranker drops might be good ones. The hybrid's three largest losses are the queries where a shopper would see search get worse, so read those first.
Report the difference as an absolute number. The relative gain of the means is 0.120, but the mean of the per-query relative gains is 0.218, because a mean of per-query ratios gives most weight to the queries where BM25 scores low.
outdoor light fixtures, where BM25 scores 0.286, contributes a relative gain of 2.492 on its own. Without that one query, the mean of relative gains falls to 0.140. Fuhr shows that the relative change in a mean says nothing reliable about the change per query, and that "for arithmetic mean, only absolute improvements are meaningful" (Fuhr, 2017, section 2.4).
Working rule: For every comparison, print the mean and median difference, the counts of wins, losses and ties, and the queries with the largest losses, then read those queries. Check judged@10 on the queries that move most before you credit the ranker. Report absolute differences of means, not percentages.
순열 검정으로 격차를 검정하라
질의 수십 개에서 얻은 두 평균 사이의 격차는 우연만으로도 생길 수 있다. 다른 질의 표본을 뽑으면 격차도 달라진다. 얕은 지표는 이 문제를 더 키운다. Buckley와 Voorhees는 precision at 10 같은 측정값을 쓸 때 시스템을 안정적으로 구분하려면 연구자에게 50개보다 훨씬 많은 질의가 필요하다는 것을 발견했다(Buckley and Voorhees, 2000). 유의성 검정(significance test)은 두 랭커가 똑같이 좋다고 가정하는 귀무가설(null hypothesis) 아래에서 두 랭커 사이의 격차가 얼마나 놀라운지를 묻는다. 그 답이 p-값(p-value)이며, 귀무가설 아래에서 측정한 격차만큼 또는 그보다 큰 격차가 나올 확률이다. 관례상 p-값이 0.05보다 작으면 실제 차이가 있다는 증거로 본다. 한 장에서 여러 번 비교할 때는 이 책의 규칙이 이 기준을 더 엄격하게 한다.
이 책의 검정은 모두 쌍체(paired) 검정이다. 두 랭커를 같은 질의로 채점하므로 각 검정은 질의별 차이를 대상으로 하고, 어려운 질의의 낮은 점수는 서로 상쇄된다. 순열 검정(permutation test)은 귀무가설 아래에서 나타날 격차를 직접 만들어 낸다. 두 랭커가 서로 바꿔 써도 되는 관계라면 각 질의의 차이는 부호가 반대일 가능성도 똑같이 크다. 그러므로 각 부호를 무작위로 뒤집고 평균을 다시 계산하는 과정을 수천 번 반복한 뒤, 뒤집은 평균이 0에서 실제 평균만큼 또는 그보다 멀리 떨어지는 경우가 얼마나 되는지 센다. 질의가 n개이면 부호 패턴은 2^n개이고, 테스트 질의의 부호 패턴은 1,073,741,824개이므로 검정은 그중 9,999개를 표본으로 뽑는다. 따라서 p-값은 추정값이다.
하이브리드는 테스트 질의에서 의미 기반 검색에 뒤처지며, 1장은 이 격차가 실제인지를 열어 두었다. 테스트 질의에서 의미 기반 검색에 대한 하이브리드의 승, 패, 무승부는 9 / 14 / 7이다. 검정은 하이브리드의 열세가 우연보다 크다고 판단할까? 답을 정한 다음 실행해 보라.
1"""Estimates the p-value of the hybrid's deficit against semantic retrieval by flipping each query's sign at random, once by hand and once with SciPy's permutation_test. The prose's point rests on the observed mean, the two p-value lines, and the line that compares the p-value with 0.05."""2import numpy as np3from scipy.stats import permutation_test45from lib.fusion import reciprocal_rank_fusion6from lib.lexical import LexicalSearch7from lib.metrics import evaluate8from lib.semantic import SemanticSearch9from lib.store import load_products, load_queries, qrels1011queries, judgments = load_queries("test"), qrels("test")12semantic = SemanticSearch().run(queries, k=100)13hybrid = reciprocal_rank_fusion([LexicalSearch(load_products()).run(queries, k=100), semantic])14after = evaluate(hybrid, judgments)["ndcg@10"].to_numpy()15before = evaluate(semantic, judgments)["ndcg@10"].to_numpy()16difference = after - before # hybrid minus semantic, per test query17print("test queries:", len(difference))18print(f"sign patterns for the test queries: {2 ** len(difference):,}")19print(f"observed mean difference: {difference.mean():.3f}")2021# if the two rankers were interchangeable, each query's difference would be as likely to have the other sign22# a fixed seed, so every run draws the same sign patterns23rng = np.random.default_rng(2026)24# 9,999 random sign patterns, one sign for each query in each25signs = rng.choice([-1, 1], size=(9999, len(difference)))26flipped = (signs * difference).mean(axis=1) # 9,999 mean differences under that assumption27# the 95th percentile of the flipped means' sizes28print(f"95% of flipped means are smaller than: {np.quantile(np.abs(flipped), 0.95):.3f}")29print(f"p-value by hand: {np.mean(np.abs(flipped) >= abs(difference.mean())):.3f}")3031result = permutation_test((after, before), lambda after_scores, before_scores, axis: np.mean(after_scores - before_scores, axis=axis),32 # samples: flip each query's pair of scores, which is the paired setting33 permutation_type="samples", rng=np.random.default_rng(2026))34print(f"p-value from scipy: {result.pvalue:.3f}")35print("difference at the 0.05 level:", "larger than chance" if result.pvalue < 0.05 else "within chance")
python permutation-test-by-hand.pytest queries: 30
sign patterns for the test queries: 1,073,741,824
observed mean difference: -0.018
95% of flipped means are smaller than: 0.022
p-value by hand: 0.117
p-value from scipy: 0.125
difference at the 0.05 level: within chance
의미 기반 검색에 대한 하이브리드의 열세는 0.05 수준에서 within chance. 관측된 평균 차이는 -0.018이고, 뒤집은 평균의 95%는 크기가 0.022보다 작다. 뒤집은 평균 중 관측된 평균만큼 또는 그보다 큰 것의 비율인 p-값은 0.117이다.
SciPy의 permutation_test을 쌍체 검정에 대해 문서가 제시하는 설정인 permutation_type="samples"로 실행하면 0.125이 나온다(SciPy documentation). 두 추정값이 조금 다른 것은 각각 자기만의 무작위 부호 패턴을 뽑기 때문이다. 열세가 실제라고 하려면 평균이 산포보다 커야 하며, 반대 방향으로 움직이는 질의 몇 개만 있어도 격차는 사라질 수 있다.
SciPy의 리샘플링 함수는 난수 생성기를 rng로 받으며, 이것이 random_state 인자를 대체한다. 1.18.1에서는 둘 다 동작하지만, 문서는 random_state를 쓰는 호출이 전환 기간이 지나면 경고를 낼 것이므로 "새 코드에서는 rng 키워드만 사용해야 한다"고 밝힌다(SciPy documentation). 이 책의 모든 예제는 고정된 시드와 함께 rng를 넘긴다.
작업 규칙: 조치를 취하려는 모든 격차는 질의별 차이에 대한 쌍체 순열 검정으로 검정하라. 이 책은 그 규칙에 설명된 대로 이 검정으로 결정한다. 임곗값보다 큰 p-값은 "차이가 없다"가 아니라 "차이의 증거가 없다"로 읽어라. 질의가 이만큼 적으면 검정이 실제 격차를 놓칠 수 있으며, McKechnie 등은 이런 놓침을 거짓 양성과 함께 측정해야 한다고 주장한다(McKechnie et al., 2025). 검정이 우연과 구별하지 못하는 격차는 설명하려 들지 마라.
쌍체 t-검정으로 p-값 구하기
쌍체 t-검정은 재표집 대신 공식을 사용해 같은 질문에 답한다. 이 검정은 쿼리별 차이의 평균을 표준오차로 나눈다. 표준오차는 차이의 표준편차를 쿼리 수의 제곱근으로 나눈 값으로, 쿼리 표본이 바뀔 때 평균이 얼마나 움직일지를 추정한다. 두 랭커의 성능이 같고 차이가 대략 정규분포를 따른다면, 이 비율 t는 t 분포를 따른다. t 분포는 종 모양이지만 정규분포보다 꼬리가 두껍고, 모양은 자유도로 정해지며, 여기서 자유도는 쿼리 수보다 1 작다. p-값은 t가 0에서 어느 방향으로든 관측값 이상 떨어져 있을 확률이다(Sakai, 2014, 3.1.1절).
t = mean(d) / (sd(d) / sqrt(n)) d: the per-query differences, n: the number of queries
쿼리별 nDCG 차이는 −1과 1 사이로 제한되고 outdoor light fixtures에서의 이득처럼 이상값이 있으므로 정규분포를 따르지 않는다. 그럼에도 실제로 t-검정은 잘 들어맞는다. Smucker 등은 50개 토픽에서 평균 정밀도(MAP, 또 다른 랭킹 지표)로 채점한 TREC 실행 결과를 두고, 무작위화 검정, 부트스트랩 검정, t-검정 사이에 실질적인 차이가 거의 없음을 발견했다. 여기서 무작위화 검정은 순열 검정이다(Smucker et al., 2007). Urbano 등은 TREC 데이터로 만든 시뮬레이션에서 토픽 25개, 50개, 100개 집합을 사용해 "t-검정과 순열 검정은 거의 동일하게 동작한다"는 결과를 얻었다(Urbano et al., 2019). 두 연구 모두 이 용도에는 Wilcoxon 부호 순위 검정과 부호 검정을 쓰지 말라고 권고한다. 또한 SciPy의 wilcoxon은 기본값인 zero_method='wilcox'에서 차이가 정확히 0인 쿼리를 모두 제외하는데(SciPy 문서), 두 실행 결과의 차이가 작으면 동점인 쿼리가 많아진다.
공식과 재표집은 1장의 격차에서 일치할까? 그중 두 가지, 곧 BM25 대비 의미 기반 검색과 의미 기반 검색 대비 하이브리드를 살펴보자. 직접 계산한 공식의 t는 SciPy의 ttest_rel와 일치해야 한다.
1"""Computes the paired t statistic and its p-value by hand for two gaps, and checks each p-value against SciPy's ttest_rel. The prose's point rests on the t and p lines printed for each gap."""2import math34from scipy.stats import t, ttest_rel56from lib.fusion import reciprocal_rank_fusion7from lib.lexical import LexicalSearch8from lib.metrics import evaluate9from lib.semantic import SemanticSearch10from lib.store import load_products, load_queries, qrels1112queries, judgments = load_queries("test"), qrels("test")13bm25 = LexicalSearch(load_products()).run(queries, k=100)14semantic = SemanticSearch().run(queries, k=100)15runs = {"bm25": bm25, "semantic": semantic, "hybrid": reciprocal_rank_fusion([bm25, semantic])}16ndcg = {name: evaluate(run, judgments)["ndcg@10"] for name, run in runs.items()} # per test query1718for after, before in [("semantic", "bm25"), ("hybrid", "semantic")]:19 difference = ndcg[after] - ndcg[before]20 n = len(difference)21 # ddof=1 divides by n - 1, the sample standard deviation the t-test uses22 standard_error = difference.std(ddof=1) / math.sqrt(n) # how much the mean would move between samples23 statistic = difference.mean() / standard_error24 p_value = 2 * t.sf(abs(statistic), df=n - 1) # both tails of the t distribution25 print(f"{after} minus {before}: {difference.mean():.3f}")26 print(f"{after} minus {before} t by hand: {statistic:.3f}")27 print(f"{after} minus {before} p by hand: {p_value:.3f}")28 print(f"{after} minus {before} p from ttest_rel: {ttest_rel(ndcg[after], ndcg[before]).pvalue:.3f}")
python paired-t-test-by-hand.pysemantic minus bm25: 0.105
semantic minus bm25 t by hand: 3.294
semantic minus bm25 p by hand: 0.003
semantic minus bm25 p from ttest_rel: 0.003
hybrid minus semantic: -0.018
hybrid minus semantic t by hand: -1.590
hybrid minus semantic p by hand: 0.123
hybrid minus semantic p from ttest_rel: 0.123
BM25 대비 의미 기반 검색에서는 평균 차이 0.105로부터 t = 3.294, p-값 0.003이 나오며, 이는 ttest_rel가 내놓는 값과 같다. 우연이 좀처럼 만들어 내지 못할 격차이다.
의미 기반 검색 대비 하이브리드에서는 t = -1.590이고 p-값은 0.123이다. 이는 같은 격차에 대한 순열 검정의 0.125에 가깝다.
작업 규칙: 재표집이 필요 없는 점검으로서 쌍체 t-검정 scipy.stats.ttest_rel을 순열 검정과 함께 보고한다. 두 결과가 임계값의 서로 다른 쪽에 놓이면 그 사실을 밝히고 순열 검정에 따라 판단한다. 평균 점수를 비교할 때는 Wilcoxon 검정이나 부호 검정을 쓰지 않는다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Report how big the gap is
A p-value says how surprising a gap is, not how big it is. On a large sample, nearly any modification produces a significant but tiny difference (Fuhr, 2017, section 2.8). Sakai recommends reporting an effect size and a confidence interval with every p-value (Sakai, 2014). A confidence interval is a range of plausible values for the true mean difference: the mean over all queries like these, scored with these judgments, not over the store's search traffic. A 95% interval comes from a procedure meant to cover that value 95% of the time.
The bootstrap builds a confidence interval by resampling. Draw as many queries as you have from the queries you have, with replacement, so that some appear twice and others not at all. Compute the mean difference, and repeat thousands of times. The percentile interval is the middle 95% of the resampled means. The effect size of a paired comparison is the mean difference divided by the standard deviation of the differences (Sakai, 2014, section 3.1.2). It is how large the gap is next to how much it varies from query to query. It isn't Cohen's d, the effect size for unpaired samples, and Sakai warns against comparing the two directly.
Can a hand-built percentile interval match SciPy's bootstrap with method="percentile"? Build one by hand for semantic retrieval against BM25 and for the hybrid against semantic retrieval, check each against SciPy, then run SciPy's default method:
1"""Builds a 95% percentile interval by hand from 9,999 resampled means, checks it against SciPy's percentile method, then reads SciPy's default BCa interval and the effect size for each gap. The prose's point rests on the BCa low and high lines and on the line that says whether each interval includes 0."""2import numpy as np3from scipy.stats import bootstrap45from lib.fusion import reciprocal_rank_fusion6from lib.lexical import LexicalSearch7from lib.metrics import evaluate8from lib.semantic import SemanticSearch9from lib.store import load_products, load_queries, qrels1011queries, judgments = load_queries("test"), qrels("test")12bm25 = LexicalSearch(load_products()).run(queries, k=100)13semantic = SemanticSearch().run(queries, k=100)14runs = {"bm25": bm25, "semantic": semantic, "hybrid": reciprocal_rank_fusion([bm25, semantic])}15ndcg = {name: evaluate(run, judgments)["ndcg@10"] for name, run in runs.items()} # per test query1617for after, before in [("semantic", "bm25"), ("hybrid", "semantic")]:18 difference, name = (ndcg[after] - ndcg[before]).to_numpy(), f"{after} minus {before}"19 # choice draws with replacement, so a query can appear twice in one set and not at all in another20 resampled = np.random.default_rng(2026).choice(difference, size=(9999, len(difference))) # 9,999 sets of queries21 # 2.5% in each tail leaves the middle 95%22 low, high = np.percentile(resampled.mean(axis=1), [2.5, 97.5]) # the middle 95% of their means23 print(f"{name}: {difference.mean():.3f}")24 print(f"{name} interval by hand: {low:.3f} to {high:.3f}")25 percentile = bootstrap((difference,), np.mean, method="percentile", rng=np.random.default_rng(2026))26 print(f"{name} percentile interval from scipy: "27 f"{percentile.confidence_interval.low:.3f} to {percentile.confidence_interval.high:.3f}")28 # BCa is SciPy's default method, so no method argument is given29 bca = bootstrap((difference,), np.mean, rng=np.random.default_rng(2026)).confidence_interval30 print(f"{name} bca low: {bca.low:.3f}\n{name} bca high: {bca.high:.3f}")31 print(f"{name} bca interval and 0: {'includes 0' if bca.low <= 0 <= bca.high else 'excludes 0'}")32 # ddof=1: the standard deviation of the differences, with n - 1 in the denominator33 print(f"{name} effect size: {difference.mean() / difference.std(ddof=1):.3f}")
python bootstrap-interval-by-hand.pysemantic minus bm25: 0.105
semantic minus bm25 interval by hand: 0.049 to 0.172
semantic minus bm25 percentile interval from scipy: 0.049 to 0.172
semantic minus bm25 bca low: 0.055
semantic minus bm25 bca high: 0.185
semantic minus bm25 bca interval and 0: excludes 0
semantic minus bm25 effect size: 0.601
hybrid minus semantic: -0.018
hybrid minus semantic interval by hand: -0.041 to 0.003
hybrid minus semantic percentile interval from scipy: -0.041 to 0.003
hybrid minus semantic bca low: -0.042
hybrid minus semantic bca high: 0.002
hybrid minus semantic bca interval and 0: includes 0
hybrid minus semantic effect size: -0.290
SciPy's percentile interval matches the one built by hand: 0.049 to 0.172 and -0.041 to 0.003. Its default method, BCa (bias-corrected and accelerated), reads different percentiles off the same resampled means. It shifts them by how far the resampled means sit off-centre from the observed mean, and stretches them by the skew it estimates by leaving out one query at a time (SciPy source). The book's harness reports BCa, designed for skewed resampled means like these.
For semantic retrieval against BM25, BCa runs from 0.055 to 0.185, so it excludes 0, and the effect size is 0.601.
For the hybrid against semantic retrieval, the interval runs from -0.042 to 0.002. It includes 0, and the effect size is -0.290. That interval allows anything from a loss of a few hundredths to a gain of at most 0.002: no gain worth having.
A bootstrap interval only approximates its level, and on a few dozen queries it falls short. To check, treat the hybrid's 30 per-query differences against semantic retrieval as if they were every query there is, so the true gap is known. Then draw 1000 new sets of the same size from them, build an interval on each, and count how often it covers the true gap:
1"""Draws new samples from the test queries' differences and counts how often a BCa or a t interval covers the known gap, at two levels. The prose's point rests on the four coverage lines and the standard-error line."""2import numpy as np3from scipy.stats import bootstrap, ttest_1samp45from lib.fusion import reciprocal_rank_fusion6from lib.lexical import LexicalSearch7from lib.metrics import evaluate8from lib.semantic import SemanticSearch9from lib.store import load_products, load_queries, qrels1011queries, judgments = load_queries("test"), qrels("test")12semantic = SemanticSearch().run(queries, k=100)13hybrid = reciprocal_rank_fusion([LexicalSearch(load_products()).run(queries, k=100), semantic])14population = (evaluate(hybrid, judgments)["ndcg@10"] - evaluate(semantic, judgments)["ndcg@10"]).to_numpy()15true_gap = population.mean() # known, because these differences stand in for every query there is1617# a fixed seed, so the coverage counts repeat on every run18rng, trials = np.random.default_rng(2026), 100019print("trials:", trials)20# binomial standard error of a proportion near 0.95, over the trials21print(f"standard error of a coverage near 0.95: {(0.95 * 0.05 / trials) ** 0.5:.3f}")22for level in [0.95, round(1 - 0.05 / 3, 4)]: # the usual level, and the level for three comparisons23 covered = {"bca": 0, "t": 0}24 for _ in range(trials):25 sample = rng.choice(population, size=len(population)) # another set of 30 queries like these26 # 1,999 resamples per interval, fewer than SciPy's default, to keep 1,000 trials quick27 bca = bootstrap((sample,), np.mean, confidence_level=level, n_resamples=1999, rng=rng).confidence_interval28 t = ttest_1samp(sample, 0).confidence_interval(level) # the interval that matches the t-test29 covered["bca"] += bca.low <= true_gap <= bca.high30 covered["t"] += t.low <= true_gap <= t.high31 for method, count in covered.items():32 print(f"{method} coverage at {level}: {count / trials:.3f}")
python interval-coverage-check.pytrials: 1000
standard error of a coverage near 0.95: 0.007
bca coverage at 0.95: 0.927
t coverage at 0.95: 0.945
bca coverage at 0.9833: 0.955
t coverage at 0.9833: 0.975
At a nominal 95%, BCa covers the true gap 0.927 of the time and the t-test's interval 0.945. At 0.9833, the level the harness uses for its planned comparisons, BCa covers 0.955 and the t interval 0.975.
Each figure is uncertain by about 0.007 either way. BCa falls short of its level at both, and the t interval comes closer to its own. So a bootstrap interval that barely excludes 0 deserves care. In a simulation, a test built on the same resampling, the bootstrap-shift test, "shows a systematic bias towards small p-values" (Urbano et al., 2019).
Whether a gap matters is a judgment no test makes for you. For precision@10, Fuhr notes that "a difference of 0.02 translates into one more relevant document per five queries" (Fuhr, 2017, section 2.8). For nDCG@10, decide before you test what gap would justify the cost of a change.
Working rule: Give every comparison as its mean difference, with its bootstrap interval, its effect size and its p-value. If the interval includes 0, the comparison shows no improvement. If it excludes 0 but lies below the smallest gap worth the change's cost, the difference may be real and still not worth shipping. Use the interval to describe a gap's size, not to decide whether it exists.
무엇을 확립된 결과로 볼지 미리 정한다
0.05 수준의 검정은 모두, 차이가 잡음일 때 5%의 확률로 거짓 양성을 낸다. 한 장에서 검정을 여러 번 수행하면 이 위험도 그만큼 여러 번 감수하게 된다. 시스템 10개의 모든 쌍을 이런 식으로 비교하면, 모든 차이가 잡음이고 검정들이 서로 독립이라고 할 때 적어도 한 번은 거짓 "유의" 결과가 나올 확률이 약 0.90이다(Sakai, 2014, section 3). Bonferroni 보정은 단순하고 보수적인 해결책이다. m개의 가설을 검정할 때 각각을 0.05를 m으로 나눈 값에서 검정한다(Fuhr, 2017, section 2.7). 이렇게 하면 검정들의 독립 여부와 관계없이, 거짓 양성이 하나라도 나올 확률이 0.05 이하로 유지된다. 다만 이는 m개의 비교가 결과를 보기 전에 고정되어 있을 때만 성립한다. Fuhr는 이것을 깨뜨리는 흔한 방식을 지적한다. 저자가 먼저 데이터에서 가장 성능이 좋은 경쟁 방법을 찾아낸 다음, 자신의 접근법을 그 방법과만 비교하는 것이다(Fuhr, 2017, section 2.6).
그래서 이 책은 모든 장에서 하나의 규칙을 쓴다.
- 비교 결과를 하나라도 보고하기 전에 테스트 질의에 대한 계획된 비교를 나열한다.
- 짝지은 순열 검정의 p-값이 그 장의 Bonferroni 임계값, 즉 0.05를 계획된 비교의 수로 나눈 값보다 작으면 차이가 확립된 것으로 본다.
- 짝지은 t-검정과 부트스트랩 구간을 함께 보고한다. 구간은 임계값을 1에서 뺀 값에 해당하는 수준으로 구한다. 둘 중 하나라도 순열 검정과 어긋나면 그 사실을 밝힌다.
- 테스트 결과를 본 뒤에 고른 비교는 탐색적이다. 그렇게 표시하고, 확립되었다고 부르지 않는다.
- 훈련 질의에 대한 비교는 튜닝용이며 증거가 아니다.
순열 검정이 결정하도록 하는 이유는, 이 검정이 차이의 분포 형태에 대해 아무것도 가정하지 않고 귀무가설 아래에서 각 질의의 부호가 동전 던지기와 같다는 것만 가정하기 때문이다. Urbano 등은 두 검정이 거의 같게 동작함을 발견했으며(Urbano et al., 2019), 그래서 t-검정은 좋은 점검 수단이 된다. 질의가 수십 개인 경우 부트스트랩 구간은 명목 수준보다 덜 자주 참값을 포함한다(coverage check). 그래서 구간은 차이를 기술할 뿐 그 차이를 판정하지는 못한다.
1장은 저장소의 파이프라인을 한 단계씩 쌓아 가며, 이 순서만으로 계획된 비교가 정해진다. 각 단계를 바로 앞 단계와 비교하는 것이다. 그러면 의미 검색 대 BM25, 하이브리드 대 의미 검색, 재순위화된 하이브리드 대 하이브리드가 되어 계획된 비교는 모두 3개이다. 임계값은 0.0167이고, 구간은 0.9833 수준을 사용한다. 재순위화된 하이브리드와 의미 검색의 비교는 탐색적이다. 의미 검색이 바로 이 테스트 질의에서 가장 높은 점수를 받아 이겨야 할 랭커가 되었기 때문이다.
작업 규칙: 테스트 질의에서 무엇이든 점수를 매기기 전에 계획된 비교의 목록을 작성하고, 목록은 짧게 유지한다. 비교 하나하나가 나머지 비교의 기준을 높이기 때문이다. 많은 랭커를 한꺼번에 비교해야 할 때는 Bonferroni가 지나치게 엄격해진다. Sakai는 먼저 랭커들 사이에 차이가 하나라도 있는지 검정하는 분산 분석을 수행하고, 이어서 무작위화 Tukey HSD 검정을 수행하라고 권한다. 이 검정은 모든 쌍을 비교하면서도 거짓 양성이 하나라도 나올 확률을 해당 수준으로 유지한다(Sakai, 2014).
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Compare runs in an evaluation harness
The book applies that rule in an evaluation harness, which holds everything fixed except the ranker: the same queries, judgments, metrics and tests, so that two runs differ only in their rankings. lib.metrics.evaluate returns one row per query, which is the shape the paired tests need. compare in lib.significance, a short module that collects this chapter's code, runs the tests on one metric's column from two runs. It returns the mean difference, the bootstrap interval, the permutation and t-test p-values, the effect size, and the wins, losses and ties. Its verdict function applies the book's rule to a result. Keep the per-query frames, and average only at the end.
So run chapter 1's four rankers through it, then make the 3 planned comparisons and the exploratory one:
1"""Runs chapter 1's four rankers through the harness and applies the Bonferroni threshold to the three planned comparisons and one exploratory comparison. The prose's point rests on the judged@10 lines, the established lines, and the exploratory comparison's p-value and agreement lines."""2from lib.fusion import reciprocal_rank_fusion3from lib.lexical import LexicalSearch4from lib.metrics import evaluate5from lib.recorded import cross_encoder_scores6from lib.semantic import SemanticSearch7from lib.significance import compare, verdict8from lib.store import load_products, load_queries, qrels910queries, judgments = load_queries("test"), qrels("test")11bm25 = LexicalSearch(load_products()).run(queries, k=100)12semantic = SemanticSearch().run(queries, k=100)13hybrid = reciprocal_rank_fusion([bm25, semantic])14score = {(query_id, product_id): value for query_id, product_id, value in cross_encoder_scores().itertuples(index=False)}15# chapter 1's rerank: only the top 50 are reordered; the rest keep their hybrid order16reranked = {query_id: sorted(ranking[:50], key=lambda product_id: score[(query_id, product_id)], reverse=True)17 + ranking[50:] for query_id, ranking in hybrid.items()}1819runs = {"bm25": bm25, "semantic": semantic, "hybrid": hybrid, "reranked": reranked}20scores = {name: evaluate(run, judgments) for name, run in runs.items()} # one row per test query21for name, frame in scores.items():22 print(f"{name} ndcg@10: {frame['ndcg@10'].mean():.3f}\n{name} judged@10: {frame['judged@10'].mean():.3f}")2324planned = [("semantic", "bm25"), ("hybrid", "semantic"), ("reranked", "hybrid")] # each stage against the last25exploratory = [("reranked", "semantic")] # chosen after chapter 1 saw the test means26threshold = 0.05 / len(planned) # Bonferroni, over the planned comparisons only27print(f"\nplanned comparisons: {len(planned)}\np-value threshold: {threshold:.4f}\ninterval level: {1 - threshold:.4f}")28# each planned test has a 0.95 chance of no false positive, if its gap is noise29print(f"chance of a false positive, all gaps noise, tests independent: {1 - 0.95 ** len(planned):.3f}")30established, disagreements = 0, 031for after, before in planned + exploratory:32 result, name = compare(scores[after]["ndcg@10"], scores[before]["ndcg@10"], confidence=1 - threshold), f"{after} minus {before}"33 # verdict runs on the exploratory one too, only for its agreement checks; it is never counted as established34 checks, kind = verdict(result, threshold), "planned" if (after, before) in planned else "exploratory"35 print(f"\n{name}: {result['mean difference']:.3f}\n{name} kind: {kind}")36 print(f"{name} interval: {result['ci low']:.3f} to {result['ci high']:.3f}")37 print(f"{name} permutation p: {result['permutation p']:.3f}\n{name} t-test p: {result['t-test p']:.3f}")38 print(f"{name} effect size: {result['effect size']:.3f}\n{name} wins, losses, ties: {result['wins']} / {result['losses']} / {result['ties']}")39 # only a planned comparison can be established; the exploratory one is labelled and never called so40 print(f"{name} established: {'yes' if checks['established'] and kind == 'planned' else 'no'}")41 for method in ["t-test", "interval"]:42 print(f"{name} {method} agrees: {'yes' if checks[method + ' agrees'] else 'no'}")43 if kind == "planned":44 established += checks["established"]45 # a planned comparison where the t-test or the interval disagrees with the permutation test46 disagreements += not (checks["t-test agrees"] and checks["interval agrees"])47print(f"\nplanned comparisons established: {established}\nplanned comparisons with a disagreement: {disagreements}")
python compare-chapter-one-rankers.pybm25 ndcg@10: 0.725
bm25 judged@10: 0.927
semantic ndcg@10: 0.830
semantic judged@10: 0.990
hybrid ndcg@10: 0.812
hybrid judged@10: 0.980
reranked ndcg@10: 0.798
reranked judged@10: 0.980
planned comparisons: 3
p-value threshold: 0.0167
interval level: 0.9833
chance of a false positive, all gaps noise, tests independent: 0.143
semantic minus bm25: 0.105
semantic minus bm25 kind: planned
semantic minus bm25 interval: 0.047 to 0.205
semantic minus bm25 permutation p: 0.001
semantic minus bm25 t-test p: 0.003
semantic minus bm25 effect size: 0.601
semantic minus bm25 wins, losses, ties: 21 / 7 / 2
semantic minus bm25 established: yes
semantic minus bm25 t-test agrees: yes
semantic minus bm25 interval agrees: yes
hybrid minus semantic: -0.018
hybrid minus semantic kind: planned
hybrid minus semantic interval: -0.048 to 0.006
hybrid minus semantic permutation p: 0.125
hybrid minus semantic t-test p: 0.123
hybrid minus semantic effect size: -0.290
hybrid minus semantic wins, losses, ties: 9 / 14 / 7
hybrid minus semantic established: no
hybrid minus semantic t-test agrees: yes
hybrid minus semantic interval agrees: yes
reranked minus hybrid: -0.014
reranked minus hybrid kind: planned
reranked minus hybrid interval: -0.053 to 0.020
reranked minus hybrid permutation p: 0.382
reranked minus hybrid t-test p: 0.375
reranked minus hybrid effect size: -0.165
reranked minus hybrid wins, losses, ties: 11 / 12 / 7
reranked minus hybrid established: no
reranked minus hybrid t-test agrees: yes
reranked minus hybrid interval agrees: yes
reranked minus semantic: -0.032
reranked minus semantic kind: exploratory
reranked minus semantic interval: -0.078 to -0.003
reranked minus semantic permutation p: 0.048
reranked minus semantic t-test p: 0.048
reranked minus semantic effect size: -0.377
reranked minus semantic wins, losses, ties: 9 / 16 / 5
reranked minus semantic established: no
reranked minus semantic t-test agrees: yes
reranked minus semantic interval agrees: no
planned comparisons established: 1
planned comparisons with a disagreement: 0
Unjudged products weigh most on BM25, whose judged@10 is 0.927 against 0.990 for semantic retrieval, 0.980 for the hybrid and 0.980 for the reranked hybrid.
With 3 tests at 0.05 each, the chance of at least one false positive would be 0.143 if every gap were noise and the tests were independent. The Bonferroni correction caps it at 0.05 either way. On nDCG@10 over the test queries, with intervals at the 0.9833 level:
| Measure | Semantic minus BM25 | Hybrid minus semantic | Reranked minus hybrid | Reranked minus semantic |
|---|---|---|---|---|
| Kind | planned | planned | planned | exploratory |
| Mean difference | 0.105 | -0.018 | -0.014 | -0.032 |
| Interval | 0.047 to 0.205 | -0.048 to 0.006 | -0.053 to 0.020 | -0.078 to -0.003 |
| Permutation p | 0.001 | 0.125 | 0.382 | 0.048 |
| t-test p | 0.003 | 0.123 | 0.375 | 0.048 |
| Effect size | 0.601 | -0.290 | -0.165 | -0.377 |
| Wins / losses / ties | 21 / 7 / 2 | 9 / 14 / 7 | 11 / 12 / 7 | 9 / 16 / 5 |
| Established | yes | no | no | no |
Of the 3 planned comparisons, 1 is established: semantic retrieval's lead over BM25, with a permutation p-value of 0.001. The hybrid's deficit against semantic retrieval and the reranker's against the hybrid are not established: on these queries neither change shows an improvement, and neither is shown to be worse. The harness checks the t-test and the interval against the permutation test: 0 planned comparisons have a disagreement.
The exploratory comparison is where the checks start to disagree. Its permutation p-value is 0.048, to set against 0.05 without a correction and 0.0167 with one, and its interval runs from -0.078 to -0.003.
The t-test sides with the permutation test, but the interval, which excludes 0, does not. Asked whether each check agrees with the permutation test, the harness answers yes for the t-test and no for the interval: an interval that excludes 0 beside a p-value above the threshold is the kind of disagreement the coverage check warns about. Whatever its numbers, this comparison can't be established, because it was chosen after seeing the test means. At most it raises a question for new queries: does this reranker trail semantic retrieval?
Chapter 1's decision stands, by a rule that doesn't depend on which ranker scored highest: the ranker to beat is the simplest pipeline that no planned comparison has shown to be beaten. Semantic retrieval beat BM25, and neither later stage beat the stage before it.
Working rule: For every change, report the mean nDCG@10 and judged@10 of each run, then a table like this one, with a column for each comparison and the exploratory ones labelled. A change ships only when it is established against the ranker to beat.
운영 환경에서 문제가 되는 것
질의 표본 하나는 오해를 낳을 수 있다. 테스트 질의에서 얻은 결과는 어떤 질의가 테스트 집합에 들어갔는지에 좌우된다. Fuhr는 단순 홀드아웃 방법은 결과가 분할에 크게 좌우될 수 있어 신뢰하기 어렵다고 주장하며, 그 대신 교차 검증을 요구한다(Fuhr, 2017, section 2.5). Sakai도 "서로 다른 훈련/검증/테스트 분할은 서로 다른 결과를 낼 수 있다"라고 동의한다(Sakai, 2020). 이 책은 모든 장이 같은 테스트 질의를 기준으로 보고하도록 분할을 하나로 고정한다. 격차가 얼마나 움직일 수 있는지 보려면 하니스의 탐색적 비교를 훈련 질의에서도 실행해 본다. 훈련 질의는 규칙이 정하듯 튜닝을 위한 것이므로, 이 비교는 증거가 아니라 예시로만 취급한다.
1"""Runs the reranked-minus-semantic comparison on the test queries and on the train queries, so the verdict can be compared across the two samples. The prose's point rests on the two gap lines and the higher-scoring-run lines."""2from lib.fusion import reciprocal_rank_fusion3from lib.lexical import LexicalSearch4from lib.metrics import evaluate5from lib.recorded import cross_encoder_scores6from lib.semantic import SemanticSearch7from lib.significance import compare8from lib.store import load_products, load_queries, qrels910lexical, embeddings = LexicalSearch(load_products()), SemanticSearch()11score = {(query_id, product_id): value for query_id, product_id, value in cross_encoder_scores().itertuples(index=False)}1213for split in ["test", "train"]: # the same comparison on another sample of the store's queries14 queries, judgments = load_queries(split), qrels(split)15 semantic = embeddings.run(queries, k=100)16 hybrid = reciprocal_rank_fusion([lexical.run(queries, k=100), semantic])17 # as in chapter 1: rerank the top 50 and keep the rest in hybrid order18 reranked = {query_id: sorted(ranking[:50], key=lambda product_id: score[(query_id, product_id)], reverse=True)19 + ranking[50:] for query_id, ranking in hybrid.items()}20 result = compare(evaluate(reranked, judgments)["ndcg@10"], evaluate(semantic, judgments)["ndcg@10"])21 gap = result["mean difference"]22 print(f"{split} queries:", len(judgments))23 print(f"{split} reranked minus semantic: {gap:.3f}")24 print(f"{split} higher-scoring run:", "reranked" if gap > 0 else "semantic" if gap < 0 else "neither")25 if split == "test":26 print(f"test permutation p: {result['permutation p']:.3f}")
python split-changes-the-verdict.pytest queries: 30
test reranked minus semantic: -0.032
test higher-scoring run: semantic
test permutation p: 0.048
train queries: 50
train reranked minus semantic: 0.014
train higher-scoring run: reranked
점수가 더 높은 실행은 테스트 질의에서는 semantic이고 훈련 질의에서는 reranked이므로, 어느 실행의 점수가 더 높은지는 분할에 따라 뒤바뀐다.
30개의 테스트 질의에서 재순위화한 하이브리드에서 의미 기반 검색을 뺀 값은 -0.032이다(순열 검정 p = 0.048). 50개의 훈련 질의에서는 0.014이다. 한 표본에서 0.05에 이렇게 가까운 p값은 그 위에 무언가를 쌓기에는 약한 근거이다. 11장은 테스트 질의가 모든 선택에 영향을 주지 않도록 막는 방법을 다룬다.
테스트 질의를 재사용하면 많은 가설을 검정하는 셈이 된다. 같은 질의에서 변경을 하나 시험할 때마다 비교가 하나 늘어나며, 몇 달에 걸쳐 시험해도 마찬가지이다. Fuhr는 "컬렉션 재사용 또한 다중 가설 검정의 한 사례"라고 지적한다(Fuhr, 2017, section 2.7). 테스트 질의에서 수행한 비교의 기록을 남기고, 임계값을 정할 때 그 수를 세어 반영한다.
동점 점수는 실행을 재현할 수 없게 만든다. 점수가 같은 두 상품은 어느 순서로든 반환될 수 있으며, 다중 스레드 색인은 점수가 동점일 때 순서를 비결정적으로 만들 수 있다(Lin and Yang, 2019). 재현 가능한 순서조차 임의적일 수 있다. 동점은 라이브러리의 top-k 선택이나 안정 정렬의 입력이 남기는 순서가 무엇이든 그대로 따라간다. 그래서 이 책의 모듈은 동점을 product_id로 해소한다. LexicalSearch와 lib.fusion은 같은 점수를 그 기준으로 정렬하고, SemanticSearch는 product_id 순서로 저장된 벡터에 대해 안정 정렬을 한다. 모든 버전을 고정하면 re-check examples가 각 예제를 기록된 출력과 대조해 다시 실행하므로, 이 순서 중 어느 하나라도 바뀌면 드러난다. 직접 만드는 시스템에서는 점수를 계산하기 전에, product_id처럼 정보를 담지 않는 고정된 순서로 동점을 해소한다.
판정되지 않은 상품은 랭커의 점수를 낮춘다. 아무도 판정하지 않은 상품을 상위에 올리는 랭커는, 그 상품이 좋더라도 그 때문에 nDCG를 잃는다. 시험하기 전에 judged@10을 확인하고, 이 값이 떨어지면 새 상품을 판정받도록 한다.
작업 규칙: 테스트 질의에서 수행하는 모든 비교를 기록하고, 경계에 있거나 탐색적인 결과는 새 질의로 확인할 질문으로 취급하며, 점수 동점은 고정된 순서로 해소하고, 모든 nDCG@10 옆에 judged@10을 함께 보고한다.
이 장이 내린 결정
아래의 각 선택은 이후 이 책의 기본값이다. 이후의 장은 그 장이 제시하는 이유가 있을 때에만 선택을 바꾼다.
- 대표 지표: 선형 이득을 쓰는 nDCG@10(등급 2, 1, 0), log2(i + 1) 할인, 그리고 판정을 받은 모든 상품으로 만든 이상적 순위를 쓴다. precision@10과 MRR을 함께 보고한다. 관련 있음은 정확히 일치함을 뜻한다.
- 우리가 만든 지표가 기준이다. 이 책은
lib.metrics을 보고하고, 각 행에서 판정을 받은 모든 상품을 넣어 scikit-learn의ndcg_score로 검증한다. - 모든 비교는 질의별 차이를 보여 준다. 평균과 중앙값, 승·패·무승부의 수, 가장 크게 진 질의, 그리고 가장 크게 변한 질의의 judged@10을 제시한다.
- 차이가 입증되었다고 보는 규칙: 먼저 테스트 질의에 대해 계획한 비교를 나열한다. 부호를 무작위로 9,999번 뒤집는 순열 검정의 p-값이 0.05를 계획한 비교의 수로 나눈 값보다 작으면 그 차이가 입증된 것이다. 쌍체 t-검정과 이에 대응하는 수준의 BCa 부트스트랩 구간을 함께 보고하고, 서로 어긋나면 그 사실을 밝힌다. 테스트 결과를 본 뒤에 고른 비교는 탐색적이라고 표시하며, 입증되었다고 부르지 않는다. 학습 질의는 튜닝에만 쓴다.
- 입증되지 않은 차이는 "개선이 확인되지 않음"으로 보고한다. 손실이라고 하지 않으며, 그 이유를 설명하지도 않는다.
- 모든 재표집은 시드를 고정한
rng를 사용하며,lib.significance을 통해 수행한다. - 계획한 비교에서 배운 것: 1장의 비교 가운데 BM25에 대한 의미 기반 검색의 우위는 입증되었고 나머지 둘은 입증되지 않았다. 따라서 의미 기반 검색이 계속 이겨야 할 랭커로 남는다. 이후의 모든 변경은 하니스에서 그 변경이 바꾸는 랭커와 비교해 검정하며, 이겨야 할 랭커를 이길 때에만 채택한다.
이 판의 이 장
2026.11.10판예제 통과 2026년 11월 19이 장에서 12개 예제개 중 12개가 통과한다
영어판 2026.11.10판을 번역한 것이다.