预测下一个词

阅读约需 58分钟 分钟,10节中含8个示例。

版次 2026.11.16 示例于 2026年11月19日 通过 86个示例中有86个通过 变化内容

AI 翻译。由人工以英文核验。 我们如何制作图书

译自英文版图书,版次 2026.11.16。 阅读原文

读完本章,你将能够:通过计数,用商店的商品名称构建一个完整的语言模型;用它在购物者输入时建议下一个词;用它生成文本;并用一个数字衡量它对从未见过的文本的预测效果。之后的每一章都会用更好的部分替换这个模型中的一个部分,并且从第 3 章起,用同样的方式衡量每一次改动。

贯穿全书的是一个反复出现的案例:一家在线家具和家居用品商店,我们称之为“商店”。它的搜索框需要自动补全,这样当购物者输入 coffee 时,就会看到 table 作为下一个词被推荐;它的简短商品描述也需要撰写和检查。这两个问题都是预测下一个词的问题,而商店拥有可供学习的文本:其目录中每件商品的名称和描述。

语言模型是这样一种程序:给定到目前为止的词,它为每个可能出现的下一个词分配一个概率。这一种能力涵盖了很多用途。建议如何补全一个搜索查询,就是挑选一个可能的下一个词。写一个句子,就是挑选一个下一个词,把它加上,再重新挑选。预测得好的模型,对其训练文本已经有所学习,因此它预测得有多好,就是衡量它的方式。聊天助手背后的大语言模型做的是同样的事,只是规模大得多:给定到目前为止的文本,它们为每一段可能出现的下一段文本分配一个概率。本书一次构建这套机制的一个部分,规模小到可以在笔记本电脑上运行,这样你就能看清每个部分的作用。

在本章中,你要统计商品名称中哪个词跟在哪个词之后,把计数转换为概率,并加以运用。你在这里构建的模型有一个严重的缺陷,本章最后会对它进行衡量。

加载商店的文本

最近一次修改见于版次 2026.11.11

模型要学会哪些词跟在哪些词后面,首先需要有可供学习的文本,还需要一种办法来判断它学到的内容能否推广到没见过的文本。第二个需求与第一个同样重要。模型只要把学习过的文本死记下来,就能把这些文本预测得完美无缺,但这无法说明它在商店新增的下一件商品上表现如何。因此,文本要在任何模型开始学习之前一次性划分为三部分:供模型学习的训练集,供你在构建模型时比较模型的验证集,以及留作最终报告的测试集。每件商品只属于一个划分,所以模型被评分所用的名称或描述,不会出现在它学习过的内容中。

本书每个示例所学习的商店文本是真实的。它来自 WANDS,这是 Wayfair 在 ECIR 2022 上随论文一同发布的公开商品搜索数据集(Chen et al., 2022),采用 MIT 许可证(许可证)。脚本 prep/wands_text.py 负责准备这些数据,其数据说明 examples/data/wands-text/README.md 记录了做法:文本已经转为小写,标点两侧带有空格,描述在句末处截断,以控制文件大小。文本中提到商店本身名称的商品已被剔除,因此本书中没有模型会学着写出商店的名称。示例通过 lib.store 读取文本,它是本书的共享模块之一:examples/lib/ 中的一些短文件,存放许多示例都需要的设置代码,你可以打开阅读。

在统计任何内容之前,先看看文本:每个划分的大小,以及几个名称:

store-text.py Python 3.12.15 · numpy 2.5.5 · pandas 3.1.1 通过
"""Counts the store's products in each split and the words in its training names, then prints one ordinary training namefor each of four kinds of product. The line "different words in training names" is the one the prose's point rests on,since the rare product-line names are among the words it counts."""from lib.store import load_products, ordinary_words, wordsproducts = load_products()                            # no split given: every product, in all three splitsprint("products:", f"{len(products):,}")for split in ["train", "validation", "test"]:    print(f"{split} products:", f"{(products['split'] == split).sum():,}")train = products[products["split"] == "train"]        # only the training names count toward the word totalsprint("words in training names:", f"{sum(len(words(name)) for name in train['name']):,}")print("different words in training names:", f"{len({w for name in train['name'] for w in words(name)}):,}")print()common = ordinary_words(300)                          # words in 300 descriptions or more: a stricter bar than the book's 30for kind in ["coffee table", "bar stool", "area rug", "bathroom vanity"]:      # one name of each kind, as examples    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.py
products: 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 条训练集描述中出现的任何词,这类词最常见的是产品系列的名称。这些罕见词到本章结尾时会变得重要。

