預測下一個詞
閱讀約需 55 分鐘 分鐘,10 節 中共有 8 個範例。
讀完本章後,你能夠只靠計數,就用商店的商品名稱建立一個完整的語言模型,用它在購物者輸入時建議下一個詞、生成文字,並用一個數字衡量它對從未見過的文字預測得有多好。後續每一章都會以更好的做法取代這個模型的某一部分,並且從第 3 章起,以同樣的方式衡量每一項改變。
全書反覆出現一個案例:一家線上家具與居家用品商店,我們稱之為「商店」。它的搜尋框需要自動完成功能,讓購物者輸入 coffee 時,看到 table 被提供為下一個詞;它的簡短商品描述也需要撰寫與檢查。這兩項都是預測下一個詞的問題,而商店有可供學習的文字:其目錄中每項商品的名稱與描述。
語言模型(language model)是一種程式,會在給定目前已出現的詞之後,為每一個可能接在後面的詞指派一個機率。這項能力涵蓋的範圍很廣。建議如何完成搜尋查詢,就是挑選一個可能的下一個詞。撰寫句子,就是挑選一個下一個詞、加進去,再重新挑選。預測得好的模型,已經學到訓練文字中的某些特性,因此預測得有多好,就是衡量它的方式。聊天助理背後的大型語言模型做的是同一件事,只是規模大得多:給定目前的文字,它們會為每一段可能的下一段文字指派一個機率。本書一次建構這套機制的一個部分,規模小到可以在筆記型電腦上執行,讓你看清楚每個部分的作用。
在本章中,你會計算商品名稱中哪個詞接在哪個詞之後,把計數轉換成機率,並加以運用。你在這裡建立的模型有一個嚴重的缺陷,本章最後會對它進行衡量。
載入商店的文字
模型要學會哪些詞會接在哪些詞之後,需要有文字可供學習,也需要一種方法來判斷它學到的內容能否延伸到從未見過的文字。第二項需求和第一項同樣重要。模型只要把學習用的文字背下來,就能完美預測那些文字,但這無法說明它面對商店下一個新增的商品時表現如何。因此,文字會在任何模型開始學習之前先分割一次,分成三個部分:供模型學習的訓練分割(training split)、在建立模型時用來比較模型的驗證分割(validation split),以及留待最終報告使用的測試分割(test split)。每項商品只屬於其中一個分割,所以模型被評分時所用的名稱或描述,不會出現在它學習過的內容中。
本書每個範例所學習的商店文字是真實的資料。它來自 WANDS,這是 Wayfair 在 ECIR 2022 隨論文發表的公開商品搜尋資料集(Chen et al., 2022),採用 MIT 授權(授權條款)。腳本 prep/wands_text.py 負責準備這些資料,其資料卡 examples/data/wands-text/README.md 說明了做法:文字已經轉為小寫,標點符號前後都有空格,描述則在句子結尾處截斷,以縮小檔案。文字中提到商店本身名稱的商品已被排除,因此本書中沒有任何模型會學到寫出商店的名稱。範例透過 lib.store 讀取文字,它是本書的共用模組之一:examples/lib/ 中的幾個短檔案,存放許多範例都需要的設定程式碼,你可以打開來閱讀。
在計數之前,先看看這些文字:每個分割的大小,以及幾個名稱:
1"""Counts the store's products in each split and the words in its training names, then prints one ordinary training name2for each of four kinds of product. The line "different words in training names" is the one the prose's point rests on,3since the rare product-line names are among the words it counts."""4from lib.store import load_products, ordinary_words, words56products = load_products() # no split given: every product, in all three splits7print("products:", f"{len(products):,}")8for split in ["train", "validation", "test"]:9 print(f"{split} products:", f"{(products['split'] == split).sum():,}")1011train = products[products["split"] == "train"] # only the training names count toward the word totals12print("words in training names:", f"{sum(len(words(name)) for name in train['name']):,}")13print("different words in training names:", f"{len({w for name in train['name'] for w in words(name)}):,}")14print()15common = ordinary_words(300) # words in 300 descriptions or more: a stricter bar than the book's 3016for kind in ["coffee table", "bar stool", "area rug", "bathroom vanity"]: # one name of each kind, as examples17 print(next(name for name in train["name"] if kind in name and all(w in common or not w.isalpha() for w in words(name)))) # the first name whose words are all common; numbers and punctuation pass
python store-text.pyproducts: 42,815
train products: 34,252
validation products: 4,282
test products: 4,281
words in training names: 231,048
different words in training names: 25,907
solid wood coffee table
25 '' bar stool
hand-knotted wool/silk teal/plum area rug
36 '' single bathroom vanity
商品名稱夠短,重複性也夠高,足以讓計數發揮作用,所以本章只用名稱來學習。商店的文字涵蓋 42,815 項商品,其中 34,252 項在訓練分割中。訓練名稱共有 231,048 個詞,包含 25,907 種不同的詞。對一份家具目錄來說,第二個數字偏大,因為許多名稱開頭是產品系列的名稱,這種詞只出現在少數幾項商品中,其他地方都不會出現。本書不印出這些名稱。範例的輸出若會顯示這類詞,就改印 [name],凡是出現在少於 30 則訓練描述中的詞都是如此,這些詞多半是產品系列的名稱。這些罕見的詞到了本章結尾會變得重要。
**實用原則:**在任何模型看到文字之前,先把文字分成訓練、驗證和測試三個部分,並且以文件為單位來分割(此處是以商品為單位),讓同一項商品的近似重複內容不會橫跨兩個部分。進行工作時,以驗證文字來比較模型,只在最終報告時才動用測試文字。先從你手上最短、最規律的文字開始學習;本章從名稱開始,描述則留到本書後面。
計算哪個詞接在哪個詞後面
載入訓練名稱之後,一個簡單的「下一個詞」模型,就是一張記錄每個詞接在其他每個詞後面次數的表。二元組(bigram)是由相鄰兩個詞組成的詞對,例如 coffee table。只要計算訓練名稱中的每一個二元組,對任何一個詞,你就能知道哪些詞接在它後面,以及各出現幾次。Claude Shannon 在奠定資訊理論的那篇論文中,正是使用這個概念:依照每個詞接在前一個詞之後的頻率來挑選詞,藉此近似英文(Shannon, 1948)。
有兩個細節能讓計數完整。名稱的第一個詞前面沒有任何東西,最後一個詞後面也沒有任何東西,但兩者都值得預測:第一個詞決定了購物者正在輸入哪一類商品,而知道名稱在哪裡結束,模型才能停下來。因此每個名稱都會補上兩個標記,開頭是 <s>,結尾是 </s>,兩者都當作詞來計算。於是詞對 <s> coffee 記錄了某個名稱以 coffee 開頭,而 table </s> 則記錄了某個名稱以 table 結尾。
先從一個其下一個詞對搜尋框很重要的詞開始,也就是 coffee。這個範例會計算訓練名稱中的每一個詞對,然後列出接在它後面的詞:
1"""Counts every word pair in the training names, padded with start and end markers, and lists the words that most often2follow coffee. The four lines under "words after coffee" are what the prose's point rests on."""3from collections import Counter45from lib.store import load_products, words67names = load_products("train")["name"] # training split only, so validation and test names never add counts8pairs = Counter()9for name in names:10 tokens = ["<s>"] + words(name) + ["</s>"] # the markers record how a name starts and where it stops11 pairs.update(zip(tokens, tokens[1:])) # tokens[1:] is the same list one word on, so each word pairs with the next1213print("word pairs:", f"{sum(pairs.values()):,}")14print("different pairs:", f"{len(pairs):,}")1516after_coffee = {following: n for (word, following), n in pairs.items() if word == "coffee"} # pairs that start with coffee, by the word after17print("words after coffee:", f"{sum(after_coffee.values()):,}")18for following, n in sorted(after_coffee.items(), key=lambda item: -item[1])[:4]: # the key negates the count, so largest first19 print(f" coffee {following:<6} {n:>6,}")
python count-next-words.pyword pairs: 265,300
different pairs: 84,529
words after coffee: 1,260
coffee table 1,129
coffee mug 45
coffee , 28
coffee jar 13
有一個詞佔了絕大多數。商店名稱中幾乎每個 coffee 都是 coffee table,而在訓練名稱中接在 coffee 後面的 1,260 個詞裡,幾乎全是 table。逗號排在第三,因為商店的文字把標點符號當作獨立的詞。這是關於詞元(token,即模型所計算的單位)的選擇,第 2 章會說明它有多重要。
這張計數表就是整個模型。它沒有任何文法規則,也不具備任何家具知識;它見過 coffee table 很多次,從未見過 coffee lamp,它所知道的僅止於此。共用模組 lib.bigrams 以類別 Bigrams 收錄了同樣的計數程式碼,因此後面的範例只需一行就能建立這個模型。
實用原則: 只在訓練切分中計算詞對,並為每段文字補上開頭與結尾標記,讓模型學會文字如何開始與結束。請保留原始計數,而不只是由計數推導出的機率:計數能告訴你每個機率背後有多少證據,後續各節也會用到。
此部分尚未翻譯,因此以英文呈現。
Turn counts into probabilities
Counts say what happened, but a language model needs probabilities: how likely each next word is. The step from one to the other is division. The probability of a word given the word before it is the number of times the pair occurred, divided by the number of times the first word occurred with anything after it. In symbols, writing w for the previous word and v for the next one:
P(v | w) = count(w v) / count(w)
Read it as "the probability of v, given w". Estimating probabilities from the fraction of times something happened is called maximum likelihood estimation: of all the probability tables you could choose, it's the one that makes the training text likeliest (Jurafsky and Martin, chapter 3).
Apply the formula to coffee and four words that might follow it, printing each probability beside the counts behind it, and then the sum over every word that followed coffee:
1"""Divides how often each of four words followed coffee by how often coffee was followed by anything, then prints the sum of the2probabilities of every word after coffee. The line for lamp, which prints 0.000, is the one the prose's point rests on:3the bigram model gives a pair it never counted no probability at all."""4from lib.bigrams import Bigrams5from lib.store import load_products67model = Bigrams(load_products("train")["name"])8after_coffee, total = model.counts["coffee"], model.totals["coffee"] # counts[word] is a Counter of the words after word; totals[word] is their sum910for following in ["table", "mug", "jar", "lamp"]:11 print(f"P({following} | coffee): {after_coffee[following] / total:.3f} ({after_coffee[following]} of {total})") # a Counter returns 0 for a word never seen after coffee, not an error12print("sum over every word after coffee:", round(sum(n / total for n in after_coffee.values()), 6)) # rounded, so float error doesn't show in the sum
python next-word-probabilities.pyP(table | coffee): 0.896 (1129 of 1260)
P(mug | coffee): 0.036 (45 of 1260)
P(jar | coffee): 0.010 (13 of 1260)
P(lamp | coffee): 0.000 (0 of 1260)
sum over every word after coffee: 1.0
The probabilities of every word that followed coffee add up to 1.0, as a distribution must, because whatever comes next is one of those words. table takes most of that probability, 0.896 (1129 of 1260), and mug far less, 0.036 (45 of 1260).
The fourth line is the one to remember. coffee lamp never occurs in the training names, so its probability is 0.000 (0 of 1260). The model doesn't say that a coffee lamp is unlikely; it says a coffee lamp is impossible. For a furniture store that's a reasonable bet, but the same zero applies to every pair the model hasn't seen, including perfectly ordinary ones. That's the flaw this chapter ends on.
Working rule: Derive probabilities from counts by division, and check that each word's probabilities sum to one; a sum that doesn't is a bug in the counting. Treat a probability as only as good as the count under it: 0.9 from 1,000 pairs is evidence, while 1.0 from a single pair is an anecdote.
此部分尚未翻譯,因此以英文呈現。
Suggest the next word as a shopper types
Autocomplete, the store's first need, wants the likeliest next words, and a probability table ranks them. A shopper who has typed coffee sees table first. With the bigram model, the suggestions for any typed text are the words with the highest probability after its last word. The bigram model's class, Bigrams, from count which word follows which, has a method, next_words, that returns them, likeliest first.
Five typed prefixes, from one word to two, show where the suggestions help and where they go wrong. Three suggestions come back for each:
1"""Asks the bigram model for its three likeliest next words after five typed prefixes, then counts the training names that2contain outdoor door. The patio bar line, which gets the same suggestions as bar, is the one the prose's point rests on."""3from lib.bigrams import Bigrams4from lib.store import load_products56model = Bigrams(load_products("train")["name"])78for typed in ["coffee", "bar", "kitchen", "outdoor", "patio bar"]:9 last_word = typed.split()[-1] # the model reads only this word, so patio never reaches it10 suggestions = model.next_words(last_word, k=3) # (word, probability) pairs, likeliest first11 print(f"{typed:<10} -> " + ", ".join(f"'{word}' {p:.2f}" for word, p in suggestions))1213names = load_products("train")["name"] # the training names as plain strings, for the substring counts14print("training names containing 'outdoor door':", sum("outdoor door" in n for n in names)) # a substring test, so `outdoor doors` counts too15print("of them, followed by 'mat':", sum("outdoor door mat" in n for n in names)) # the same test, with mat after them
python autocomplete.pycoffee -> 'table' 0.90, 'mug' 0.04, ',' 0.02
bar -> 'stool' 0.32, 'pull' 0.18, '&' 0.15
kitchen -> 'sink' 0.17, 'island' 0.16, 'canister' 0.12
outdoor -> 'door' 0.22, 'patio' 0.07, 'area' 0.06
patio bar -> 'stool' 0.32, 'pull' 0.18, '&' 0.15
training names containing 'outdoor door': 215
of them, followed by 'mat': 214
After coffee, bar and kitchen, the top suggestions are what a shopper would want: tables, stools, sinks and islands. After outdoor they're weaker. The top suggestion, door, starts a real product type: 214 of the 215 training names containing outdoor door go on to mat. But a one-word suggestion can't offer a two-word product type, and after door the shares are small, because outdoor is followed by many different words. A comma and an ampersand also show up as suggestions, which no search box should offer. Filtering punctuation out of suggestions is a reasonable patch, and chapter 2 treats the cause.
The last line shows the model's real limit. A shopper who types patio bar gets exactly the suggestions for bar, because a bigram model looks at one word of context and nothing before it. patio is lost, so the model offers pull and &, which belong to cabinet hardware and to names such as bar & counter stools. Using more context is the subject of chapter 3, and a model that weighs every earlier word is where the book is heading.
Working rule: For autocomplete, offer the top few next words by probability, and drop tokens that aren't words, such as punctuation. Expect a bigram model's suggestions to be good after words that are almost always followed by the same thing, such as coffee, and poor after words with many possible continuations, such as outdoor. When the earlier words matter, as they do in patio bar, a bigram model can't help, however much text it learns from.
一次產生一個詞來生成名稱
同一張機率表既能補全文字,也能寫出文字。要生成,從 <s> 開始,依各詞的機率比例隨機抽出下一個詞,將它附加上去,再從剛抽出的詞重複同樣的步驟,直到模型抽出 </s> 為止。採用隨機抽取,而不是每次都取機率最高的詞,模型才能產生多樣的名稱,而不是每次都得到同一個。本書最終要建構的大型語言模型也以同樣的方式寫出文字:一次一個 token,每個 token 都從依目前已有文字算出的機率中選出。
以帶有種子的隨機數產生器依這些機率抽出六個名稱,每次執行的結果都相同,因此本書中的名稱與程式碼產生的輸出一致:
1"""Draws six product names from the bigram model, one word at a time, with a fixed seed so the same six come out on every2run. The count of generated words never seen in training is the line the prose's point rests on."""3import numpy as np45from lib.bigrams import END, START, Bigrams6from lib.store import load_products, masked78model = Bigrams(load_products("train")["name"])9rng = np.random.default_rng(2026) # fixed seed: any seed gives six names, this one gives the book's101112def generate(longest=12): # twelve words at most, if the end marker hasn't come first13 word, name = START, []14 while len(name) < longest:15 candidates = list(model.counts[word]) # the words seen after word: the only ones the model can draw16 chances = [model.probability(word, c) for c in candidates]17 word = candidates[rng.choice(len(candidates), p=chances)] # choice returns an index into candidates, drawn with these chances18 if word == END:19 break20 name.append(word)21 return " ".join(name)222324generated = [generate() for _ in range(6)]25print("\n".join(masked(name) for name in generated)) # masked shows each rare word, used in fewer than 30 training descriptions, as [name]; most are product lines' names26print("generated words never seen in training:", sum(w not in model.counts for name in generated for w in name.split())) # every training word is a key, since each is followed by something
python generate-names.pywaterproof table
long bistro set , dimmable led , smart dryer
[name] 3 '' wide genuine leather lounge chair
[name] kitchen cart
[name] pressure balanced tub door , french [name] panel post cap
[name] 68.75 '' wide armchair
generated words never seen in training: 0
每一組相鄰的詞都合理,因為每一組都曾出現在真實的名稱中:genuine leather、kitchen cart、lounge chair。但整個名稱往往並不合理,因為沒有任何機制讓名稱停留在同一種產品上。有一個名稱從一組小酒館桌椅,跳到可調光的燈,再跳到智慧烘衣機,中間以逗號相連,因為逗號之後幾乎什麼都可能接上。模型的記憶只到前一個詞,所以無從得知自己原本在描述一組小酒館桌椅。另有一些名稱把產品系列的名稱(以 [name] 印出)接到另一類產品上,例如皮革躺椅,原因是訓練文字中以產品系列名稱開頭的名稱十分常見。其中沒有任何東西是憑空創造的:bigram 模型只能寫出它計數過的詞,輸出也印證了這一點,其中有 0 個生成的詞不見於訓練名稱之中。
生成的名稱能讓人看見模型的限制,這是一個數字做不到的,因此值得閱讀。不過它們並不度量任何東西:六個名稱太少,無法比較兩個模型,而讀者對「合理」的感受也會日日不同。下一節提供這個數字。
實用原則: 每次更動模型時都要生成樣本並閱讀,因為樣本會呈現分數所掩蓋的失敗,例如文字從一項產品漂移到另一項產品。使用固定的種子,讓樣本可以重現。切勿以樣本來比較模型;應以驗證文字上的困惑度來比較。
此部分尚未翻譯,因此以英文呈現。
Score a model with perplexity
A language model is good when it gives high probability to the text that actually occurs. That suggests a score: run the model over real text, and see how much probability it gave to each word that came next. The standard way to summarize this is perplexity, and this book uses it to compare every model it builds.
Start from one pair. If the model gave the actual next word probability p, its surprise at that word is −log p: zero when it was certain (p = 1) and larger the less it expected the word. The cross-entropy of a text is the average surprise over every word in it, written with N as the number of predicted words:
cross-entropy = −(1/N) Σ log P(next word | previous word)
Perplexity is the cross-entropy turned back into a count: perplexity = exp(cross-entropy) (Jurafsky and Martin, chapter 3). It reads as the number of equally likely words the model was choosing between, on average, at each step. A perplexity of 10 means the model was, on average, as uncertain as if it had to pick among 10 equally likely words. Lower is better, and a model that knew every next word would score 1. This book uses natural logarithms throughout, which changes cross-entropy's units but not perplexity.
Score one training name, sled coffee table, pair by pair to see where its surprise sits, and then every training name at once:
1"""Scores the training name sled coffee table pair by pair, to show where its surprise sits, then scores every training name2at once. The printed line for P(sled | <s>), the largest surprise in the name, is the one the prose's point rests on."""3import math45from lib.bigrams import Bigrams, padded, perplexity6from lib.store import load_products78train = load_products("train")["name"]9model = Bigrams(train)1011name = "sled coffee table" # a training name, so every pair in it has a count12tokens = padded(name) # the name with <s> and </s> around it, as in training13surprise = 0.014for word, following in zip(tokens, tokens[1:]): # tokens[1:] shifts the list one word on, so each pair is a word and the next15 p = model.probability(word, following)16 surprise += -math.log(p) # natural log, so surprise is in nats, the units that exp() undoes17 print(f"P({following} | {word}) = {p:.4f} -log P = {-math.log(p):.2f}")18print("average -log P:", round(surprise / (len(tokens) - 1), 3)) # pairs: one fewer than the tokens, one per word predicted, </s> included19print("perplexity of the name:", round(math.exp(surprise / (len(tokens) - 1)), 1)) # perplexity is exp of the average surprise20print("perplexity of every training name:", round(perplexity(model, train), 1)) # pooled over every pair in every name, not averaged name by name
python perplexity-by-hand.pyP(sled | <s>) = 0.0001 -log P = 8.83
P(coffee | sled) = 0.7846 -log P = 0.24
P(table | coffee) = 0.8960 -log P = 0.11
P(</s> | table) = 0.6903 -log P = 0.37
average -log P: 2.389
perplexity of the name: 10.9
perplexity of every training name: 16.9
Almost all the surprise falls on the first pair. Few names begin with sled, so the model was surprised by it, and after that each word was close to expected: coffee follows sled in most training names that contain sled, and table follows coffee. The name's average surprise is 2.389, and its perplexity 10.9. Over every training name, the model's perplexity is 16.9: on the text it learned from, it was choosing among about that many likely words at each step.
That number flatters the model, because it's measured on the text the counts came from. Every pair in the training names has a count, so no pair surprises the model infinitely. The real test is text it hasn't seen.
Working rule: Score every language model by its perplexity on validation text, computed exactly as above, with natural logarithms and every predicted word counted, the end marker included. Compare perplexities only between models that use the same tokens and the same validation text, since splitting text differently changes N and what counts as a word. Report training perplexity only beside validation perplexity, to show how much the model memorized.
未見過的詞對會讓模型失效
以計數方式訓練的模型,只認得它計數過的詞對。驗證用的名稱之所以與訓練用的名稱分開保存,正是為了這個原因:它們能顯示模型遇到從未見過的文字時會發生什麼事。在以困惑度為模型評分中,模型在訓練名稱上的得分是 16.9。執行下一個範例之前,先猜猜它在 4,282 個驗證名稱上的困惑度會是多少。
1"""Scores the bigram model on the validation names, which it never learned from, then counts the pairs in them that never2occurred in training. The printed validation perplexity, which is infinite, is the line the prose's point rests on."""3from lib.bigrams import Bigrams, padded, perplexity4from lib.store import load_products, masked56model = Bigrams(load_products("train")["name"])7validation = load_products("validation")["name"] # products the model never learned from89print("validation perplexity:", perplexity(model, validation)) # inf as soon as one pair has probability zero, rather than an error1011pairs = [(w, f) for name in validation for w, f in zip(padded(name), padded(name)[1:])] # each neighbouring pair in a padded name12unseen = [pair for pair in pairs if model.probability(*pair) == 0] # probability is 0 for a pair the training names never contain13print("validation word pairs:", f"{len(pairs):,}")14print("pairs never seen in training:", f"{len(unseen):,}")15print("share never seen in training:", f"{len(unseen) / len(pairs):.0%}")16names_hit = sum(any(model.probability(*p) == 0 for p in zip(padded(n), padded(n)[1:])) for n in validation) # a name counts once, if any of its pairs is unseen17print("names with an unseen pair:", f"{names_hit:,}")18print("validation names:", f"{len(validation):,}")19print("first unseen pairs:", ", ".join(masked(f"{w} {f}") for w, f in unseen[:3])) # the first three in validation order, not the most common
python perplexity-on-new-names.pyvalidation perplexity: inf
validation word pairs: 33,336
pairs never seen in training: 8,278
share never seen in training: 25%
names with an unseen pair: 3,724
validation names: 4,282
first unseen pairs: [name] [name], [name] 4, wood half-circle
驗證困惑度是無限大:範例印出的是 inf。只要有一個詞對被模型賦予零機率就夠了,因為它的驚訝度 −log 0 是無限大,任何包含它的平均值也同樣是無限大。而且不只一個。驗證詞對中有 25% 從未出現在訓練名稱裡,而 3,724 的驗證名稱至少含有一個這樣的詞對。最前面幾個未見過的詞對說明了原因:若驗證名稱以訓練名稱從未提及的產品線開頭,印出來的形式是 [name],那麼它的第一個詞對與第二個詞對都是未見過的。
這正是機率一節所警告的缺陷。最大概似估計會賦予每個未見過的詞對零機率,而在真實文字中,大多數新文件都含有某些未見過的內容:新的產品線、不常見的尺寸,或是熟悉的詞出現在不熟悉的位置,例如 half-circle 出現在 wood 之後。增加訓練文字多少有些幫助,卻無法解決問題。語言不斷產生新的組合,因此把每個未見過的組合都視為不可能的模型,在新文字上必然會失敗。
解決辦法是平滑(smoothing):從模型已見過的詞對中拿走一小部分機率,分給未見過的詞對。
實用原則: 絕不要相信會對任何事物賦予零機率的語言模型;在比較模型之前,先檢查它在驗證文字上的困惑度是否為無限大或未定義。遇到這種情況時,像上面那樣計算未見過的詞對數量,就能知道模型無法處理的文字占多大比例。
此部分尚未翻譯,因此以英文呈現。
Give unseen pairs a little probability
The model in unseen word pairs break the model fails because it gives unseen pairs probability zero, and smoothing gives them some. The simplest smoothing method, add-one smoothing, pretends that every possible pair occurred once more than it did. Every count goes up by one, including the zeros, and the totals grow to match:
P(v | w) = (count(w v) + 1) / (count(w) + V)
where V is the size of the vocabulary, every word the model can predict. A word the training text doesn't contain at all is counted as one more vocabulary entry, <unk>, for unknown, so the probabilities still sum to one. No pair now has probability zero, so perplexity on new text is finite. The question is what it costs.
Two numbers show the cost, the probability of table after coffee and perplexity, under each model:
1"""Compares the counted and add-one bigram models on one probability and on perplexity, to show what add-one smoothing2costs. The printed validation perplexity, add-one, is the line the prose's point rests on: it is finite, where the3counted model's is infinite."""4from lib.bigrams import Bigrams, perplexity5from lib.store import load_products67model = Bigrams(load_products("train")["name"])8train, validation = load_products("train")["name"], load_products("validation")["name"] # the counts come from the training names; validation tests them910print("vocabulary:", f"{len(model.vocabulary):,}") # every word the model can predict: training words, </s> and <unk>, but not <s>, which is never predicted11print("P(table | coffee) counted:", round(model.probability("coffee", "table"), 3))12print("P(table | coffee) add-one:", round(model.probability("coffee", "table", add_one=True), 3)) # add_one adds one to every count, and the vocabulary's size to every total13print("training perplexity, counted:", round(perplexity(model, train), 1)) # on the names the counts came from, so every pair has a count14print("training perplexity, add-one:", f"{perplexity(model, train, add_one=True):,.1f}")15print("validation perplexity, add-one:", f"{perplexity(model, validation, add_one=True):,.1f}") # add-one gives no pair probability zero, so this is finite
python add-one-smoothing.pyvocabulary: 25,909
P(table | coffee) counted: 0.896
P(table | coffee) add-one: 0.042
training perplexity, counted: 16.9
training perplexity, add-one: 1,232.8
validation perplexity, add-one: 1,575.1
The vocabulary holds 25,909 words, the end marker and <unk> included, and that's the problem. Add-one smoothing adds one imagined occurrence for every one of them after every word, so after coffee it imagines tens of thousands of extra pairs against about a thousand real ones.
The probability of table after coffee falls from 0.896 to 0.042. The model now believes far less in what it has seen, and the perplexities show it: on the training names, perplexity rises from 16.9 to 1,232.8.
The validation perplexity is finite, 1,575.1, which is progress, but the model gives so much probability to word pairs that never happen that its predictions are nearly useless.
Add-one smoothing fixes the infinity and breaks almost everything else, because it adds one imagined pair for every word in the vocabulary, however much evidence the real counts hold, and spreads them evenly. Better smoothing methods take far less probability away from seen pairs, and give it to unseen pairs in proportion to how often their words occur elsewhere. Chapter 3 covers those methods. There, the counted model of this chapter, looking further back and with a better smoothing method, becomes the baseline that every later model in the book is measured against.
Working rule: Never ship a counted model without smoothing, and never ship one with add-one smoothing: measure validation perplexity and expect add-one to lose to every method in chapter 3, which compares them on the same tokens. Use add-one only as this chapter does, to show that zero probabilities are fixable and that the fix needs care.
正式環境中會出什麼問題
二元語法(bigram)自動完成既便宜又快速,作為搜尋框的基準線仍然合理。它會帶來下列問題:
- **商品目錄會持續變動。**以上個月的名稱統計出來的模型,並不認得這個月的產品線。購物者輸入新的產品線時,完全得不到建議,因為模型沒有該詞之後的計數,直到計數重新建立為止。因此請定期重建計數,並在商品目錄變動時一併重建。
- **建議可能令人難堪。**模型會建議訓練文字中接在某個詞之後的任何內容,包括標點符號。請讓建議通過一份允許詞元(token)清單的過濾,並在上線前以人工檢視最常出現的建議。
- **熱門商品會排擠其他商品。**如果某個詞大多數時候後面都接同一種產品類型,例如
coffee,模型就總是建議該類型。想找咖啡杯的購物者必須多打幾個字。請提供多個建議,而不是只提供一個。 - **只有一個詞的上下文太少。**如同
patio bar所示,模型會忽略最後一個詞以外的所有內容。如果購物者輸入的查詢很長,請衡量在以更多詞作為條件之後,建議改變的頻率,第 3 章會處理這件事。 - **資料表會隨文字增長。**二元語法表會為每一組出現過的詞對建立一筆項目;上下文變長時,項目數量會暴增。只統計你需要的部分,若記憶體吃緊,可以剔除只出現過一次的詞對。
本章的決定
- 商店的文字依商品一次切分為訓練、驗證與測試三個切分,模型只從訓練切分學習。 在模型學過的文字上取得的分數衡量的是記憶,而不是預測;依商品切分,可避免同一商品的近似重複名稱同時落在兩邊。
- 每段文字都以
<s>和</s>補齊。 模型因此學會文字如何開始與結束,自動完成需要這一點來處理使用者的第一個詞,生成也需要它來決定何時停止。 - 模型以驗證文字上的困惑度(perplexity)來比較, 使用自然對數,並計入每一個被預測的詞,包括結束標記。生成的樣本會被閱讀以了解它們呈現的內容,但絕不用來在模型之間做選擇。
- 以計數建立的商店商品名稱二元語法(bigram)模型,是本書的第一個模型。 在只有一種常見接續詞的詞之後,例如
coffee,它能建議出好的下一個詞;在有許多種接續詞的詞之後,例如outdoor,建議就很差。它只看得到一個詞的上下文,因此patio bar與bar會得到相同的建議。 - 未經平滑時,該模型在驗證文字上的困惑度為無限大;採用加一平滑後,困惑度變為有限,但表現不佳。 第 3 章為它提供更好的平滑方法,並以它作為基準,沿用相同的切分與相同的衡量方式,讓之後的每個模型都能在對等的條件下與它比較。
本章,於本版次中
版次 2026.11.16範例於 2026年11 月 19 通過測試本章 8 個範例 個範例中有 8 個通過
譯自英文書,版次 2026.11.16。