질의 이해
읽는 데 약 61분분 걸린다, 10절에 12개 예제이(가) 있음.
AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식
영어판 2026.11.10판을 번역한 것이다. 원문 읽기
이 장을 마치면 검색에 앞서 쇼핑객의 질의를 바꿀 수 있다. 철자를 교정하고, 단위를 한 가지 방식으로 표기하고, 동의어로 확장하고, 상품 클래스를 예측하고, 대규모 언어 모델로 재작성하고, 그 모델이 상상한 상품으로 검색하고, 후속 질문을 독립된 질의로 바꾸는 방법을 다룬다. 또한 각 변경이 그 질의를 받는 검색기에 도움이 되는지를 사람의 판단으로 결정할 수 있다.
쇼핑객이 the store의 검색창에 입력하는 짧은 질의 중 일부는 원하는 상품과 일치하지 못한다. ligth bulb는 단어의 철자가 틀렸다. 7qt slow cooker는 크기를 0 상품이 담고 있는 용어로 적는다. midcentury tv unit의 경우 7장에서 센 정확히 일치하는 상품은 25개이며, 그중 0개는 midcentury를, 0개는 unit을 포함한다.
책상을 검색한 뒤 in white를 입력하는 쇼핑객은 흰색 책상을 뜻하지만, 단어만으로는 그 의미가 드러나지 않는다. 질의 이해(query understanding)는 이러한 간극을 메우기 위해 검색 시스템이 검색에 앞서 질의에 하는 모든 작업이다. 질의를 교정하고, 정규화하고, 확장하고, 분류하고, 재작성한다. 5장부터 7장까지는 검색기를 바꾸었다. 이 장에서는 검색기를 고정하고 질의를 바꾼다. 고정하는 검색기는 lib.lexical에 있는 이 책의 어간 추출을 하지 않는 기준선인 BM25와, 질의의 임베딩을 각 상품의 임베딩과 비교하는 시맨틱 검색이다. 두 임베딩은 모두 Snowflake/snowflake-arctic-embed-m-v1.5가 미리 계산해 둔다.
이 장의 기법 중 세 가지는 이 상점의 LLM을 사용한다. 그 모델은 gemma4:12b-it-q4_K_M이며, Google이 Apache 2.0 라이선스로 공개한 개방형 모델이다(모델 카드). 예제에서는 이 모델을 호출하지 않는다. 스크립트 두 개, 즉 recordings/llm_rewrites.py와 recordings/llm_conversations.py가 온도 0과 고정된 시드로 모델을 한 번 실행하고 그 출력을 녹화본(recording)으로 저장했으며, 예제는 lib.recorded를 통해 이를 읽는다. 각 녹화본의 manifest.json에는 전체 프롬프트가 들어 있다. 녹화본은 4장과 같은 개방형 모델과 설정을 사용한다. LLM은 쇼핑객의 말만 볼 뿐 상품은 보지 못한다. 이 장의 모든 점수는 사람의 판단을 사용한다.
모든 설정은 50개의 훈련 질의에서 정하며, 30개의 테스트 질의는 보고용으로 남겨 둔다. 이 장은 계획한 비교 5개를 결과를 읽기 전에 테스트 질의로 확정했다. 각 비교 대상은 변경을 하나만 가한 검색기이며, 입력된 그대로의 질의를 쓰는 같은 검색기와 견주어 측정한다.
- 동의어 목록을 쓴 BM25
- 예측한 클래스에 가중치를 준 시맨틱 검색
- LLM의 재작성에 대한 BM25
- LLM의 재작성에 대한 시맨틱 검색
- 질의의 임베딩과 LLM이 상상한 상품의 임베딩을 평균하는 HyDE를 쓴 시맨틱 검색
계획한 각 비교는 이 책의 규칙을 통과해야 한다. 쌍체 순열 검정에서 p-value가 0.01 미만이어야 하며, 이 값은 0.05를 계획한 비교의 수로 나눈 것이다. 쌍체 t-검정과 99% 부트스트랩 구간을 함께 제시한다. 철자 교정, 단위 정규화, 후속 질문 재작성은 각각 다루는 질의가 너무 적어 검정할 수 없으므로 해당 절은 탐색적이다.
카탈로그의 단어를 기준으로 철자 교정하기
첫 번째 공백은 ligth bulb처럼 오타다. BM25에서는 철자가 틀린 단어가 같은 철자 오류를 가진 상품하고만 일치하며, 6장이 보여 주듯이 질의의 임베딩을 질의가 뜻하는 상품에서 멀어지게 할 수도 있다. 검색 질의에는 이런 오류가 많다. 웹 검색을 다룬 한 연구인 Cucerzan and Brill (2004)는 검색 엔진에 입력되는 질의의 약 10~15퍼센트에 오류가 있다고 보고한다. 고전적인 교정기는 잡음 채널(noisy channel) 모델이다. 입력된 단어 t에 대해 P(c) × P(t | c)를 최대화하는 교정 후보 c를 고른다(Kernighan et al., 1990). P(c)는 후보 단어가 얼마나 흔한지를 나타낸다. 오류 모델인 P(t | c)는 c를 뜻한 쇼핑객이 t를 입력할 가능성이 얼마나 되는지를 나타낸다. Kernighan et al.은 오타에서 한 번의 편집으로 도달하는 단어, 즉 삭제, 삽입, 대체 또는 이웃한 두 글자의 맞바꿈으로 얻는 단어를 후보로 삼는다. 한 문자열을 다른 문자열로 바꾸는 데 필요한 삽입, 삭제, 대체의 횟수를 두 문자열의 편집 거리(edit distance)라고 하며(Manning et al., 2008), 여기서 쓰는 교정기는 맞바꿈도 한 번의 편집으로 센다. 한 교재는 두 원칙을 쉬운 말로 이렇게 서술한다. 올바른 철자 중에서는 가장 가까운 것을 고르고, 비슷하게 가까운 후보 사이에서는 더 흔한 것을 고른다(Manning et al., 2008). Norvig는 이런 교정기를 몇 줄의 코드로 작성한다(Norvig).
correction(t) = argmax over candidates c of P(c) × P(t | c)
올바른 단어로 간주하는 단어의 목록인 어휘 목록(lexicon)이 무엇을 교정할지를 결정한다. 웹 검색 엔진은 질의 로그로 어휘 목록을 만들므로, 이들이 고르는 교정은 다른 사용자의 질의에서 가장 흔한 것이다(Manning et al.). 이 상점에는 로그가 없으므로 어휘 목록을 카탈로그의 텍스트에서 가져온다. 어휘 목록의 출처는 브랜드 이름에서 중요하다. 상품 검색의 교정기는 진짜 오타와 관례에서 벗어난 철자로 쓴 새 브랜드를 구별해야 하기 때문이다(Guo et al., 2024).
여기서 쓰는 교정기는 가장 단순한 오류 모델을 쓴다. 어휘 목록에 있는 단어는 그대로 두고, 한 번의 편집으로 닿는 후보가 두 번의 편집으로 닿는 후보보다 우선하며, 편집 횟수가 같은 후보 사이에서는 각 후보가 얼마나 흔한지를 뜻하는 P(c)로 승부를 가른다. 80개의 질의 전체에 이 교정기를 실행하여 어떤 질의가 바뀌는지 살펴보자.
1"""A spelling corrector built from the catalog's word counts, run on every query and checked against2lib.queries.correct_query. The prose's point rests on the "queries changed" line and on the line that says whether both correctors agree."""3import re4from collections import Counter56from lib.queries import correct_query7from lib.store import load_products, load_queries, product_text89texts = product_text(load_products()).str.lower()10counts = Counter(re.findall(r"[a-z]+", " ".join(texts))) # the lexicon, and how common each word is111213def edits1(word):14 """Every string one edit away: a deletion, a swap of two neighbouring letters, a replacement or an insertion."""15 splits = [(word[:cut], word[cut:]) for cut in range(len(word) + 1)]16 letters = "abcdefghijklmnopqrstuvwxyz"17 return ({left + right[1:] for left, right in splits if right}18 | {left + right[1] + right[0] + right[2:] for left, right in splits if len(right) > 1}19 | {left + letter + right[1:] for left, right in splits if right for letter in letters}20 | {left + letter + right for left, right in splits for letter in letters})212223def correct(word):24 """Keep a word the catalog uses. Otherwise take the commonest catalog word one edit away, else two."""25 if not word.isalpha() or word in counts:26 return word27 candidates = {edit for edit in edits1(word) if edit in counts} or {28 two for edit in edits1(word) for two in edits1(edit) if two in counts}29 # the most common candidate; on a tie in counts, the alphabetically first one30 return max(sorted(candidates), key=counts.get) if candidates else word313233queries = load_queries()34corrected = queries["query"].map(lambda query: " ".join(correct(word) for word in query.lower().split()))35changed = queries[corrected != queries["query"].str.lower()]36print(f"catalog words: {len(counts):,}")37print("queries changed:", len(changed))38print("of them, train queries:", (changed["split"] == "train").sum())39for query_id, query in changed["query"].items():40 print(f" {query} ({changed.at[query_id, 'split']}), corrected: {corrected[query_id]}")41same = corrected.equals(queries["query"].map(lambda query: correct_query(query, counts)))42print("same as lib.queries.correct_query:", same)43for word in ["tye", "tie", "the", "kohler", "whitehaven", "malachi", "luau"]: # P(c), as counts44 print(f"catalog count of {word}:", counts[word])
python catalog-spelling-corrector.pycatalog words: 19,680
queries changed: 4
of them, train queries: 3
foutains with brick look (train), corrected: fountains with brick look
twin over full bunk beds cool desins (train), corrected: twin over full bunk beds cool designs
ligth bulb (train), corrected: light bulb
tye dye duvet cover (test), corrected: the dye duvet cover
same as lib.queries.correct_query: True
catalog count of tye: 0
catalog count of tie: 45
catalog count of the: 20389
catalog count of kohler: 71
catalog count of whitehaven: 60
catalog count of malachi: 5
catalog count of luau: 4
카탈로그에는 서로 다른 단어가 19,680개 쓰이며, 교정기는 질의 4개를 바꾼다. 이 가운데 3개가 훈련 질의다. 공용 함수 lib.queries.correct_query도 같은 교정을 수행하며, 교정기는 6장의 철자 탐침이 하는 방식대로 각 훈련 질의를 교정한다. 즉 6장이 이 책을 위해 작성한 오타 질의의 올바른 철자 사본을 쓴다.
교정기는 브랜드를 건드리지 않는다. 카탈로그가 브랜드를 쓰고 있기 때문이다. kohler는 71번, whitehaven는 60번 쓰인다. 교정기가 그대로 두는 단어 중에는 드문 것도 있다. malachi는 5번, luau는 4번 쓰인다. 드문 단어를 뺀 어휘 목록은 이 둘을 모두 오타로 취급할 것이다.
교정기의 실패는 테스트 질의에서 나타난다. tye dye duvet cover는 the dye duvet cover가 된다. tye는 tie(카탈로그에 45번)에서도, the(20389)에서도 한 번의 편집 거리에 있으며, P(c)가 더 흔한 단어를 고르기 때문이다. 그리고 refrigerator with ice an water in door는 an을 그대로 둔다. 그 an은 실제 단어 오류(real-word error)다. 이는 "flew form Heathrow"처럼 모든 단어의 철자가 맞는 오타를 가리킨다(Manning et al., 2008). 두 경우 모두 문맥이 필요하다. tye와 an에 대해, 한 번의 편집 거리 안에 있는 각 카탈로그 단어가 질의의 다음 단어인 dye 또는 water 바로 앞에 얼마나 자주 오는지 센다.
1"""For the misspelled word in two test queries, `tye` and the real-word error `an`, counts how often each nearby catalog word comes before the query's next2word, and shows the context-free corrector's choice. The prose's point rests on the "catalog count of ... the3corrector's choice" lines."""4import re5from collections import Counter67from lib.queries import correct_word, edits1, word_counts8from lib.store import load_products, product_text910texts = product_text(load_products()).str.lower()11counts = word_counts(texts) # the corrector's lexicon12words_per_product = [re.findall(r"[a-z]+", text) for text in texts]13pairs = Counter(pair for words in words_per_product for pair in zip(words, words[1:])) # neighbouring words1415# tye in "tye dye duvet cover", an in "refrigerator with ice an water in door": each word, the word after it16for word, after in [("tye", "dye"), ("an", "water")]:17 # the typed word and each catalog word one edit away, ranked by how often each comes before the next word18 options = sorted(((pairs[(edit, after)], edit) for edit in edits1(word) | {word} if edit in counts), reverse=True)19 for count, edit in options[:3]:20 print(f"catalog count of {edit} {after}:", count)21 choice = correct_word(word, counts) # what the corrector without context picks22 print(f"the corrector's choice for {word}: {choice}")23 print(f"catalog count of {choice} {after}, the corrector's choice:", pairs[(choice, after)])
python spelling-context-counts.pycatalog count of tie dye: 18
catalog count of type dye: 0
catalog count of tyke dye: 0
the corrector's choice for tye: the
catalog count of the dye, the corrector's choice: 0
catalog count of and water: 59
catalog count of a water: 20
catalog count of in water: 9
the corrector's choice for an: an
catalog count of an water, the corrector's choice: 0
dye 앞에서 카탈로그 텍스트에는 tie 18번이 있고, 교정기가 고른 the는 0번이다. water 앞에서는 and가 59번 나와 a의 20번보다 앞서고, 교정기가 고른 an는 0번이다. 이 두 질의에서 각 후보를 이웃 단어와 함께 채점하는 교정기라면 tie와 and를 고를 것이다. 이제 교정된 각 질의를 그 질의 자체의 판정으로 채점할 수 있으며, 이로써 교정이 도움이 되는지 알 수 있다.
1"""Scores each typo query, and the variant spelling tye dye, with BM25, and with recorded embeddings where the corrected2text has one, as typed and as corrected. The prose's point rests on the nDCG@10 lines for queries 20 and 224 (train) and the corrected BM25 line for 459 (test)."""3from lib.lexical import LexicalSearch4from lib.metrics import ndcg_at_k5from lib.queries import correct_query, word_counts6from lib.recorded import probes7from lib.semantic import SemanticSearch8from lib.store import load_products, load_queries, product_text, qrels910products, queries, judgments = load_products(), load_queries(), qrels()11counts = word_counts(product_text(products))12bm25, semantic = LexicalSearch(products), SemanticSearch()13probe_queries, probe_vectors = probes() # recorded embeddings of the four typo queries, spelled correctly14spelling = probe_queries[probe_queries["kind"] == "spelling"]15# the probes' embeddings, keyed by the correctly spelled text, so a corrected query can find its own16spelled = {row["query"]: probe_vectors[index] for index, row in spelling.iterrows()}17typo_queries = spelling["of_query_id"].astype(int).tolist()18print("typo queries:", len(typo_queries))19print("of them, test queries:", (queries.loc[typo_queries, "split"] == "test").sum())2021for query_id in typo_queries + [459]: # the typo queries, then the one variant spelling, tye dye22 typed = queries.at[query_id, "query"]23 corrected = correct_query(typed, counts)24 label = f"{query_id} ({queries.at[query_id, 'split']})"25 print(f"{label}: {typed} -> {corrected}")26 for name, text in [("typed", typed), ("corrected", corrected)]:27 ranking = list(bm25.search(text, k=10).index)28 print(f"{label}, bm25 ndcg@10 {name}: {ndcg_at_k(ranking, judgments[query_id], 10):.3f}")29 if corrected == typed.lower():30 print(f"{label}: the corrector changes nothing")31 elif corrected in spelled:32 for name, vector in [("typed", semantic.query_vectors[query_id]), ("corrected", spelled[corrected])]:33 ranking = list(semantic.search_vector(vector, k=10).index)34 print(f"{label}, semantic ndcg@10 {name}: {ndcg_at_k(ranking, judgments[query_id], 10):.3f}")35 else:36 print(f"{label}: no recorded embedding of the corrected text")
python measure-spelling-corrections.pytypo queries: 4
of them, test queries: 1
305 (train): ligth bulb -> light bulb
305 (train), bm25 ndcg@10 typed: 0.945
305 (train), bm25 ndcg@10 corrected: 0.945
305 (train), semantic ndcg@10 typed: 1.000
305 (train), semantic ndcg@10 corrected: 1.000
20 (train): foutains with brick look -> fountains with brick look
20 (train), bm25 ndcg@10 typed: 0.356
20 (train), bm25 ndcg@10 corrected: 0.507
20 (train), semantic ndcg@10 typed: 0.353
20 (train), semantic ndcg@10 corrected: 0.645
224 (train): twin over full bunk beds cool desins -> twin over full bunk beds cool designs
224 (train), bm25 ndcg@10 typed: 0.488
224 (train), bm25 ndcg@10 corrected: 0.488
224 (train), semantic ndcg@10 typed: 0.565
224 (train), semantic ndcg@10 corrected: 0.616
406 (test): refrigerator with ice an water in door -> refrigerator with ice an water in door
406 (test), bm25 ndcg@10 typed: 0.501
406 (test), bm25 ndcg@10 corrected: 0.501
406 (test): the corrector changes nothing
459 (test): tye dye duvet cover -> the dye duvet cover
459 (test), bm25 ndcg@10 typed: 0.953
459 (test), bm25 ndcg@10 corrected: 0.953
459 (test): no recorded embedding of the corrected text
교정은 foutains with brick look(훈련)에서 가장 큰 효과를 낸다. 의미 기반 검색은 0.353에서 0.645으로, BM25는 0.356에서 0.507로 바뀐다.
나머지 두 훈련 오타 중 twin over full bunk beds cool desins는 의미 기반 검색만 0.565에서 0.616로 움직이고, ligth bulb는 어느 검색기도 움직이지 않는다. refrigerator with ice an water in door에서는 교정기가 아무것도 바꾸지 않으며, 올바르게 고쳐도 BM25에는 도움이 되지 않는다. 입력된 an과 올바른 and 중에서 bm25s는 an, and를 불용어로 버리며, and로 철자를 쓴 6장의 질의 사본은 0.501를 기록하여 입력된 그대로의 질의와 같다.
tye dye duvet cover에서는 the가 불용어이고 tye가 어떤 상품과도 일치하지 않으므로, 두 버전이 같은 용어를 검색하여 BM25가 어느 쪽이든 0.953를 기록한다. 의미 기반 검색은 교정된 텍스트로 채점할 수 없다. 녹화 자료에 그 텍스트의 임베딩이 없기 때문이다. 이 상점에는 오타 질의가 4개 있고 그중 1개가 테스트 질의이며, 이렇게 적은 수로 얻을 수 있는 가장 작은 양측 순열 p-값은 0.125이다.
작업 규칙: 어휘 목록은 카탈로그로 만들고, 질의 로그가 생기면 그것으로도 만들며, 어휘 목록에 없는 단어만 교정하여 브랜드 이름이 살아남게 하라. 단어를 교정하기 전에 이웃 단어를 확인하라. 문맥 없는 교정기는 변형 철자를 흔한 단어로 바꾸고 실제 단어 오류를 놓친다. 각 교정은 오타 질의 자체의 판정으로 채점하고, 교정기를 시험하기 전에 이 상점이 가진 것보다 훨씬 많은 오타 질의를 모아라.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Normalize units the way the catalog writes them
A typo has one right spelling; a size, as in 7qt slow cooker, often has several. Normalization maps the different ways of writing one thing to a single form, on the products and on the query alike. Sizes in this catalog need it. Chapter 5 found that 7qt and 7 qt never match each other, because the tokenizer drops the one-character 7. A normalizer that joins each number to its unit, written one way, turns both into one term, 7qt. It has to run on the product text when you build the index, and on every query. It also has to produce terms the tokenizer keeps whole. The tokenizer splits words at a decimal point, so 3.7qt would become 7qt. To prevent that, the shared function lib.queries.normalize_units writes the point as an underscore, which the tokenizer keeps inside a word. It also leaves in alone when a number or one follows, as in 3 in 1.
A rule written from the queries would cover qt, in, inch and ". Before you trust it, count how the catalog writes inches. We count them first, print the terms the tokenizer makes of a few normalized texts, and build BM25 three times: over the text as written, normalized by that first rule, and normalized by normalize_units, which also handles the catalog's two apostrophes, '', for inches. We score every query, train or test, that gives a number with a unit:
1"""Counts how the catalog writes inches, prints the terms the tokenizer makes of normalized texts, and scores BM25 on2every query with a unit under three rules. The prose's point rests on the "bm25 ndcg@10" lines for queries 62 and 482."""3from lib.lexical import LexicalSearch4from lib.lexical_by_hand import tokenize5from lib.metrics import ndcg_at_k6from lib.queries import INCH_SPELLINGS, normalize_units, unit_rules7from lib.store import load_products, load_queries, product_text, qrels89products, queries, judgments = load_products(), load_queries(), qrels()10text = product_text(products).str.lower()11# the catalog's spellings of inches after a number; -? also takes a hyphen, as in 48-inch12for name, unit in [("''", r"''"), ('"', r"\""), ("inch", r"-?inch")]:13 print(f"products that write a number then {name}:", text.str.contains(rf"\d\s*{unit}").sum())1415# the first rule, written from the queries' units: lib's inch spellings (inches, inch, in, ") without the two apostrophes; quarts are always included16first_try = unit_rules([spelling for spelling in INCH_SPELLINGS if spelling != "''"]) # written from queries17# None leaves the text as written, with no normalization18rules = {"as written": None, "first try": first_try, "normalized": unit_rules()}19checks = [("3.7-quart slow cooker", "normalized"), ("3 in 1 sofa bed", "normalized"), ("1 in twin", "normalized"),20 ("48 '' range hood", "first try"), ("48 '' range hood", "normalized")]21for example, name in checks: # what the tokenizer reads22 print(f"terms of {example}, {name}:", " ".join(tokenize(normalize_units(example, rules[name]))))2324searches = {}25for name, rule in rules.items():26 rewritten = products.copy()27 if rule is not None:28 for column in ["name", "product_class", "category", "description"]: # the columns product_text joins29 rewritten[column] = rewritten[column].map(lambda value: normalize_units(value, rule))30 searches[name] = LexicalSearch(rewritten)3132# queries with a number and a unit: qt, in, inch or a double quote33with_units = queries[queries["query"].str.contains(r"\d\s*(?:qt|in\b|inch|\")")]34print("queries with a unit:", len(with_units))35print("of them, test queries:", (with_units["split"] == "test").sum())36for query_id, query in with_units["query"].items():37 label = f"{query_id} ({queries.at[query_id, 'split']})"38 print(f"{label}: {query} -> {normalize_units(query)}")39 for name, rule in rules.items():40 typed = query if rule is None else normalize_units(query, rule)41 ranking = list(searches[name].search(typed, k=10).index)42 print(f"{label}, bm25 ndcg@10 {name}: {ndcg_at_k(ranking, judgments[query_id], 10):.3f}")
python normalize-units-both-sides.pyproducts that write a number then '': 3014
products that write a number then ": 65
products that write a number then inch: 215
terms of 3.7-quart slow cooker, normalized: 3_7qt slow cooker
terms of 3 in 1 sofa bed, normalized: sofa bed
terms of 1 in twin, normalized: 1in twin
terms of 48 '' range hood, first try: 48 range hood
terms of 48 '' range hood, normalized: 48in range hood
queries with a unit: 4
of them, test queries: 2
62 (train): 7qt slow cooker -> 7qt slow cooker
62 (train), bm25 ndcg@10 as written: 0.554
62 (train), bm25 ndcg@10 first try: 0.930
62 (train), bm25 ndcg@10 normalized: 0.930
101 (train): 48 in entry table with side by side drawer -> 48in entry table with side by side drawer
101 (train), bm25 ndcg@10 as written: 0.569
101 (train), bm25 ndcg@10 first try: 0.569
101 (train), bm25 ndcg@10 normalized: 0.569
285 (test): 48" sliding single track , barn door for laundry -> 48in sliding single track , barn door for laundry
285 (test), bm25 ndcg@10 as written: 0.592
285 (test), bm25 ndcg@10 first try: 0.592
285 (test), bm25 ndcg@10 normalized: 0.592
482 (test): 48 inch kitchen hood -> 48in kitchen hood
482 (test), bm25 ndcg@10 as written: 1.000
482 (test), bm25 ndcg@10 first try: 0.824
482 (test), bm25 ndcg@10 normalized: 1.000
The catalog's usual way to write inches is the one a rule written from the queries misses: two apostrophes after a number, in 3014 products, against 65 for " and 215 for inch.
The tokenizer reads 3.7-quart slow cooker, normalized, as 3_7qt slow cooker, and 3 in 1 sofa bed as sofa bed. normalize_units still misreads 1 in twin as 1in twin, which is why the terms are worth printing.
Normalizing lifts the train query 7qt slow cooker: BM25's nDCG@10 goes from 0.554 to 0.930, and the first rule gives 0.930. The test query 48 inch kitchen hood shows what the first rule loses by missing the two apostrophes. It scores 1.000 as written and 0.824 under the first rule. The query becomes 48in, while the first rule leaves a hood written 48 '' as 48 range hood, and the full rule makes it 48in range hood. With the full rule, the hood query scores 1.000.
The other train query, 48 in entry table with side by side drawer, scores 0.569 as written and 0.569 normalized, and the test query about a sliding barn door scores 0.592 and 0.592. That makes 4 queries with a unit, 2 of them test queries: too few to test.
Working rule: Write normalization rules from the catalog's text, not from the queries, by counting every way it writes each unit. Print the terms the tokenizer makes of the normalized text, because a rule that looks right can produce terms that match the wrong products. Apply the same rules to products and queries in one release, and rebuild the index. When the catalog keeps sizes in fields, such as the width in attributes, match the size against the field instead, as chapter 6 suggests.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Expand queries with a synonym list
Some gaps are neither typos nor units but different words for one thing, as when the exact products for midcentury tv unit say stand. Query expansion adds terms to a query so that it can match products that use other words for the same thing. Expansion generally increases recall, the share of the relevant products that a search finds (Manning et al., 2008). It can also significantly decrease precision, the share of found products that are relevant, particularly when the query contains ambiguous terms (Manning et al., 2008). A word that expansion adds can match products the shopper didn't ask for, and move the query away from its meaning, which is called query drift. Expansion terms can come from a hand-built list of synonyms, or from the results. Pseudo-relevance feedback assumes the top results are relevant and adds their terms to the query, which makes drift its known risk (Manning et al., 2008).
Here lib.queries.SYNONYMS holds 14 groups of interchangeable words, such as stand and unit, written by reading the train queries whose exact products miss a query word. When a query contains a word or phrase from a group, expand appends the group's other members, and BM25 searches the result. Measure it on the train queries, then make the first of the chapter's planned comparisons on the test queries:
1"""Expands each query with the synonym list, scores BM25 on the train and test queries as typed and expanded, and2runs the list's planned test comparison. The prose's point rests on the "synonyms, bm25" lines of that comparison."""3from lib.lexical import LexicalSearch4from lib.metrics import evaluate5from lib.queries import PLANNED_TEST_COMPARISONS, SYNONYMS, THRESHOLD, expand, report_planned6from lib.store import load_products, load_queries, qrels78products, judgments = load_products(), qrels()9bm25 = LexicalSearch(products)10print("synonym groups:", len(SYNONYMS))11scores = {}12for split in ["train", "test"]:13 queries = load_queries(split)14 expanded = queries.assign(query=queries["query"].map(expand))15 changed = queries.index[expanded["query"] != queries["query"]]16 print(f"{split} queries the list changes:", len(changed))17 for name, frame in [("typed", queries), ("expanded", expanded)]:18 scores[split, name] = evaluate(bm25.run(frame), qrels(split))19 print(f"{split} ndcg@10 {name}: {scores[split, name]['ndcg@10'].mean():.3f}")20 print(f"{split} judged@10 {name}: {scores[split, name]['judged@10'].mean():.3f}")21for query in queries.loc[changed, "query"]: # the test queries the list changes22 print(f"test query changed: {query}")23 # expand returns the query, a space, then the added words, so this slice keeps only the added words24 print(f"words the list adds to it: {expand(query)[len(query) + 1:]}")2526change = (scores["train", "expanded"]["ndcg@10"] - scores["train", "typed"]["ndcg@10"]).round(3)27print(f"train queries better, worse: {(change > 0).sum()}, {(change < 0).sum()}") # for choosing, not evidence28print(f"share of the net train gain from the largest gain: {change.max() / change.sum():.3f}")29for kind, query_id in [("gain", change.idxmax()), ("loss", change.idxmin())]:30 query = load_queries().at[query_id, "query"]31 # the same slice: everything after the query and the space that expand puts between them32 added = expand(query)[len(query) + 1:]33 print(f"largest train {kind}: {query}")34 print(f"largest train {kind}, words added: {added}")35 print(f"largest train {kind}, change: {change[query_id]:+.3f}")36named = [product_id for product_id in bm25.search(expand(query), k=10).index if added in products.at[product_id, "name"]]37print(f"largest train loss, top 10 names with {added}:", len(named)) # query and added: the largest loss's38print("largest train loss, of those, unjudged:", sum(product_id not in judgments[query_id] for product_id in named))3940print("\nplanned test comparisons:", len(PLANNED_TEST_COMPARISONS))41print(f"p-value threshold: {THRESHOLD:.2f}")42report_planned("synonyms, bm25", scores["test", "expanded"]["ndcg@10"], scores["test", "typed"]["ndcg@10"])
python synonym-expansion-train-and-test.pysynonym groups: 14
train queries the list changes: 14
train ndcg@10 typed: 0.695
train judged@10 typed: 0.930
train ndcg@10 expanded: 0.722
train judged@10 expanded: 0.944
test queries the list changes: 1
test ndcg@10 typed: 0.725
test judged@10 typed: 0.927
test ndcg@10 expanded: 0.725
test judged@10 expanded: 0.927
test query changed: indoor multi tiered plant stand
words the list adds to it: unit
train queries better, worse: 6, 5
share of the net train gain from the largest gain: 0.473
largest train gain: midcentury tv unit
largest train gain, words added: stand mid century
largest train gain, change: +0.632
largest train loss: wire basket with dividers
largest train loss, words added: hamper
largest train loss, change: -0.176
largest train loss, top 10 names with hamper: 4
largest train loss, of those, unjudged: 4
planned test comparisons: 5
p-value threshold: 0.01
synonyms, bm25, mean difference: 0.000
synonyms, bm25, wins, losses, ties: 0, 0, 30
synonyms, bm25, permutation p: 1.000
synonyms, bm25, established at 0.01: no
synonyms, bm25, t-test p: 1.000
synonyms, bm25, t-test agrees: yes
synonyms, bm25, 99% interval: 0.000 to 0.000
synonyms, bm25, interval agrees: yes
The list changes 14 train queries. Mean nDCG@10 goes from 0.695 to 0.722, and judged@10, the share of the top 10 with a judgment, rises too, from 0.930 to 0.944.
Of the changed train queries, 6, 5 score better and worse, respectively, and one query, midcentury tv unit, accounts for 0.473 of the net gain, gaining +0.632 with stand mid century added. The list was written from these queries, so even these numbers flatter it.
The largest loss, -0.176, shows drift: wire basket with dividers gets hamper, and 4 products whose names contain hamper enter its top 10. Of those, 4 are unjudged, so the metric counts them as irrelevant, which for hampers is a fair guess.
On the test queries, the list changes 1 query, indoor multi tiered plant stand, by adding unit. Judged@10 stays at 0.927, and the difference isn't established (planned comparisons). On the queries it was written from, the list helped about as many queries as it hurt, and queries it wasn't written for rarely contain its words.
Working rule: Keep a synonym list for vocabulary gaps you have seen, write each entry from a failing query, and read the products each entry adds before you keep it. Never report a list's gain on the queries you wrote it from, and keep an entry only if a planned comparison on the test queries shows a gain. Test any expansion of semantic retrieval first: the LLM's rewrites, which add synonyms and also broaden and drop words, hurt it. When the gaps are too many to list, try stemming or learned sparse retrieval instead.
상품 텍스트로 질의 분류기 학습하기
시스템은 질의의 단어를 바꾸는 대신, 질의가 어떤 종류의 상품을 찾는지 예측할 수 있다. 질의 분류(query classification)는 질의를 Range Hoods와 같이 매장의 분류 체계에 속한 클래스에 배정한다. 상품 검색에서 "질의를 미리 정의된 상품 분류 체계에 매핑하는 일은 이커머스 질의 이해 파이프라인의 중요한 단계"이며(Skinner and Kallumadi, 2019), 예측된 클래스는 검색을 카탈로그의 알맞은 영역으로 이끌 수 있다. 분류기를 학습하려면 보통 레이블이 달린 질의가 필요하다. Skinner와 Kallumadi는 기존의 상품 분류 체계 매핑이 질의 분류를 개선하고 레이블 데이터의 필요를 줄일 수 있다고 보고한다. 이들은 클래스가 알려진 상품 제목으로 먼저 사전 학습한 뒤, 더 적은 수의 레이블 질의로 미세 조정한다.
이 매장은 한 걸음 더 나아가 레이블이 달린 질의를 전혀 쓰지 않는다. 가진 것이 없기 때문이다. WANDS는 각 질의에 "질의가 속하는 범주"인 query_class를 부여하지만(WANDS), 2장은 이 값이 예측이며 일부는 틀렸음을 보여 준다. 또한 이 책이 사용하는 WANDS 표본은 클래스마다 질의를 많아야 하나만 담고 있어(examples/data/wands/README.md), 학습할 질의가 두 개 이상인 클래스가 없다. 그래서 product_class를 가진 상품으로 학습하고, 그 분류기를 질의에 적용한다.
나이브 베이즈(naive Bayes) 분류기는 상품 텍스트에서 클래스를 몇 줄로 학습할 수 있다. 말로 풀면, 나이브 베이즈는 어떤 클래스가 상품들 사이에서 흔하고 질의의 단어가 그 클래스의 상품 텍스트에서 흔할 때 그 클래스를 질의에 어울린다고 본다. 단어를 서로 독립으로 취급하는데, 이것이 "naive"(순진하다)는 이름의 까닭이다. 어떤 클래스에서 한 번도 보지 못한 단어가 그 클래스를 배제하지 않도록, 각 횟수에 1을 더한다.
predicted class = argmax over classes c of log P(c) + sum over the query's words w of log P(w | c)
P(w | c) = (count of w in class c's text + 1) / (number of words in class c's text + vocabulary size)
상품 텍스트의 단어 수로 이를 직접 구현하고, 1.9.1 버전 scikit-learn의 MultinomialNB와 결과를 대조한 다음, 예측을 query_class와, 그리고 각 질의의 정확(exact) 상품이 가진 클래스와 비교한다.
1"""A naive Bayes query classifier built by hand from product text, checked against scikit-learn's MultinomialNB and2compared with each query's exact products. The prose's point rests on the two "queries where most exact products3have" lines and on the agreement line with MultinomialNB."""4import numpy as np56from lib.queries import class_rows, train_classifier7from lib.store import load_labels, load_products, load_queries, product_text89products, queries, labels = load_products(), load_queries(), load_labels()10rows = class_rows(products) # one row per (product, class) for products with a class11vectorizer, model = train_classifier(products) # the same, by scikit-learn's MultinomialNB12words = vectorizer.transform(product_text(rows)) # word counts: one row per (product, class), one column per word13classes = np.array(sorted(rows["label"].unique()))14print("product classes:", len(classes))15print("products without a class:", (products["product_class"] == "").sum())16print("products with several classes:", products["product_class"].str.contains("|", regex=False).sum())17# query classes whose name matches no product class18missing = queries["query_class"].dropna()[lambda names: ~names.isin(classes)]19print("query classes that no product has:", len(missing))20print("query classes that no product has, names:", "; ".join(missing))2122# Naive Bayes: log P(class) + sum over the query's words of log P(word | class), each word count smoothed by 123word_counts = np.vstack([np.asarray(words[(rows["label"] == name).to_numpy()].sum(axis=0)) for name in classes])24log_prior = np.log(rows["label"].value_counts()[classes].to_numpy() / len(rows))25log_likelihood = np.log((word_counts + 1) / (word_counts.sum(axis=1, keepdims=True) + word_counts.shape[1]))26query_words = vectorizer.transform(queries["query"])27predicted = classes[np.asarray(query_words @ log_likelihood.T + log_prior).argmax(axis=1)]28print("same predictions as MultinomialNB:", (predicted == model.predict(query_words)).sum(), "of", len(queries))2930queries = queries.assign(predicted=predicted)31print("predicted class equals query_class:", (queries["predicted"] == queries["query_class"]).sum())32# judgment grade 2 is exact; a product's classes are joined by |, so they're split before matching33exact = labels[labels["grade"] == 2].join(products["product_class"].str.split("|"), on="product_id")34for column, name in [("predicted", "predicted class"), ("query_class", "query_class")]:35 share = [exact.loc[exact["query_id"] == query_id, "product_class"].apply(lambda names: label in names).mean()36 for query_id, label in queries[column].items()]37 print(f"queries where most exact products have the {name}:", (np.array(share) > 0.5).sum())38# outdoor light fixtures, desk and chair set, and pool floats39for query_id in [133, 255, 410]:40 query, split, label = queries.loc[query_id, ["query", "split", "predicted"]]41 print(f"{query_id} ({split}): {query} -> {label}"42 f" (query_class: {queries.at[query_id, 'query_class']})")43print("predicted class for 7qt slow cooker:", queries.at[62, "predicted"]) # its query_class has no products
python query-classes-by-hand.pyproduct classes: 410
products without a class: 800
products with several classes: 620
query classes that no product has: 1
query classes that no product has, names: Crock Pots & Slow Cookers
same predictions as MultinomialNB: 80 of 80
predicted class equals query_class: 60
queries where most exact products have the predicted class: 63
queries where most exact products have the query_class: 63
133 (test): outdoor light fixtures -> Light Bulbs (query_class: Outdoor Wall Lights)
255 (test): desk and chair set -> Desks (query_class: Office Chairs)
410 (train): pool floats -> Deck Boxes (query_class: Lawn Games)
predicted class for 7qt slow cooker: Slow Cookers
상품은 410개의 클래스를 사용한다. 클래스가 없는 상품 800개는 제외하며, 클래스가 여러 개인 상품 620개는 클래스마다 학습 행을 하나씩 만든다.
직접 만든 분류기는 80 of 80개 질의에서 MultinomialNB와 같은 예측을 한다. 그 예측은 그중 60개에서 query_class와 같지만, query_class도 하나의 추측일 뿐이다. 판정과 대조하면 두 추측은 비긴다. 정확 상품 대부분이 예측 클래스를 가진 질의는 63개이고, 정확 상품 대부분이 query_class를 가진 질의는 63개이다. 예측 가운데 세 가지는 이 분류기가 질의를 오직 단어만으로 읽는 방식을 보여 준다. outdoor light fixtures은 Light Bulbs가 되고, desk and chair set은 Desks가 되며, pool floats은 Deck Boxes가 된다.
표본의 설계는 이 검사가 보여 줄 수 있는 것을 제한한다. 각 클래스는 많아야 질의 하나로 검증되므로 클래스별 정확도는 측정할 수 없고, 80개의 질의는 410개 클래스 중 일부만 다루므로 나머지 클래스에 대해서는 이 수치가 아무것도 말해 주지 않는다. 이 질의들로는 질의 분류기를 학습할 수 없고, 두 분류기는 이 소수의 질의를 각각 맞히는지만으로 비교할 수 있다. 또한 질의 클래스 1개, 곧 Crock Pots & Slow Cookers은 어떤 상품 클래스도 가리키지 않으므로, 상품으로 학습한 분류기는 이를 예측할 수 없다.
작업 규칙: 레이블이 달린 질의가 없을 때는 상품의 클래스로 질의 분류기를 학습하고, 다른 분류기의 추측이 아니라 판정이 내려진 정확 상품의 클래스와 대조해 검증한다. 로그에서 레이블이 달린 질의를 얻게 되면 그것으로 학습한다. 예측된 클래스는 순위 결정을 위한 힌트로 다루고, 레이블로 취급하지 않는다.
필터링 대신 예측된 클래스를 부스트한다
여기서 예측된 클래스는 상품 텍스트로 학습한 나이브 베이즈 분류기에서 나온다. 예측된 클래스는 두 가지 방식으로 검색에 작용할 수 있다. 필터는 예측된 클래스에 속한 상품만 남긴다. 부스트는 예측된 클래스에 속한 상품의 점수에 고정된 값을 더하므로, 다른 상품을 제거하지 않고도 해당 상품이 위로 올라간다. 필터는 분류기의 성능만큼만 쓸모가 있다. 예측된 클래스 밖에 있는 관련 상품은 모두 사라지기 때문이다.
스토어의 학습 판정은 필터가 얼마나 손해를 일으키는지 보여 준다. 학습 질의에서 정확한 상품 501 of 1937개가 해당 질의의 예측된 클래스 밖에 있다. 스토어에서 가장 좋은 랭커이자 이겨야 할 랭커인 시맨틱 검색의 유사도에 부스트를 더하고, 학습 질의에서 다섯 가지 부스트 가중치와 필터 하나를 시험한다. 이 장의 두 번째 계획된 비교를 위해 가장 좋은 부스트를 테스트 질의에 적용한다.
1"""Counts the exact train products outside each query's predicted class, scores a class filter and several boosts on2the train queries, and takes the best boost to the test queries as a planned comparison. The prose's point rests on3the "exact train products outside the predicted class" line and on the planned comparison's lines."""4from lib.metrics import evaluate5from lib.queries import THRESHOLD, class_boost_run, in_class, report_planned, train_classifier6from lib.semantic import SemanticSearch7from lib.store import load_products, load_queries, qrels89products, queries = load_products(), load_queries()10vectorizer, model = train_classifier(products) # trained on product text, never on queries11predicted = dict(zip(queries.index, model.predict(vectorizer.transform(queries["query"]))))12semantic = SemanticSearch()13train, train_judgments = load_queries("train"), qrels("train")1415exact, outside = 0, 016for query_id, judged in train_judgments.items():17 member = in_class(products, predicted[query_id])18 exact += sum(grade == 2 for grade in judged.values())19 outside += sum(grade == 2 and not member[product_id] for product_id, grade in judged.items())20print(f"exact train products outside the predicted class: {outside} of {exact}")2122base = evaluate(semantic.run(train), train_judgments)23print(f"train ndcg@10 semantic: {base['ndcg@10'].mean():.3f}")24print(f"train judged@10 semantic: {base['judged@10'].mean():.3f}")25train_scores = {}26for weight in [None, 0.01, 0.02, 0.05, 0.1, 0.2]: # None: keep only the predicted class27 train_scores[weight] = evaluate(class_boost_run(semantic, train.index, predicted, products, weight), train_judgments)28 name = "filter" if weight is None else f"boost {weight}"29 print(f"train ndcg@10 {name}: {train_scores[weight]['ndcg@10'].mean():.3f}")30# every weight except None, the filter31boosts = [weight for weight in train_scores if weight is not None]32best = max(boosts, key=lambda weight: train_scores[weight]["ndcg@10"].mean())33for name, weight in [("filter", None), ("best boost", best)]:34 print(f"train judged@10 {name}: {train_scores[weight]['judged@10'].mean():.3f}")35print("best boost on train:", best)3637print(f"\nthe planned test comparison, threshold {THRESHOLD:.2f}:")38test, test_judgments = load_queries("test"), qrels("test")39boosted = evaluate(class_boost_run(semantic, test.index, predicted, products, best), test_judgments)40plain = evaluate(semantic.run(test), test_judgments)41print(f"test judged@10 semantic: {plain['judged@10'].mean():.3f}")42print(f"test judged@10 boosted: {boosted['judged@10'].mean():.3f}")43report_planned("class boost, semantic", boosted["ndcg@10"], plain["ndcg@10"])
python class-boost-train-and-test.pyexact train products outside the predicted class: 501 of 1937
train ndcg@10 semantic: 0.772
train judged@10 semantic: 0.964
train ndcg@10 filter: 0.675
train ndcg@10 boost 0.01: 0.773
train ndcg@10 boost 0.02: 0.774
train ndcg@10 boost 0.05: 0.768
train ndcg@10 boost 0.1: 0.742
train ndcg@10 boost 0.2: 0.692
train judged@10 filter: 0.866
train judged@10 best boost: 0.966
best boost on train: 0.02
the planned test comparison, threshold 0.01:
test judged@10 semantic: 0.990
test judged@10 boosted: 0.993
class boost, semantic, mean difference: 0.005
class boost, semantic, wins, losses, ties: 7, 4, 19
class boost, semantic, permutation p: 0.174
class boost, semantic, established at 0.01: no
class boost, semantic, t-test p: 0.164
class boost, semantic, t-test agrees: yes
class boost, semantic, 99% interval: -0.002 to 0.017
class boost, semantic, interval agrees: yes
학습 질의에서 필터는 단순 랭커보다 성능이 나쁘다. nDCG@10은 0.772에서 0.675로, judged@10은 0.964에서 0.866로 떨어지며, 따라서 상위 10개에도 아무도 판정하지 않은 상품이 많이 채워진다.
작은 부스트는 학습 점수를 거의 움직이지 못하고, 큰 부스트는 점수를 떨어뜨린다. nDCG@10은 0.01에서 0.773, 0.2에서 0.692이다. 학습에서 가장 좋은 부스트는 0.02이며, 이때 nDCG@10은 0.774이고 judged@10은 0.966이다.
테스트 질의에서 judged@10은 부스트가 없을 때 0.990, 있을 때 0.993이며, 부스트의 이득은 입증되지 않았다(계획된 비교).
작업 규칙: 예측된 클래스로 필터링하지 않는다. 학습 질의에서 조정한 가중치로 부스트하고, 계획된 비교에서 이득이 입증된 경우에만 부스트를 유지한다. 이 스토어의 부스트는 입증되지 않았으므로 시맨틱 검색에는 부스트를 적용하지 않는다. 클래스 필터는 쇼핑하는 사람이 직접 클래스를 고른 경우, 예를 들어 카테고리를 클릭한 경우에만 권장한다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Rewrite queries with an LLM
Query rewriting replaces the query with a text written to retrieve better. Where the corrector, the unit rules and the synonym list each fix one kind of gap, an LLM can fix spelling, expand abbreviations and add synonyms in one step, with no list to maintain. In rewrite-retrieve-read, the rewritten query goes to the retriever in place of the original (Ma et al., 2023). Studies report gains. With query2doc, which appends an LLM-written passage, a pseudo-document, to the query, BM25 improved by 3% to 15% on ad-hoc IR datasets, with text-davinci-003 writing the passages for MS MARCO and TREC DL queries (Wang et al., 2023). Other studies report failures. A comparison of 11 expansion methods, 12 datasets and 24 retrievers found that expansion helps weaker models and generally harms stronger ones (Weller et al., 2024). Another study found that LLM-based expansion can significantly degrade retrieval when the LLM lacks the knowledge or the query is highly ambiguous (Abe et al., 2025).
The rewrites that the examples read were recorded with the store's LLM, the open model named in the chapter's opening, run locally on each query alone. The prompt's instruction is: "Rewrite this search query from an online furniture and home-goods store so that a search engine finds what the shopper wants. Fix spelling, expand abbreviations and add common synonyms for the product type, but keep every requirement the shopper stated and add none of your own. Return a single line." The rest of the prompt gives the query and asks for JSON, and the recording's manifest holds it in full. The recording script embedded each rewrite as a query, with the same embedding model as the products. BM25 searches the rewrite's text, and semantic retrieval its embedding. The train queries come first, to see what the rewrites change before any test:
1"""Prints the store's recorded LLM rewrites for a few train queries, then scores BM25 and semantic retrieval on the2train queries, typed and rewritten. The prose's point rests on the nDCG@10 lines for both retrievers."""3from lib.lexical import LexicalSearch4from lib.metrics import evaluate5from lib.recorded import llm_rewrites, manifest6from lib.semantic import SemanticSearch7from lib.store import load_products, load_queries, qrels89recording = manifest("llm-rewrites")10print("model:", recording["model"])11print("embedding model:", recording["embedding_model"])12print("rewrite prompt, first line:", recording["prompts"]["rewrite"].split("\n")[0])13table, rewrite_vectors, _ = llm_rewrites()14rewrites = table.set_index("query_id")["rewrite"]15# the embeddings come in the table's row order, not query order: row maps each query_id to its row16row = {query_id: position for position, query_id in enumerate(table["query_id"])}17# a spelling fix, a product code, and malachi sled18for query_id in [20, 205, 313]:19 print(f"rewrite of {load_queries().at[query_id, 'query']}: {rewrites[query_id]}")2021queries, judgments = load_queries("train"), qrels("train")22products = load_products()23# judgment grade 2 is exact24exact = [product_id for product_id, grade in judgments[313].items() if grade == 2]25print("exact products for malachi sled:", "; ".join(products.loc[exact, "name"]))26bm25, semantic = LexicalSearch(products), SemanticSearch()27runs = {"bm25, typed": bm25.run(queries),28 "bm25, rewrite": bm25.run(queries.assign(query=rewrites[queries.index].to_numpy())),29 "semantic, typed": semantic.run(queries),30 "semantic, rewrite": {query_id: list(semantic.search_vector(rewrite_vectors[row[query_id]]).index)31 for query_id in queries.index}}32scores = {name: evaluate(run, judgments) for name, run in runs.items()}33for name, frame in scores.items():34 print(f"train ndcg@10 {name}: {frame['ndcg@10'].mean():.3f}")35 print(f"train judged@10 {name}: {frame['judged@10'].mean():.3f}")36for retriever in ["bm25", "semantic"]: # for choosing, not evidence37 change = (scores[f"{retriever}, rewrite"]["ndcg@10"] - scores[f"{retriever}, typed"]["ndcg@10"]).round(3)38 print(f"train queries better, worse, {retriever}: {(change > 0).sum()}, {(change < 0).sum()}")39 print(f"largest train loss, {retriever}: {queries.at[change.idxmin(), 'query']}")40 print(f"largest train loss, {retriever}, change: {change.min():+.3f}")
python llm-rewrites-on-train.pymodel: gemma4:12b-it-q4_K_M
embedding model: Snowflake/snowflake-arctic-embed-m-v1.5
rewrite prompt, first line: Rewrite this search query from an online furniture and home-goods store so that a search engine finds what the shopper wants. Fix spelling, expand abbreviations and add common synonyms for the product type, but keep every requirement the shopper stated and add none of your own. Return a single line.
rewrite of foutains with brick look: fountains with brick look, brick style water features, masonry fountains, faux brick fountains
rewrite of ines shag rug w003096809: Ines shag rug w003096809 area rug carpet
rewrite of malachi sled: Malachi sled sofa couch settee loveseat
exact products for malachi sled: malachi sled end table; malachi 44 '' console table; malachi sled coffee table
train ndcg@10 bm25, typed: 0.695
train judged@10 bm25, typed: 0.930
train ndcg@10 bm25, rewrite: 0.646
train judged@10 bm25, rewrite: 0.868
train ndcg@10 semantic, typed: 0.772
train judged@10 semantic, typed: 0.964
train ndcg@10 semantic, rewrite: 0.759
train judged@10 semantic, rewrite: 0.924
train queries better, worse, bm25: 23, 24
largest train loss, bm25: malachi sled
largest train loss, bm25, change: -0.644
train queries better, worse, semantic: 18, 25
largest train loss, semantic: wall design shelf
largest train loss, semantic, change: -0.653
Spelling comes out right (fountains with brick look, brick style water features, masonry fountains, faux brick fountains), and codes survive (Ines shag rug w003096809 area rug carpet). For malachi sled, a product line, the LLM guessed a sofa: it wrote Malachi sled sofa couch settee loveseat, while the exact products are malachi sled end table; malachi 44 '' console table; malachi sled coffee table.
On the train queries, the rewrite lowers nDCG@10 for both retrievers: BM25 from 0.695 to 0.646, and semantic retrieval from 0.772 to 0.759. Judged@10 falls for both, from 0.930 to 0.868 and from 0.964 to 0.924, so the rewrites surface products nobody judged, and part of each fall in nDCG@10 may come from them.
The losses aren't one bad query: the numbers of queries that score better and worse are 23, 24 for BM25 and 18, 25 for semantic retrieval. BM25's largest loss is malachi sled, the product line the LLM turned into a sofa, at -0.644, and semantic retrieval's is wall design shelf, at -0.653.
These train numbers shape expectations and prove nothing. The third and fourth of the chapter's 5 planned comparisons were fixed in advance, so they go to the test queries whatever the train queries show, and each counts as established if p is below 0.01. Before the test numbers arrive, pick one: does the rewrite help BM25, the weaker retriever, hurt semantic retrieval, the stronger one, or do neither?
1"""Scores BM25 and semantic retrieval on the test queries, as typed and rewritten, as the chapter's planned comparisons,2then repeats both on condensed runs as an exploratory check. The prose's point rests on the "established at 0.01" lines."""3from lib.lexical import LexicalSearch4from lib.metrics import evaluate5from lib.queries import THRESHOLD, condensed, report_planned, rewrite_runs6from lib.semantic import SemanticSearch7from lib.significance import compare8from lib.store import load_products, load_queries, qrels910queries, judgments = load_queries("test"), qrels("test") # scored on the human judgments11# for each retriever, its run on the rewrite, then its run on the query as typed12runs = rewrite_runs(queries, LexicalSearch(load_products()), SemanticSearch())1314print(f"the planned test comparisons, threshold {THRESHOLD:.2f}:")15for retriever, (rewritten, typed) in runs.items():16 name = f"llm rewrite, {retriever}"17 after, before = evaluate(rewritten, judgments), evaluate(typed, judgments)18 for form, frame in [("typed", before), ("rewrite", after)]:19 print(f"{name}, test ndcg@10 {form}: {frame['ndcg@10'].mean():.3f}")20 print(f"{name}, test judged@10 {form}: {frame['judged@10'].mean():.3f}")21 report_planned(name, after["ndcg@10"], before["ndcg@10"])2223 # Exploratory, never established: the same comparison on condensed runs, which drop unjudged products24 # rewritten comes first in each pair, as rewrite_runs returns them; the rewrite is "after"25 after, before = (evaluate(condensed(run, judgments), judgments)["ndcg@10"] for run in (rewritten, typed))26 # confidence = 1 - THRESHOLD: a 99% interval, at the level the planned comparisons use27 result = compare(after, before, confidence=1 - THRESHOLD)28 print(f"{name}, condensed ndcg@10 typed: {before.mean():.3f}")29 print(f"{name}, condensed ndcg@10 rewrite: {after.mean():.3f}")30 print(f"{name}, condensed, exploratory mean difference: {result['mean difference']:.3f}")31 print(f"{name}, condensed, exploratory permutation p: {result['permutation p']:.3f}")32 low, high = result["ci low"], result["ci high"]33 print(f"{name}, condensed, exploratory {1 - THRESHOLD:.0%} interval: {low:.3f} to {high:.3f}")
python llm-rewrites-on-test.pythe planned test comparisons, threshold 0.01:
llm rewrite, bm25, test ndcg@10 typed: 0.725
llm rewrite, bm25, test judged@10 typed: 0.927
llm rewrite, bm25, test ndcg@10 rewrite: 0.669
llm rewrite, bm25, test judged@10 rewrite: 0.903
llm rewrite, bm25, mean difference: -0.056
llm rewrite, bm25, wins, losses, ties: 13, 15, 2
llm rewrite, bm25, permutation p: 0.060
llm rewrite, bm25, established at 0.01: no
llm rewrite, bm25, t-test p: 0.060
llm rewrite, bm25, t-test agrees: yes
llm rewrite, bm25, 99% interval: -0.143 to 0.005
llm rewrite, bm25, interval agrees: yes
llm rewrite, bm25, condensed ndcg@10 typed: 0.778
llm rewrite, bm25, condensed ndcg@10 rewrite: 0.725
llm rewrite, bm25, condensed, exploratory mean difference: -0.053
llm rewrite, bm25, condensed, exploratory permutation p: 0.044
llm rewrite, bm25, condensed, exploratory 99% interval: -0.150 to -0.002
llm rewrite, semantic, test ndcg@10 typed: 0.830
llm rewrite, semantic, test judged@10 typed: 0.990
llm rewrite, semantic, test ndcg@10 rewrite: 0.749
llm rewrite, semantic, test judged@10 rewrite: 0.947
llm rewrite, semantic, mean difference: -0.081
llm rewrite, semantic, wins, losses, ties: 7, 19, 4
llm rewrite, semantic, permutation p: 0.000
llm rewrite, semantic, established at 0.01: yes
llm rewrite, semantic, t-test p: 0.000
llm rewrite, semantic, t-test agrees: yes
llm rewrite, semantic, 99% interval: -0.132 to -0.035
llm rewrite, semantic, interval agrees: yes
llm rewrite, semantic, condensed ndcg@10 typed: 0.834
llm rewrite, semantic, condensed ndcg@10 rewrite: 0.791
llm rewrite, semantic, condensed, exploratory mean difference: -0.043
llm rewrite, semantic, condensed, exploratory permutation p: 0.002
llm rewrite, semantic, condensed, exploratory 99% interval: -0.079 to -0.014
For BM25, nDCG@10 falls from 0.725 to 0.669, a difference that isn't established (planned comparisons). Judged@10 falls too, from 0.927 to 0.903.
Semantic retrieval shows an established loss: nDCG@10 falls from 0.830 to 0.749, with a permutation p-value that rounds to 0.000. Judged@10 falls as well, from 0.990 to 0.947.
Because judged@10 fell, we repeat both comparisons on condensed lists, which drop unjudged products before scoring. That check was chosen after seeing the drop, so it is exploratory and can't establish anything.
For semantic retrieval, condensed nDCG@10 still falls, from 0.834 to 0.791, a difference of -0.043, a permutation p of 0.002, and a 99% interval from -0.079 to -0.014. So the loss doesn't rest on unjudged products alone.
For BM25, condensed nDCG@10 goes from 0.778 to 0.725, with a permutation p of 0.044.
The rewrite didn't help BM25: it moved the other way from what Weller et al. and query2doc report, though not by an established amount. The rewrite's harm to semantic retrieval is what Weller et al. found for strong retrievers. Both results hold for this model, this prompt and these queries.
The queries that move most show what a rewrite does. Read them with the number of unjudged products in each rewritten top 10, which the metric counts as irrelevant:
1"""For each retriever, finds the test queries whose nDCG@10 moves most under the rewrite, and counts the unjudged2products in each rewritten top 10. The prose's point rests on the largest-loss and largest-gain lines, and on the3spelling-only check for BM25's largest gain."""4from bm25s.stopwords import STOPWORDS_EN56from lib.lexical import LexicalSearch7from lib.metrics import evaluate, ndcg_at_k8from lib.queries import rewrite_runs9from lib.recorded import llm_rewrites, probes10from lib.semantic import SemanticSearch11from lib.store import load_products, load_queries, qrels1213queries, judgments = load_queries("test"), qrels("test")14bm25 = LexicalSearch(load_products())15rewrites = llm_rewrites()[0].set_index("query_id")["rewrite"]16largest = {}17for retriever, (rewritten, typed) in rewrite_runs(queries, bm25, SemanticSearch()).items():18 change = evaluate(rewritten, judgments)["ndcg@10"] - evaluate(typed, judgments)["ndcg@10"]19 for kind, query_id in [("loss", change.idxmin()), ("gain", change.idxmax())]:20 label, largest[(retriever, kind)] = f"{retriever}, largest {kind}", query_id21 print(f"{label}: {queries.at[query_id, 'query']}")22 print(f"{label}, change: {change[query_id]:+.3f}")23 print(f"{label}, rewrite: {rewrites[query_id]}")24 unjudged = sum(product_id not in judgments[query_id] for product_id in rewritten[query_id][:10])25 print(f"{label}, unjudged products in the rewrite's top 10: {unjudged}")2627# BM25's largest gain: score the query with only its spelling fixed (chapter 6's probe), apart from the added words28query_id = largest[("bm25", "gain")]29# the spelling probes, keyed by the test query each one corrects30spelled = probes()[0].dropna(subset=["of_query_id"]).set_index("of_query_id")["query"]31if query_id in spelled.index:32 for name, text in [("typed", queries.at[query_id, "query"]), ("spelling fixed only", spelled[query_id])]:33 ranking = list(bm25.search(text, k=10).index)34 print(f"bm25, largest gain, ndcg@10 {name}: {ndcg_at_k(ranking, judgments[query_id], 10):.3f}")35 # bm25s's English stop words, which it drops before matching36 print("bm25 stop words among an and and:", ", ".join(word for word in ["an", "and"] if word in STOPWORDS_EN))
python rewrite-largest-changes.pybm25, largest loss: fold in half table
bm25, largest loss, change: -0.471
bm25, largest loss, rewrite: folding table, collapsible table, drop leaf table, gateleg table
bm25, largest loss, unjudged products in the rewrite's top 10: 3
bm25, largest gain: refrigerator with ice an water in door
bm25, largest gain, change: +0.159
bm25, largest gain, rewrite: refrigerator with ice and water in door, fridge with door dispenser, refrigerator with external water and ice dispenser
bm25, largest gain, unjudged products in the rewrite's top 10: 1
semantic, largest loss: pull out sleeper loveseat
semantic, largest loss, change: -0.304
semantic, largest loss, rewrite: pull out sleeper loveseat sofa couch convertible sofa sofa bed
semantic, largest loss, unjudged products in the rewrite's top 10: 4
semantic, largest gain: nautical platters
semantic, largest gain, change: +0.055
semantic, largest gain, rewrite: nautical platters serving trays seafood platters maritime serving boards
semantic, largest gain, unjudged products in the rewrite's top 10: 0
bm25, largest gain, ndcg@10 typed: 0.501
bm25, largest gain, ndcg@10 spelling fixed only: 0.501
bm25 stop words among an and and: an, and
Both largest losses come from a rewrite that drops or broadens what the shopper asked for. BM25's largest loss, -0.471 for fold in half table, comes from folding table, collapsible table, drop leaf table, gateleg table, which drops in half and adds other kinds of table; 3 of its top 10 are unjudged. Semantic retrieval's largest loss, -0.304 for pull out sleeper loveseat, comes from pull out sleeper loveseat sofa couch convertible sofa sofa bed, which widens a loveseat to any sofa; 4 of its top 10 are unjudged.
BM25's largest gain, +0.159 for refrigerator with ice an water in door, comes from refrigerator with ice and water in door, fridge with door dispenser, refrigerator with external water and ice dispenser. The rewrite fixes an, but with only that fix BM25 scores 0.501, the same as the query as typed, 0.501, because both spellings are stop words. The gain comes from the words the rewrite adds. Semantic retrieval's largest gain is +0.055, for nautical platters, rewritten as nautical platters serving trays seafood platters maritime serving boards.
Working rule: Don't put an LLM rewrite in front of a strong retriever without a planned comparison on the test queries. Read the per-query losses for dropped requirements and broadened products, which the prompt's "keep every requirement" doesn't prevent. The store's semantic retrieval, the ranker to beat, keeps searching the query as typed.
가상의 상품으로 검색하기 (HyDE)
재작성이 LLM에 더 나은 질의를 요청한다면, 가상 문서 임베딩(hypothetical document embeddings)의 약자인 HyDE는 그 질의에 답이 될 것으로 상상한 문서를 LLM에 요청한다. LLM이 질의에 답하도록 작성한 가상 문서를 인코더가 임베딩하면, 그 벡터는 임베딩 공간에서 실제 문서들이 놓인 영역 근처에 자리 잡는다(Gao et al., 2023). 지어낸 세부 내용이 사실일 필요는 없다. 저자들은 인코더의 밀집 병목이 환각된 세부 내용을 걸러 낸다고 주장하는데, 이는 저자들의 논거일 뿐 측정 결과가 아니다. 저자들의 주요 결과는 온도 0.7로 샘플링한 InstructGPT(text-davinci-003)를 사용한다. 문단 순위화 벤치마크인 TREC DL19에서 HyDE는 관련성 레이블 없이 학습한 임베딩 모델인 Contriever의 nDCG@10을 0에서 100 사이의 척도로 44.5에서 61.3으로 끌어올렸다(Gao et al., Table 1). 레이블로 미세 조정한 Contriever에서는 결과가 LLM에 따라 달랐다. 더 작은 LLM은 nDCG@10을 약간 낮췄는데, 성능이 떨어지는 지시 모델은 미세 조정된 검색기의 전반적인 성능을 해칠 수 있기 때문이다. 반면 InstructGPT는 이를 높였고, DL19에서 가장 크게 올라 62.1에서 67.4가 되었다(Table 4).
여러 확장 기법은 원래 질의를 섞어 둔 채로 유지한다. HyDE는 가상 문서들의 임베딩을 질의 자체의 임베딩과 함께 평균한다(Gao et al., 3.2절). 관련성 피드백(relevance feedback)은 첫 결과에 대한 판정으로 질의를 개선하는 방법이며, Rocchio 방식은 원래 벡터를 합에 그대로 두면서 질의 벡터를 관련 있다고 판정된 결과 쪽으로 옮긴다(Manning et al., 2008). BM25의 경우 query2doc은 생성된 문단 앞에 질의를 다섯 번 반복하여 원래 용어가 가중치를 유지하게 한다(Wang et al., 2023).
HyDE 녹화본에는 질의마다 가상 상품이 하나씩 들어 있으며, 이는 상점의 LLM이 질의만 보고 작성한 것이다. 이름, 분류, 설명으로 이루어지고 상품으로서 임베딩된다. 여기서 hyde 함수는 이 임베딩을 질의의 임베딩과 평균한 뒤, 6장에서 평균 후에 권하는 대로 결과를 길이 1로 되돌린다. 두 임베딩은 한 가지 점에서 다르다. 질의의 임베딩에는 임베딩 모델의 질의 프롬프트가 붙고, 상품의 임베딩에는 모든 상품과 마찬가지로 이것이 붙지 않는다.
hyde(query) = (embedding(hypothetical product) + embedding(query)) / 2, then scaled to length 1
train 질의에서는 가상 상품의 임베딩만 사용한 경우도 시도하고, BM25에 대해서는 가상 상품의 텍스트만 사용한 경우와, query2doc의 가중 방식대로 그 앞에 질의를 다섯 번 반복한 경우도 시도한다. 그런 다음 이 장의 계획된 비교 중 마지막을 수행한다.
1"""Scores HyDE, its parts and their combinations with BM25 and semantic retrieval on the train queries, then runs HyDE2against semantic retrieval as the chapter's last planned comparison on the test queries. The prose's point rests on3the train lines for the hypothetical product alone and on the planned comparison's lines."""4import numpy as np56from lib.lexical import LexicalSearch7from lib.metrics import evaluate8from lib.queries import THRESHOLD, report_planned9from lib.recorded import llm_rewrites10from lib.semantic import SemanticSearch11from lib.store import load_products, load_queries, qrels1213# the hypothetical products' embeddings come in the table's row order; zip pairs each with its query_id14table, _, hypothetical_vectors = llm_rewrites()15hypothetical, vectors = table.set_index("query_id")["hypothetical"], dict(zip(table["query_id"], hypothetical_vectors))16bm25, semantic = LexicalSearch(load_products()), SemanticSearch()171819def hyde(query_id):20 """Gao et al.'s average of the hypothetical product's embedding and the query's, scaled back to length 1."""21 average = (vectors[query_id] + semantic.query_vectors[query_id]) / 222 return average / np.linalg.norm(average)232425def runs(queries):26 ids, typed = queries.index, queries["query"]27 return {"semantic": semantic.run(queries),28 "hypothetical alone": {query_id: list(semantic.search_vector(vectors[query_id]).index) for query_id in ids},29 "hyde": {query_id: list(semantic.search_vector(hyde(query_id)).index) for query_id in ids},30 "bm25": bm25.run(queries),31 "bm25, hypothetical alone": bm25.run(queries.assign(query=ids.map(hypothetical))),32 "bm25, query five times plus hypothetical": bm25.run(queries.assign( # query2doc's weighting33 query=[" ".join([typed[query_id]] * 5 + [hypothetical[query_id]]) for query_id in ids]))}343536train = {name: evaluate(run, qrels("train")) for name, run in runs(load_queries("train")).items()}37for name, frame in train.items():38 print(f"train ndcg@10 {name}: {frame['ndcg@10'].mean():.3f}")39 print(f"train judged@10 {name}: {frame['judged@10'].mean():.3f}")40change = (train["hypothetical alone"]["ndcg@10"] - train["semantic"]["ndcg@10"]).round(3) # for choosing, not evidence41print(f"train queries better, worse, hypothetical alone: {(change > 0).sum()}, {(change < 0).sum()}")4243print(f"\nthe planned test comparison, threshold {THRESHOLD:.2f}:")44test = {name: evaluate(run, qrels("test")) for name, run in runs(load_queries("test")).items()45 if name in ["semantic", "hyde"]}46for name, frame in test.items():47 print(f"test judged@10 {name}: {frame['judged@10'].mean():.3f}")48report_planned("hyde, semantic", test["hyde"]["ndcg@10"], test["semantic"]["ndcg@10"])
python hyde-train-and-test.pytrain ndcg@10 semantic: 0.772
train judged@10 semantic: 0.964
train ndcg@10 hypothetical alone: 0.704
train judged@10 hypothetical alone: 0.890
train ndcg@10 hyde: 0.769
train judged@10 hyde: 0.946
train ndcg@10 bm25: 0.695
train judged@10 bm25: 0.930
train ndcg@10 bm25, hypothetical alone: 0.644
train judged@10 bm25, hypothetical alone: 0.854
train ndcg@10 bm25, query five times plus hypothetical: 0.694
train judged@10 bm25, query five times plus hypothetical: 0.912
train queries better, worse, hypothetical alone: 13, 29
the planned test comparison, threshold 0.01:
test judged@10 semantic: 0.990
test judged@10 hyde: 0.970
hyde, semantic, mean difference: -0.031
hyde, semantic, wins, losses, ties: 8, 14, 8
hyde, semantic, permutation p: 0.108
hyde, semantic, established at 0.01: no
hyde, semantic, t-test p: 0.121
hyde, semantic, t-test agrees: yes
hyde, semantic, 99% interval: -0.115 to 0.001
hyde, semantic, interval agrees: yes
train 질의에서 가상 상품만 사용하면 의미 기반 검색의 nDCG@10은 0.772에서 0.704로 바뀌며, 점수가 더 좋아진 질의 수와 나빠진 질의 수는 13, 29이다. Judged@10도 함께 떨어져 0.964에서 0.890가 된다.
질의와 평균하면 점수는 0.769이고 judged@10은 0.946이다. BM25도 같은 양상을 보인다. 질의만 쓰면 0.695, 가상 텍스트만 쓰면 0.644, 그 앞에 질의를 다섯 번 반복하면 0.694이며, judged@10은 각각 0.930, 0.854, 0.912이다.
질의를 유지하면 가상 상품이 잃은 부분이 회복되며, train 질의에서는 어느 검색기든 이 조합이 질의 단독보다 더한 이득을 주지 못한다. train 수치는 설계의 지침일 뿐이며, 증거가 되는 것은 계획된 test 비교뿐이다.
test 질의에서 judged@10은 0.990에서 0.970로 바뀌며, HyDE는 의미 기반 검색과 확립된 차이를 보이지 않는다(계획된 비교). 이 결과는 상점의 120억 매개변수 모델 gemma4:12b-it-q4_K_M이 온도 0에서 질의마다 만든 가상 상품 하나에 해당한다. Gao et al.은 훨씬 큰 LLM에서 샘플링했고, 미세 조정된 검색기의 성능을 높인 것도 그 LLM뿐이었다.
작업 규칙: HyDE를 시도할 때는 언제나 질의 자체의 임베딩을 평균에 포함한다. 가장 큰 이득은 레이블 없이 학습한 인코더에서 기대하라. 미세 조정된 인코더에서는 Gao et al.이 가장 큰 LLM으로만 이득을 보았고, 상점은 자신의 모델, 프롬프트, 인코더로 이득을 전혀 보지 못했다. 이 질의들에서 이미 BM25를 앞서는 상점의 인코더 같은 인코더에서는, 질의마다 LLM을 호출하는 비용을 치르기 전에 HyDE를 시험하라. 상점은 HyDE를 사용하지 않는다.
후속 질문을 독립형 질의로 바꾸기
장의 도입부에서 남은 마지막 간극은 대화에서 나온다. 구매자의 다음 메시지는 흔히 앞선 메시지에 의존한다. in white가 책상 검색을 좁히는 경우가 그렇다. 검색은 하나의 텍스트만 보므로, 후속 질문은 독립형 질의(standalone query)가 되어야 한다. 독립형 질의는 앞선 턴 없이도 읽히고, 구매자가 여전히 원하는 것을 그대로 담고 있는 질의다. 대화형 질의 재작성은 맥락에 의존하는 질문을 같은 답을 갖는 자기완결적 질문으로 바꾸며, CANARD 데이터셋에는 이런 재작성이 40,527개 들어 있다(Elgohary et al., 2019). 대화형 검색 평가인 TREC CAsT 2019에서 사람이 쓴 재작성은 가장 좋은 자동 시스템을 상대적으로 35% 앞섰다(Dalton et al., 2020). 프롬프트를 쓰는 LLM을 다룬 후속 연구는 "정보가 풍부한 질의 재작성은 사람의 재작성보다, 특히 희소 검색기에서, 검색 성능을 크게 향상시킬 수 있다"고 보고했다(Ye et al., 2023). CAsT의 후속인 TREC iKAT 2025에서는 대부분의 실행이 파이프라인에 LLM을 사용하여 질의를 한 번 또는 여러 번 재작성했다(TREC iKAT 2025 overview).
WANDS에는 대화가 없으므로, 이 책을 위해 상점의 대화를 직접 만들었다. 후속 질문 12개로, 각각 테스트 질의를 색, 모양, 크기, 마감 중 하나의 속성으로 좁힌다. 두 턴만 본 상점의 LLM이 각 후속 질문을 독립형으로 재작성했다. 예를 들어 coat rack for bedroom 다음에 something in black가 오고, 이는 black coat rack for bedroom로 재작성된다. 판정은 정제된 질의가 아니라 첫 질의에 대해 상품에 등급을 매기므로, nDCG로는 후속 질문을 채점할 수 없다. 대신 각 상위 10개에서 세 종류의 상품을 센다. 첫째는 정제 조건을 유지하는 상품으로, attributes 또는 텍스트에 그 값이 들어 있는 상품이다. 예를 들면 black이다(예제는 attributes만으로 센 수도 함께 출력한다). 둘째는 올바른 종류의 상품으로, 판정자가 첫 질의에 대해 정확 또는 부분 일치로 평가한 상품이다. 셋째는 둘 다에 해당하는 상품이다. 후속 질문 단독, 두 턴을 이어 붙인 것, 독립형 질의를 각각 질의로 임베딩해 비교하고, 첫 질의를 기준선으로 둔다. 독립형 질의의 상위 100개에는 그 값을 명시한 상품만 남기는 필터를 더한다. 값은 기록된 대화에서 가져오며, 실제 시스템이라면 후속 질문에서 추출해야 한다.
1"""Counts, in each conversation's top 10, the products that keep the refinement and the products of the right kind, for2the follow-up alone, the joined turns, the standalone query, and the standalone query filtered by the value. The prose's3point rests on the "refinement in text or attributes" and "right kind with the refinement" lines."""4import numpy as np56from lib.queries import mentions7from lib.recorded import llm_conversations8from lib.semantic import SemanticSearch9from lib.store import load_products, load_queries, product_text, qrels1011products, judgments, semantic = load_products(), qrels("test"), SemanticSearch()12attributes, text = products["attributes"], product_text(products) # the embeddings read only the text13conversations, vectors = llm_conversations() # follow-ups we wrote for the book, not shoppers'14print("conversations:", len(conversations))15# row 4, the fifth conversation, which the example prints16example = conversations.iloc[4]17print(f"first query: {load_queries().at[example['query_id'], 'query']}")18print(f"follow-up: {example['follow_up']}")19print(f"standalone: {example['standalone']}")2021shares, filtered_lengths = {}, [] # shares: (top 10, measure) -> one share per conversation22for row, (first, value) in enumerate(zip(conversations["query_id"], conversations["value"])):23 # the standalone query's top 100, the pool the filter draws from24 standalone = semantic.search_vector(vectors["standalone"][row], k=100).index25 stated = mentions(standalone, value, attributes) | mentions(standalone, value, text)26 tops = {"first query": semantic.search(first, k=10).index,27 "follow-up alone": semantic.search_vector(vectors["follow_up"][row], k=10).index,28 "turns joined": semantic.search_vector(vectors["joined"][row], k=10).index,29 "standalone": standalone[:10],30 "standalone, filtered": standalone[stated][:10]} # given the value, which a live system extracts31 filtered_lengths.append(len(tops["standalone, filtered"]))32 for name, top in tops.items():33 in_attributes = mentions(top, value, attributes)34 in_either = in_attributes | mentions(top, value, text)35 # the first query's grade 1 (partial) or 2 (exact); a product with no judgment counts as 036 right_kind = np.array([judgments[first].get(product_id, 0) >= 1 for product_id in top], dtype=bool)37 for measure, hits in [("refinement in attributes", in_attributes), ("refinement in text or attributes", in_either),38 ("right kind", right_kind), ("right kind with the refinement", in_either & right_kind)]:39 shares.setdefault((name, measure), []).append(hits.sum() / 10) # empty places count as misses40for (name, measure), values in shares.items():41 print(f"{name}, {measure}: {np.mean(values):.3f}")4243kept = np.subtract(shares["standalone", "refinement in text or attributes"], shares["turns joined", "refinement in text or attributes"])44print(f"standalone against turns joined, more, fewer, same: {(kept > 0).sum()}, {(kept < 0).sum()}, {(kept == 0).sum()}")45print("conversations the filter leaves with fewer than 10 products:", sum(length < 10 for length in filtered_lengths))
python follow-up-refinements.pyconversations: 12
first query: coat rack for bedroom
follow-up: something in black
standalone: black coat rack for bedroom
first query, refinement in attributes: 0.125
first query, refinement in text or attributes: 0.200
first query, right kind: 0.958
first query, right kind with the refinement: 0.175
follow-up alone, refinement in attributes: 0.433
follow-up alone, refinement in text or attributes: 0.950
follow-up alone, right kind: 0.058
follow-up alone, right kind with the refinement: 0.058
turns joined, refinement in attributes: 0.208
turns joined, refinement in text or attributes: 0.383
turns joined, right kind: 0.933
turns joined, right kind with the refinement: 0.325
standalone, refinement in attributes: 0.200
standalone, refinement in text or attributes: 0.392
standalone, right kind: 0.958
standalone, right kind with the refinement: 0.350
standalone, filtered, refinement in attributes: 0.583
standalone, filtered, refinement in text or attributes: 0.900
standalone, filtered, right kind: 0.675
standalone, filtered, right kind with the refinement: 0.675
standalone against turns joined, more, fewer, same: 5, 4, 3
conversations the filter leaves with fewer than 10 products: 3
후속 질문 단독은 상위 10개 중 0.950개에서 정제 조건을 유지하지만, 올바른 종류의 상품은 0.058개뿐이다. 첫 질의를 담은 형태는 어느 것이든 올바른 종류의 상품을 찾는다. 이어 붙인 턴은 0.933개, 독립형 질의는 0.958개다.
이 대화에서 이어 붙인 턴과 독립형 질의는 모두 첫 질의보다 정제 조건을 더 자주 유지한다. 첫 질의는 정제 조건을 요청한 적이 없다. 수치는 0.383과 0.392이고, 첫 질의는 0.200이다.
attributes만으로 세면 비율은 더 낮아, 0.208, 0.200, 0.125이다. 많은 상품이 그 값을 텍스트에만 명시하는데, 임베딩이 읽는 것은 텍스트뿐이기 때문이다. 아래의 결론은 텍스트 또는 속성 기준의 집계에 근거하며, 이 집계는 과대 계산일 수 있다. round legs를 언급하는 상품도 둥근 것으로 세기 때문이다.
LLM의 재작성은 턴을 이어 붙인 것보다 나은 점이 없다. 이어 붙인 턴과 비교하면 독립형 질의가 정제 조건을 유지하는 상품을 더 많이, 더 적게, 같은 수로 가져오는 대화는 5, 4, 3개다. 올바른 종류이면서 정제 조건도 유지하는 상품은 독립형 질의의 상위 10개에서 0.350를 차지하고, 이어 붙인 턴에서는 0.325를 차지한다.
필터는 이 비율을 0.675로 높이지만, 상품이 10개 미만으로 남는 대화가 3개 생긴다.
이 12개의 대화는 구매자의 것이 아니라 우리가 만든 것이므로, 위 수치는 검증이 아니라 진단이다.
작업 규칙: 후속 질문만으로 검색하지 않는다. 최소한 앞선 턴과 이어 붙이거나, 독립형으로 재작성한다. 정제 조건이 카탈로그에 명시된 값을 가리키면 그 값을 추출해 가중치를 주거나 필터로 쓰고, 남는 상품이 너무 적으면 필터를 적용하지 않은 목록으로 되돌린다. 이 중 무엇이든 신뢰하기 전에 자신의 로그에서 가져온 대화로 측정한다.
운영 환경에서 무엇이 잘못되는가
LLM으로 하는 모든 재작성은 질의 경로에 놓인 모델 호출이다. 예제는 오프라인에서 한 번 기록해 둔 재작성을 읽지만, 실제 검색창은 쇼핑객이 기다리는 동안 질의마다 모델을 호출한다. query2doc의 저자들은 이 방법에 LLM 추론이 필요하며 그 추론이 상당히 느릴 수 있다고 밝혔고(Wang et al., 2023), 더 길어진 질의는 BM25 검색도 느리게 만든다. 측정값이 아닌 경험칙은 다음과 같다. 자주 들어오는 질의는 오프라인에서 재작성해 결과를 캐시에 저장하고, 테스트에서 이득이 확인된 질의에 대해서만 온라인에서 모델을 호출한다.
재작성은 하나의 모델과 하나의 프롬프트에 속한다. 모델 버전이 바뀌거나 프롬프트의 표현이 달라지면 어떤 재작성이든 바뀔 수 있다. 저장소에 있는 기록의 매니페스트에는 모델의 다이제스트와 각 프롬프트가 그대로 들어 있으며, 둘 중 하나가 바뀌면 다시 측정해야 한다.
어휘 사전은 카탈로그를 따라가야 한다. 지난달 카탈로그로 만든 교정기는 이번 달의 브랜드 이름을 오타로 취급할 수 있다. 인덱스를 다시 만들 때 어휘 사전도 함께 다시 만들고, 교정기가 바꾼 모든 질의를 원래 질의와 나란히 기록하여 tye → the와 같은 과교정을 찾아낼 수 있도록 한다. 기계 번역된 질의에서는 철자 오류가 검색이 반환하는 상품을 바꾸므로(Hanneman et al., 2024), 교정기가 놓친 오류는 한 질의의 결과가 불안정하게 나타나는 형태로 드러난다고 예상해야 한다.
분류기는 분류 체계를 따른다. 상품 클래스의 이름이 바뀌거나 나뉘거나 합쳐지면 분류기를 다시 학습시킨다. Crock Pots & Slow Cookers처럼 어떤 상품 클래스의 이름도 아닌 질의 클래스는 결코 예측될 수 없다. 7qt slow cooker의 경우 분류기는 대신 Slow Cookers를 예측한다.
재작성된 질의는 판정되지 않은 상품을 드러낸다. 이 장에서 nDCG@10으로 점수를 매긴 LLM 기반 변경은 모두 judged@10을 낮추었다. 재작성을 채택하기 전에 그 상위 10개 결과에 있는 판정되지 않은 상품을 판정받게 하거나, 2장에서처럼 압축된 점수를 확인한다.
작업 규칙: 질의를 입력된 그대로와 재작성된 형태로 모두 기록하고, LLM 재작성은 캐시하고, 모델과 프롬프트를 출력과 함께 버전 관리하고, 카탈로그가 바뀔 때마다 어휘 사전과 분류기를 다시 만든다.
이 장이 내린 결정
아래의 모든 설정은 train 질의에서 정했다. 표에는 test 질의에서 계획한 5개의 비교가 열마다 하나씩 들어 있다. 각 비교는 하나만 바꾼 검색기를 입력된 그대로의 질의를 사용하는 같은 검색기와 견준 것이다.
| 측정값 | BM25, 동의어 | 시맨틱, 클래스 부스트 | BM25, LLM 재작성 | 시맨틱, LLM 재작성 | 시맨틱, HyDE |
|---|---|---|---|---|---|
| 평균 차이 | 0.000 | 0.005 | -0.056 | -0.081 | -0.031 |
| 승, 패, 무승부 | 0, 0, 30 | 7, 4, 19 | 13, 15, 2 | 7, 19, 4 | 8, 14, 8 |
| 순열 p | 1.000 | 0.174 | 0.060 | 0.000 | 0.108 |
| 확립 여부 | no | no | no | yes | no |
| t-검정 p | 1.000 | 0.164 | 0.060 | 0.000 | 0.121 |
| 99% 구간 | 0.000 to 0.000 | -0.002 to 0.017 | -0.143 to 0.005 | -0.132 to -0.035 | -0.115 to 0.001 |
| t-검정 일치 | yes | yes | yes | yes | yes |
| 구간 일치 | yes | yes | yes | yes | yes |
- 맞춤법: 카탈로그가 쓰지 않는 단어만 교정한다. 교정기는 상점의 train 오타를 고치지만, 오타 질의가 너무 적어 검증할 수 없고
tye dye나ice an water를 처리하려면 문맥이 필요하다. 상점은 아직 교정기를 실행하지 않는다. - 단위: 상품과 질의에 하나의 표기를 쓰되, 카탈로그 자체의 표기에서 정하고 소수는 그대로 유지한다. 크기 질의가 너무 적어 검증할 수 없으므로 기준선 BM25는 그대로 둔다.
- 동의어: train 질의에서 확인한 공백을 메우는 목록으로, BM25에만 적용한다. 이 목록은 test 질의 1개를 바꾸었고 확립된 차이를 보이지 못했으므로, 기준선은 질의를 확장하지 않는다.
- 질의 클래스: 상품 텍스트로 학습한 나이브 베이즈를 쓴다. 표본에 클래스당 질의가 많아야 하나뿐이기 때문이다. 예측된 클래스는 힌트로 쓴다. 필터는 train에서 손해를 보고, 가장 좋은 부스트도 test에서 확립되지 않으므로 시맨틱 검색에는 부스트를 적용하지 않는다.
- LLM 재작성: 쓰지 않는다. 시맨틱 검색에서의 손해는 확립되었고, BM25의 변화는 확립되지 않았다.
- HyDE: 쓰지 않는다. 질의와 평균을 내면 확립된 차이가 없고, 가상의 상품만 쓰면 train에서 손해를 본다.
- 후속 질의: 단독으로는 결코 검색하지 않는다. 대화의 턴을 이어 붙이면 LLM이 만든 독립 질의와 거의 비슷한 성능을 낸다. 다음 단계는 정제된 값에 대한 필터이며, 여기에는 추출된 값과 대체 방안이 필요하다.
- 검색기는 입력된 그대로의 질의를 받는다. 시맨틱 검색은 계속 넘어야 할 순위 지정기로 남고, 어간 처리를 하지 않은 BM25는 기준선으로 남는다.
- 이 장이 보여 준 것: train 질의에서 맞아 보임으로 평가되는 변경도 test 질의에서 계획된 비교를 통과해야 하며, 여기서 시험한 변경 중 이득으로 통과한 것은 없다. 확립된 차이는 LLM의 재작성 하나였고, 그것은 시맨틱 검색에서의 손해였다.
이 판의 이 장
2026.11.10판예제 통과 2026년 11월 19이 장에서 12개 예제개 중 12개가 통과한다
영어판 2026.11.10판을 번역한 것이다.