**工作准则:**在任何模型看到文本之前,先把文本划分为训练、验证和测试三部分,并且按文档(这里是按商品)划分,这样同一件商品的近似重复内容就不会分处两个部分。工作期间在验证集文本上比较模型,只在最终报告时使用测试集文本。先从最短、最规整的文本学起;本章从名称开始,描述留到本书后面。

统计哪个词跟在哪个词之后

最近一次修改见于版次 2026.11.11

载入训练名称之后,一个简单的“下一个词”模型,就是一张记录每个词在其他词之后出现频率的表。二元组(bigram)是一对相邻的词,例如 coffee table。统计训练名称中的每一个二元组,对任意一个词,你都能知道哪些词跟在它后面,以及各出现了多少次。克劳德·香农(Claude Shannon)在奠定信息论的那篇论文中,用的正是这一思路:按照每个词跟在前一个词之后的出现频率来选词,从而近似英语(Shannon, 1948)。

有两个细节使计数完整。名称的第一个词前面没有任何词,最后一个词后面也没有任何词,但二者都值得预测:第一个词决定了购物者正在输入哪一类商品,而知道名称在何处结束,模型才能停下来。因此,每个名称都补上两个标记,开头的 <s> 和结尾的 </s>,它们都算作词。这样,<s> coffee 这一对就记录了名称以 coffee 开头,而 table </s> 则记录了名称以 table 结尾。

先从一个其后继词对搜索框很重要的词开始,即 coffee。该示例统计训练名称中的每一对词,然后列出跟在它后面的词:

count-next-words.py Python 3.12.15 · numpy 2.5.5 · pandas 3.1.1 通过
"""Counts every word pair in the training names, padded with start and end markers, and lists the words that most oftenfollow coffee. The four lines under "words after coffee" are what the prose's point rests on."""from collections import Counterfrom lib.store import load_products, wordsnames = load_products("train")["name"]                # training split only, so validation and test names never add countspairs = Counter()for name in names:    tokens = ["<s>"] + words(name) + ["</s>"]       # the markers record how a name starts and where it stops    pairs.update(zip(tokens, tokens[1:]))            # tokens[1:] is the same list one word on, so each word pairs with the nextprint("word pairs:", f"{sum(pairs.values()):,}")print("different pairs:", f"{len(pairs):,}")after_coffee = {following: n for (word, following), n in pairs.items() if word == "coffee"}   # pairs that start with coffee, by the word afterprint("words after coffee:", f"{sum(after_coffee.values()):,}")for following, n in sorted(after_coffee.items(), key=lambda item: -item[1])[:4]:   # the key negates the count, so largest first    print(f"  coffee {following:<6} {n:>6,}")
输出python count-next-words.py
word 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

最近一次修改见于版次 2026.11.16

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:

