次の単語を予測する
読了まで約47 分分、10 節 節の 8 例 例。
この章を終えるまでに、ある店舗の商品名から、単語の出現を数えるだけで完全な言語モデルを構築できるようになる。そのモデルを使って、買い物客の入力に合わせて次の単語を提案し、テキストを生成し、モデルが一度も見たことのないテキストをどれだけうまく予測できるかを一つの数値で測定できるようになる。以降の各章では、このモデルの一部をより優れたものに置き換えていく。第3章以降では、変更のたびに同じ方法でモデルを測定する。
本書全体を通して、一つのケーススタディが繰り返し登場する。家具と家庭用品を扱うオンラインストアであり、以下ではこれを「店舗」と呼ぶ。店舗の検索ボックスにはオートコンプリートが必要である。買い物客が coffee と入力したときに、次の単語として table が提示されるようにしたい。また、短い商品説明文の作成と確認も必要である。どちらも次の単語を予測する問題であり、店舗にはそれを学習するためのテキストがある。カタログに載っているすべての商品の名前と説明文である。
言語モデルとは、ここまでの単語を与えられたときに、次に来うるすべての単語に確率を割り当てるプログラムである。この一つの能力で多くのことができる。検索クエリの続きを提案することは、次の単語として可能性の高いものを選ぶことである。文を書くことは、次の単語を選んで追加し、再び選ぶことの繰り返しである。予測がうまいモデルは、学習に使ったテキストについて何かを学び取っている。したがって、どれだけうまく予測できるかが、そのモデルを測る尺度になる。チャットアシスタントの背後にある大規模言語モデルも、桁違いに大きな規模で同じことを行っている。それまでのテキストを与えられると、次に来うる各テキスト片に確率を割り当てるのである。本書は、この仕組みを一度に一つの部品ずつ、ノートパソコンで動かせる小さな規模で構築していく。そうすることで、各部品が何をしているかを確認できる。
この章では、商品名の中でどの単語がどの単語に続くかを数え、その回数を確率に変換し、それを実際に役立てる。ここで構築するモデルには重大な欠陥がある。章の最後で、その欠陥を測定する。
ストアのテキストを読み込む
モデルがどの単語がどの単語に続くかを学ぶには、学習に使うテキストと、学んだ内容が見たことのないテキストにも通用するかを確かめる方法が必要である。後者は前者と同じくらい重要である。モデルは、学習に使ったテキストを丸暗記すれば、そのテキストを完全に予測できる。しかしそれは、ストアが次に追加する商品に対してモデルがどの程度うまく働くかを何も示さない。そこで、テキストは何かが学習する前に一度だけ3つに分割する。モデルが学習する学習用分割、モデルを構築する間にモデル同士を比較するための検証用分割、最終報告のために取っておくテスト用分割である。各商品はちょうど1つの分割に属するため、モデルの評価に使う名前や説明が、そのモデルの学習に使った内容に現れることはない。
本書のすべての例が学習に使うストアのテキストは、実在のものである。これは、Wayfair が ECIR 2022 の論文とともに公開した商品検索の公開データセット WANDS から取得したもので(Chen et al., 2022)、MIT ライセンスの下で提供されている(ライセンス)。スクリプト prep/wands_text.py がこのデータを準備する。その方法はデータカード examples/data/wands-text/README.md に記されている。テキストはすでに小文字化されており、句読点の前後には空白が入っている。説明文は、ファイルを小さく保つために文末で切り詰めてある。テキストにストア自身の名前が含まれる商品は除外してあるため、本書のどのモデルもストアの名前を書くようには学習しない。例はこのテキストを lib.store を通して読み込む。これは本書の共有モジュールの1つで、多くの例が必要とする設定用のコードを収めた短いファイルとして 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 である。家具のカタログとしては、この2つ目の数は大きい。多くの名前が商品ラインの名前で始まり、その語はわずかな商品にしか現れず、ほかのどこにも現れないからである。本書ではそれらの名前を表示しない。例の出力にそのような語が現れる場合は、学習用の説明文のうち30件未満でしか使われていない語は、代わりに [name] と表示する。そのような語は多くの場合、商品ラインの名前である。これらの稀な語は、この章の終わりまでに重要になる。
実践ルール: テキストは、どのモデルにも見せる前に学習用、検証用、テスト用に分割する。分割は文書単位(ここでは商品単位)で行い、1つの品目のほぼ重複したものが2つの部分にまたがらないようにする。作業中はモデルを検証用テキストで比較し、テスト用テキストは最終報告にだけ使う。まずは手元にある最も短く最も規則的なテキストから学習させる。この章では名前から始め、説明文は本書の後の部分で扱う。
どの単語がどの単語に続くかを数える
訓練用の名前を読み込んだら、次に来る語を予測する単純なモデルは、各単語が他の各単語の後にどれだけの頻度で現れたかを表にしたものになる。バイグラム(bigram)とは、coffee table のように隣り合う2つの単語の組である。訓練用の名前に含まれるすべてのバイグラムを数えれば、任意の単語について、その後にどの単語がどれだけの頻度で続いたかが分かる。クロード・シャノンは、情報理論を創始した論文でまさにこの考え方を用いた。直前の単語に続く頻度に応じて各単語を選ぶことで、英語を近似したのである(Shannon, 1948)。
次の2点に注意すると、数え上げが完全になる。名前の最初の単語は何にも続かず、最後の単語には何も続かない。しかし、どちらも予測する価値がある。最初の単語は、買い物客がどの種類の商品を入力しているかを決め、名前の終わる位置が分かればモデルは生成を止められるからである。そこで、各名前の先頭に <s>、末尾に </s> という2つの記号を付け加え、これらも単語として数える。すると、<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
1つの語が突出している。この店の名前に現れる coffee のほとんどは coffee table であり、訓練用の名前で coffee の後に続く 1,260 個の語のうち、ほとんどが table である。3番目にはカンマが来る。この店のテキストでは、句読点がそれぞれ独立した単語として扱われているためである。これはトークン、すなわちモデルが数える単位についての選択であり、それがどれほど重要かは第2章で示す。
この頻度表がモデルのすべてである。文法の規則も家具の知識も持たない。coffee table は何度も見たが、coffee lamp は一度も見ておらず、モデルが知っているのはそれだけである。共有モジュール lib.bigrams には、これと同じ数え上げのコードがクラス Bigrams として収められており、後の例ではモデルを1行で構築できる。
実践ルール: 組の数え上げは訓練用の分割だけで行い、すべてのテキストに開始記号と終了記号を付けて、テキストがどのように始まりどのように終わるかをモデルに学習させる。確率だけでなく、元の頻度も保持しておくこと。頻度を見れば、各確率がどれだけの根拠に基づいているかが分かり、次の節ではそれが必要になる。
この部分はまだ翻訳されていないため、英語で表示している。
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.
名前を1語ずつ生成する
同じ確率表は、テキストを補完するだけでなく、書くこともできる。生成するには、<s>から始め、確率に比例して次の語を無作為に引き、それを追加し、引いた語から同じ操作を繰り返す。これをモデルが</s>を引くまで続ける。常に最も確率の高い語を選ぶのではなく無作為に引くことで、モデルは毎回同じ名前ではなく、さまざまな名前を生み出せる。本書が目指す大規模言語モデルも、同じ方法でテキストを書く。すなわち、それまでのテキストから計算した確率にもとづいて、トークンを1つずつ選ぶのである。
シード付きの乱数生成器でこれらの確率から引いた6つの名前は、実行のたびに同じものになる。そのため、本書に載せた名前はコードの出力と一致する。
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がその例である。一方、名前全体としては妥当でないことが多い。名前を1つの製品にとどめるものが何もないからである。ある名前は、ビストロセットから調光可能な照明、さらにスマート乾燥機へと、カンマでつながって進んでいく。カンマの後には、ほとんど何が続いてもよいからである。モデルは直前の語より先の記憶を持たないので、ビストロセットについて述べていたことを知りえない。また別の名前は、製品ラインの名前([name]と表記される)を、革のラウンジチェアのような別種の製品に結びつける。製品ライン名で始まる名前は、訓練テキストに多く見られるからである。何も発明されてはいない。バイグラムモデルは数えた語しか書けず、出力もそれを裏づけている。生成された語のうち、訓練用の名前に含まれないものは0個である。
生成された名前は、数値では見えないモデルの限界を見えるようにする。そのため、読む価値がある。ただし、何かを測るものではない。6つの名前では2つのモデルを比べるには少なすぎ、読み手の「妥当」という感覚も日によって変わる。数値は次の節で示す。
実践ルール: モデルを変更するたびにサンプルを生成して読むこと。スコアに隠れる失敗、たとえばテキストがある製品から別の製品へ逸れていくといった失敗が、サンプルには現れるからである。サンプルを再現できるように、シードは固定する。モデルをそのサンプルで比較してはならない。比較は、検証用テキストでのパープレキシティで行う。
この部分はまだ翻訳されていないため、英語で表示している。
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.
この部分はまだ翻訳されていないため、英語で表示している。
Unseen word pairs break the model
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.
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
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
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.
本番環境で起こる問題
バイグラムによるオートコンプリートは、低コストで高速であり、検索ボックス向けのベースラインとしては今でも妥当である。ただし、次のような問題が伴う。
- カタログは変化し続ける。 先月の商品名から数えたモデルは、今月の商品ラインを知らない。買い物客が新しい商品ラインを入力しても、モデルにはその語の後に続く出現回数がないため、カウントを作り直すまで候補はまったく表示されない。したがって、カウントは定期的に、またカタログが変わるたびに作り直すこと。
- 候補が不適切になることがある。 モデルは、学習に使ったテキストで単語の後に続いたものを、句読点も含めてそのまま候補にする。候補は許可されたトークンの一覧で絞り込み、公開前に頻度の高い候補を人の目で確認すること。
- 人気商品がほかの商品を押しのける。
coffeeのように、ほとんどの場合に同じ種類の商品が後に続く単語は、常にその種類を候補として示す。コーヒーマグを探している買い物客は、より多くの文字を入力しなければならない。候補は1つではなく、複数を提示すること。 - 文脈が1語では少なすぎる。
patio barで示したとおり、このモデルは直前の1語以外をすべて無視する。買い物客が長いクエリを入力する場合は、より多くの語を条件にしたときに候補がどの程度変わるかを測定すること。これは第3章で扱う。 - テーブルはテキストとともに大きくなる。 バイグラムのテーブルには、これまでに現れたすべての組が項目として含まれる。文脈を長くすると、項目数は爆発的に増える。必要なものだけを数え、メモリに余裕がなければ、1回しか現れなかった組を削除すること。
この章で決めたこと
- 店舗のテキストは、商品を単位として一度だけ、訓練用、検証用、テスト用に分割し、モデルは訓練用だけから学習する。 モデルが学習したテキストで得たスコアは、予測ではなく記憶を測るものである。商品単位で分割すれば、一つの商品のよく似た名前が両側に入ることを防げる。
- すべてのテキストの前後に
<s>と</s>を付ける。 これにより、モデルはテキストの始まり方と終わり方を学べる。オートコンプリートが買い物客の最初の単語を扱うために、また生成が停止するために、これが必要になる。 - モデルは、検証用テキストでのパープレキシティによって比較する。 自然対数を用い、終了マーカーを含め、予測した単語をすべて数える。生成したサンプルは、そこに表れるものを知るために読むが、モデルの選択には決して使わない。
- 店舗の商品名に対するバイグラムモデルは、頻度の数え上げで作る、本書で最初のモデルである。 よくある続きが一つに決まる語、たとえば
coffeeの後では適切な次の単語を提案できるが、続く語が多様な語、たとえばoutdoorの後では提案の質が低い。文脈として見るのは一語だけなので、patio barとbarには同じ提案が返る。 - 平滑化をしない場合、このモデルの検証用パープレキシティは無限大になり、加算平滑化(add-one)を行うと有限にはなるが値は悪い。 第3章では、より良い平滑化の方法を与えてこのモデルをベースラインとし、分割と評価尺度は同じものを使い続ける。こうして、以後のすべてのモデルを同じ条件でこのモデルと比較できる。
この版における本章
第2026.11.16版2026年11月19日時点で例が通過この章の8 例件のうち8件が合格
英語版の書籍(版2026.11.16)から翻訳した。