next-word-probabilities.py Python 3.12.15 · numpy 2.5.5 · pandas 3.1.1 通过
"""Divides how often each of four words followed coffee by how often coffee was followed by anything, then prints the sum of theprobabilities of every word after coffee. The line for lamp, which prints 0.000, is the one the prose's point rests on:the bigram model gives a pair it never counted no probability at all."""from lib.bigrams import Bigramsfrom lib.store import load_productsmodel = Bigrams(load_products("train")["name"])after_coffee, total = model.counts["coffee"], model.totals["coffee"]   # counts[word] is a Counter of the words after word; totals[word] is their sumfor following in ["table", "mug", "jar", "lamp"]:    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 errorprint("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.py
P(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

最近一次修改见于版次 2026.11.11

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:

autocomplete.py Python 3.12.15 · numpy 2.5.5 · pandas 3.1.1 通过
"""Asks the bigram model for its three likeliest next words after five typed prefixes, then counts the training names thatcontain outdoor door. The patio bar line, which gets the same suggestions as bar, is the one the prose's point rests on."""from lib.bigrams import Bigramsfrom lib.store import load_productsmodel = Bigrams(load_products("train")["name"])for typed in ["coffee", "bar", "kitchen", "outdoor", "patio bar"]:    last_word = typed.split()[-1]                    # the model reads only this word, so patio never reaches it    suggestions = model.next_words(last_word, k=3)   # (word, probability) pairs, likeliest first    print(f"{typed:<10} -> " + ", ".join(f"'{word}' {p:.2f}" for word, p in suggestions))names = load_products("train")["name"]               # the training names as plain strings, for the substring countsprint("training names containing 'outdoor door':", sum("outdoor door" in n for n in names))   # a substring test, so `outdoor doors` counts tooprint("of them, followed by 'mat':", sum("outdoor door mat" in n for n in names))   # the same test, with mat after them
输出python autocomplete.py
coffee     -> '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.

逐词生成名称

最近一次修改见于版次 2026.11.16

同一张概率表既可以补全文本,也可以写出文本。要生成名称,就从<s>开始,按概率大小随机抽取下一个词,将其追加到已有序列之后,再从刚抽到的词出发重复这一步,直到模型抽到</s>为止。随机抽取,而不是每次都取最可能的词,正是模型能够产生各不相同的名称、而不是每次都得到同一个名称的原因。本书最终要构建的大语言模型也以同样的方式写文本:一次一个词元,每个词元都从根据已有文本算出的概率中选取。

用带固定种子的随机数生成器,依据这些概率抽取六个名称,每次运行的结果都相同,因此本书中的名称与代码的输出一致:

generate-names.py Python 3.12.15 · numpy 2.5.5 · pandas 3.1.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 everyrun. The count of generated words never seen in training is the line the prose's point rests on."""import numpy as npfrom lib.bigrams import END, START, Bigramsfrom lib.store import load_products, maskedmodel = Bigrams(load_products("train")["name"])rng = np.random.default_rng(2026)                    # fixed seed: any seed gives six names, this one gives the book'sdef generate(longest=12):                            # twelve words at most, if the end marker hasn't come first    word, name = START, []    while len(name) < longest:        candidates = list(model.counts[word])        # the words seen after word: the only ones the model can draw        chances = [model.probability(word, c) for c in candidates]        word = candidates[rng.choice(len(candidates), p=chances)]   # choice returns an index into candidates, drawn with these chances        if word == END:            break        name.append(word)    return " ".join(name)generated = [generate() for _ in range(6)]print("\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' namesprint("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.py
waterproof 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])接到了另一类商品上,例如一把皮质休闲椅,这是因为以产品系列名开头的名称在训练文本中很常见。这里并没有凭空创造的内容:二元语法模型只能写出它统计过的词,输出也印证了这一点,其中有0个生成的词不包含在训练名称之中。

生成的名称能以数字做不到的方式显现模型的局限,因此值得一读。不过,它们并不衡量任何东西:六个名称太少,不足以比较两个模型,而且读者对“合理”的感觉每天都在变化。下一节给出数字。

工作准则: 每次修改模型时都生成样本并阅读,因为样本会显现分数所掩盖的失败,例如文本从一个商品漂移到另一个商品。使用固定的种子,使样本可以复现。切勿根据样本比较模型;应当在验证文本上按困惑度来比较。

这部分尚未翻译,因此以英文显示。

Score a model with perplexity

最近一次修改见于版次 2026.11.16

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:

perplexity-by-hand.py Python 3.12.15 · numpy 2.5.5 · pandas 3.1.1 通过
"""Scores the training name sled coffee table pair by pair, to show where its surprise sits, then scores every training nameat once. The printed line for P(sled | <s>), the largest surprise in the name, is the one the prose's point rests on."""import mathfrom lib.bigrams import Bigrams, padded, perplexityfrom lib.store import load_productstrain = load_products("train")["name"]model = Bigrams(train)name = "sled coffee table"                  # a training name, so every pair in it has a counttokens = padded(name)                       # the name with <s> and </s> around it, as in trainingsurprise = 0.0for word, following in zip(tokens, tokens[1:]):   # tokens[1:] shifts the list one word on, so each pair is a word and the next    p = model.probability(word, following)    surprise += -math.log(p)                # natural log, so surprise is in nats, the units that exp() undoes    print(f"P({following} | {word}) = {p:.4f}   -log P = {-math.log(p):.2f}")print("average -log P:", round(surprise / (len(tokens) - 1), 3))   # pairs: one fewer than the tokens, one per word predicted, </s> includedprint("perplexity of the name:", round(math.exp(surprise / (len(tokens) - 1)), 1))   # perplexity is exp of the average surpriseprint("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.py
P(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.

这部分尚未翻译,因此以英文显示。

Unseen word pairs break the model

最近一次修改见于版次 2026.11.16

A model trained by counting knows only the pairs it has counted, and the validation names were kept apart from the training names for exactly this reason: they show what happens when the model meets text it never saw. The model scored 16.9 on the training names, in score a model with perplexity. Before you run the next example, guess its perplexity on the 4,282 validation names.

perplexity-on-new-names.py Python 3.12.15 · numpy 2.5.5 · pandas 3.1.1 通过
"""Scores the bigram model on the validation names, which it never learned from, then counts the pairs in them that neveroccurred in training. The printed validation perplexity, which is infinite, is the line the prose's point rests on."""from lib.bigrams import Bigrams, padded, perplexityfrom lib.store import load_products, maskedmodel = Bigrams(load_products("train")["name"])validation = load_products("validation")["name"]   # products the model never learned fromprint("validation perplexity:", perplexity(model, validation))   # inf as soon as one pair has probability zero, rather than an errorpairs = [(w, f) for name in validation for w, f in zip(padded(name), padded(name)[1:])]   # each neighbouring pair in a padded nameunseen = [pair for pair in pairs if model.probability(*pair) == 0]   # probability is 0 for a pair the training names never containprint("validation word pairs:", f"{len(pairs):,}")print("pairs never seen in training:", f"{len(unseen):,}")print("share never seen in training:", f"{len(unseen) / len(pairs):.0%}")names_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 unseenprint("names with an unseen pair:", f"{names_hit:,}")print("validation names:", f"{len(validation):,}")print("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.py
validation 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

The validation perplexity is infinite: the example prints inf. One pair the model gave probability zero is enough, because its surprise, −log 0, is infinite, and so is any average that includes it. And there isn't only one. 25% of the validation word pairs never occur in the training names, and 3,724 of the validation names contain at least one. The first unseen pairs show why: a validation name that starts with a product line the training names never mention, printed as [name], makes both its first pair and its second unseen.

This is the flaw the probabilities section warned about. Maximum likelihood gives every unseen pair probability zero, and in real text most new documents contain something unseen: a new product line, an unusual size, a familiar word in an unfamiliar place, such as half-circle after wood. More training text helps a little, but it can't solve the problem. Language keeps producing new combinations, so a model that calls every unseen combination impossible will always fail on new text.

The fix is smoothing, which gives unseen pairs some probability by taking a little away from the pairs the model has seen.

Working rule: Never trust a language model that gives zero probability to anything; check for infinite or undefined perplexity on validation text before you compare models. When you see one, count the unseen pairs, as above, to know how much of the text the model can't handle.

这部分尚未翻译,因此以英文显示。

Give unseen pairs a little probability

最近一次修改见于版次 2026.11.16

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:

add-one-smoothing.py Python 3.12.15 · numpy 2.5.5 · pandas 3.1.1 通过
"""Compares the counted and add-one bigram models on one probability and on perplexity, to show what add-one smoothingcosts. The printed validation perplexity, add-one, is the line the prose's point rests on: it is finite, where thecounted model's is infinite."""from lib.bigrams import Bigrams, perplexityfrom lib.store import load_productsmodel = Bigrams(load_products("train")["name"])train, validation = load_products("train")["name"], load_products("validation")["name"]   # the counts come from the training names; validation tests themprint("vocabulary:", f"{len(model.vocabulary):,}")   # every word the model can predict: training words, </s> and <unk>, but not <s>, which is never predictedprint("P(table | coffee) counted:", round(model.probability("coffee", "table"), 3))print("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 totalprint("training perplexity, counted:", round(perplexity(model, train), 1))   # on the names the counts came from, so every pair has a countprint("training perplexity, add-one:", f"{perplexity(model, train, add_one=True):,.1f}")print("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.py
vocabulary: 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 自动补全成本低、速度快,作为搜索框的基线方案仍然合适。它也带来下面这些问题:

  • 商品目录在不断变化。 根据上个月的商品名称统计出的模型,并不了解本月的新产品线。购物者输入新产品线的名称时,完全得不到建议,因为模型中没有该词之后的计数,直到计数重建为止。因此,应按计划重建计数,并在商品目录变化时同样重建。
  • 建议可能令人尴尬。 模型会建议训练文本中跟在某个词之后的任何内容,包括标点。应通过允许使用的词元列表过滤建议,并在上线之前人工审查出现频率最高的那些建议。
  • 热门商品会挤掉其他商品。 如果某个词在大多数情况下后面跟着同一种商品类型,例如 coffee,模型就总是建议这种类型。寻找咖啡杯的购物者就必须多输入几个字。应提供多条建议,而不是只提供一条。
  • 只用一个词作为上下文太少。 正如 patio bar 所显示的,模型会忽略最后一个词之外的所有内容。如果购物者输入的查询较长,应衡量在以更多词为条件之后,建议的变化频率,第 3 章会做这件事。
  • 表会随文本增大。 bigram 表为每一个出现过的词对保存一个条目;上下文越长,条目数量增长得越剧烈。只统计需要的内容,如果内存紧张,可以裁剪只出现过一次的词对。

本章的决定

最近一次修改见于版次 2026.11.11
  • 商店的文本按商品一次性划分为训练集、验证集和测试集,模型只从训练集学习。 模型在自己学过的文本上得到的分数衡量的是记忆,而不是预测。按商品划分,可以避免同一商品的近似重复名称同时落在两边。
  • 每条文本都用 <s> 和 </s> 填充。 这样模型就能学到文本如何开头和结尾:自动补全需要它来处理用户输入的第一个词,文本生成需要它来判断何时停止。
  • 模型之间用验证文本上的困惑度来比较,使用自然对数,并且每个被预测的词都要计入,包括结束标记。生成的样本要仔细阅读,看它们说明了什么,但绝不用来在模型之间做选择。
  • 根据计数构建的商店商品名称二元模型,是本书的第一个模型。 对于只有一种常见后续词的词,例如 coffee,它给出的下一个词建议很好;对于后续词很多的词,例如 outdoor,建议则较差。它只能看到一个词的上下文,所以 patio bar 和 bar 得到的建议相同。
  • 不做平滑时,该模型在验证集上的困惑度为无穷大;使用加一平滑后,困惑度变为有限值,但仍然很差。 第 3 章为它给出更好的平滑方法,并把它作为基线,同时沿用相同的划分和相同的度量,使之后的每个模型都能在同等条件下与它比较。

本章,在本版次中

版次 2026.11.16示例于 2026年11月19日 通过本章 8个示例 个示例中有 8 个通过

译自英文版图书,版次 2026.11.16。

引用本节

格式

每种格式均引用英文原书,本译本以其为准。

每种格式都会注明该版次。其链接会打开当前版次,节标题处会说明该节文本最后一次修改的时间。访问日期和检索日期即为您打开此页的当天。

本页内容

第 1 章,共 11 章: 预测下一个词

  1. 加载商店的文本
  2. 统计哪个词跟在哪个词之后
  3. Turn counts into probabilities
  4. Suggest the next word as a shopper types
  5. 逐词生成名称
  6. Score a model with perplexity
  7. Unseen word pairs break the model
  8. Give unseen pairs a little probability
  9. 生产环境中的问题
  10. 本章的决定

返回顶部全部章节