다음 단어 예측하기

읽는 데 약 44분분 걸린다, 10절에 8개 예제이(가) 있음.

2026.11.16판 예제 통과 2026년 11월 19 86개 예제 중 86개 통과 변경 사항

AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식

영어판 2026.11.16판을 번역한 것이다. 원문 읽기

이 장을 마치면 매장의 상품명을 세는 방식만으로 완전한 언어 모델을 만들 수 있다. 그 모델로 쇼핑객이 입력하는 동안 다음 단어를 제안하고, 텍스트를 생성하고, 한 번도 본 적 없는 텍스트를 얼마나 잘 예측하는지 하나의 수치로 측정할 수 있다. 이후의 모든 장은 이 모델의 한 부분을 더 나은 것으로 바꾸며, 3장부터는 각 변경을 같은 방식으로 측정한다.

이 책에서는 온라인 가구·생활용품 매장 하나를 사례로 계속 다루며, 이를 매장이라고 부른다. 매장의 검색창에는 자동 완성이 필요하다. 쇼핑객이 coffee를 입력하면 다음 단어로 table이 제안되도록 하기 위해서다. 또 짧은 상품 설명을 작성하고 검토하는 일도 필요하다. 둘 다 다음 단어를 예측하는 문제이며, 매장에는 이를 학습시킬 텍스트가 있다. 카탈로그에 있는 모든 상품의 이름과 설명이다.

언어 모델은 지금까지의 단어가 주어졌을 때 다음에 올 수 있는 모든 단어에 확률을 부여하는 프로그램이다. 이 능력 하나로 많은 일을 할 수 있다. 검색어를 어떻게 끝맺을지 제안하는 것은 가능성이 높은 다음 단어를 고르는 일이다. 문장을 쓰는 것은 다음 단어를 고르고, 그것을 덧붙이고, 다시 고르는 일이다. 예측을 잘하는 모델은 학습한 텍스트에 대해 무언가를 배운 것이므로, 얼마나 잘 예측하는지가 곧 모델을 측정하는 기준이다. 채팅 도우미의 바탕이 되는 대규모 언어 모델도 훨씬 큰 규모로 같은 일을 한다. 지금까지의 텍스트가 주어지면 가능한 다음 텍스트 조각 각각에 확률을 부여한다. 이 책은 그 구조를 한 번에 한 부분씩, 노트북에서 실행할 수 있을 만큼 작게 만들어 가며 각 부분이 무엇을 하는지 볼 수 있게 한다.

이 장에서는 상품명에서 어떤 단어 뒤에 어떤 단어가 오는지 세고, 그 횟수를 확률로 바꾸어 활용한다. 여기서 만드는 모델에는 심각한 결함이 있으며, 장의 끝에서 그 결함을 측정한다.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Load the store's text

마지막으로 변경된 판: 2026.11.11판

Before a model can learn which words follow which, it needs text to learn from, and a way to tell whether what it learned carries over to text it hasn't seen. The second need matters as much as the first. A model can predict the text it learned from perfectly by memorizing it, which says nothing about how it will do on the next product the store adds. So the text is split once, before anything learns from it, into three parts: a training split that models learn from, a validation split for comparing models while you build them, and a test split kept for final reports. Each product belongs to exactly one split, so no name or description a model is scored on appears in what it learned from.

The store's text, which every example in this book learns from, is real. It comes from WANDS, a public product-search dataset that Wayfair published with a paper at ECIR 2022 (Chen et al., 2022), under the MIT licence (licence). The script prep/wands_text.py prepares it, and its data card, examples/data/wands-text/README.md, says how: the text is already lowercased, with spaces around punctuation, and descriptions are cut at a sentence end to keep the file small. Products whose text names the store itself are left out, so no model in this book learns to write the store's name. The examples read the text through lib.store, one of the book's shared modules: short files in examples/lib/ that hold setup code many examples need, which you can open and read.

Before counting anything, look at the text: the size of each split, and a few names:

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

Product names are short and repetitive enough for counting to work, so this chapter learns from them alone. The store's text covers 42,815 products, 34,252 of them in the training split. The training names hold 231,048 words, of 25,907 different kinds. That second count is large for a catalog of furniture, because many names start with a product line's name, a word that appears in a handful of products and nowhere else. This book doesn't print those names. Where an example's output would show one, it prints [name] instead, for any word used in fewer than 30 of the training descriptions, most often a product line's name. Those rare words will matter by the end of the chapter.

Working rule: Split your text into training, validation and test parts before any model sees it, and split by document (here, by product), so near-duplicates of one item never straddle two parts. Compare models on validation text while you work, and touch the test text only for the final report. Learn from the shortest, most regular text you have first; this chapter starts with names, and descriptions come later in the book.

어떤 단어 다음에 어떤 단어가 오는지 세기

마지막으로 변경된 판: 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이다. 쉼표가 세 번째인 것은 상점의 텍스트가 구두점을 별개의 단어로 취급하기 때문이다. 이는 모델이 세는 단위인 토큰에 관한 선택이며, 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.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

Generate names one word at a time

마지막으로 변경된 판: 2026.11.16판

The same probability table can write text as well as complete it. To generate, start at <s>, draw the next word at random in proportion to its probability, append it, and repeat from the word you drew, until the model draws </s>. Drawing at random, rather than always taking the likeliest word, is what lets the model produce varied names instead of the same one every time. The large language models this book builds toward write text the same way: one token at a time, each chosen from probabilities computed from the text so far.

Six names, drawn from those probabilities by a seeded random generator, come out the same on every run, so the names in this book match what the code produces:

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

Each adjacent pair of words is plausible, because each pair occurred in a real name: genuine leather, kitchen cart, lounge chair. The names as a whole often aren't, because nothing keeps a name on one product. One name runs from a bistro set to a dimmable light to a smart dryer, joined by commas, since after a comma almost anything can follow. The model has no memory beyond the last word, so it can't know it was describing a bistro set. Others attach a product line's name, printed as [name], to a product of a different kind, such as a leather lounge chair, because names that start with a product line are common in the training text. Nothing is invented: a bigram model can only write words it counted, and the output confirms it, with 0 generated words that the training names don't contain.

Generated names make a model's limits visible in a way a number can't, which makes them worth reading. They don't measure anything, though: six names are too few to compare two models, and a reader's sense of "plausible" changes from day to day. The next section gives the number.

Working rule: Generate samples whenever you change a model, and read them, because they show failures that a score hides, such as text drifting from one product to another. Use a fixed seed so the samples are reproducible. Never compare models by their samples; compare them by perplexity on validation text.

이 부분은 아직 번역되지 않았으므로 영어로 표시된다.

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.

운영 환경에서 생기는 문제

바이그램 자동완성은 비용이 낮고 빠르며, 검색창의 기준선으로는 여전히 쓸 만하다. 여기에는 다음과 같은 문제가 따른다.

  • 카탈로그는 계속 바뀐다. 지난달의 상품명으로 집계한 모델은 이번 달의 상품 라인을 모른다. 구매자가 새 상품 라인을 입력하면 모델에 그 뒤에 이어지는 횟수 정보가 없으므로, 집계를 다시 만들기 전까지는 제안이 전혀 나오지 않는다. 따라서 집계를 일정에 따라, 그리고 카탈로그가 바뀔 때마다 다시 만들어야 한다.
  • 제안이 곤란한 결과를 낳을 수 있다. 모델은 학습 텍스트에서 어떤 단어 뒤에 나왔던 것이라면 구두점까지 포함해 무엇이든 제안한다. 허용된 토큰 목록으로 제안을 걸러내고, 가장 빈번한 제안은 공개하기 전에 직접 검토해야 한다.
  • 인기 상품이 나머지를 밀어낸다. coffee처럼 대부분의 경우 한 가지 상품 유형이 뒤따르는 단어는 언제나 그 유형만 제안한다. 커피 머그잔을 찾는 구매자는 더 많이 입력해야 한다. 제안은 하나가 아니라 여러 개를 내놓아야 한다.
  • 문맥이 단어 하나로는 너무 적다. patio bar에서 보았듯이 모델은 마지막 단어 외에는 모두 무시한다. 구매자가 긴 검색어를 입력한다면 더 많은 단어를 조건으로 삼았을 때 제안이 얼마나 자주 달라지는지 측정해야 한다. 이는 3장에서 다룬다.
  • 표가 텍스트와 함께 커진다. 바이그램 표에는 지금까지 본 모든 쌍에 대한 항목이 있다. 문맥이 길어지면 항목 수가 폭발적으로 늘어난다. 필요한 것만 집계하고, 메모리가 부족하면 한 번만 나온 쌍은 쳐내야 한다.

이 장에서 결정한 것

마지막으로 변경된 판: 2026.11.11판
  • 상점의 텍스트는 상품 단위로 한 번만 나누어 학습, 검증, 테스트 분할을 만들고, 모델은 학습 분할로만 학습한다. 모델이 학습한 텍스트에서 얻은 점수는 예측이 아니라 암기를 측정한다. 상품 단위로 나누면 한 상품의 거의 같은 이름들이 양쪽에 나뉘어 들어가는 일을 막을 수 있다.
  • 모든 텍스트에는 <s>와 </s>를 덧붙인다. 그러면 모델이 텍스트가 어떻게 시작하고 끝나는지 학습한다. 자동 완성은 사용자의 첫 단어를 예측하는 데, 생성은 멈출 시점을 정하는 데 이 정보가 필요하다.
  • 모델은 검증 텍스트의 퍼플렉서티로 비교한다. 자연로그를 쓰고, 끝 표시를 포함해 예측하는 모든 단어를 센다. 생성한 표본은 그것이 보여 주는 바를 읽어 보되, 모델을 고르는 근거로는 쓰지 않는다.
  • 상점의 상품 이름에 대해 빈도로 만든 바이그램 모델이 이 책의 첫 모델이다. 이 모델은 coffee처럼 이어지는 말이 하나로 모이는 단어 뒤에서는 좋은 다음 단어를 제안하고, outdoor처럼 이어지는 말이 많은 단어 뒤에서는 좋지 않은 단어를 제안한다. 이 모델은 한 단어만 문맥으로 보므로 patio bar와 bar에 같은 제안을 한다.
  • 스무딩을 하지 않으면 이 모델의 검증 퍼플렉서티는 무한대이고, 더하기 일 스무딩을 하면 유한하지만 나쁜 값이 된다. 3장은 더 나은 스무딩 방법을 적용해 이 모델을 기준선으로 삼는다. 같은 분할과 같은 측정을 유지하므로, 이후의 모든 모델은 이 기준선과 같은 조건에서 비교된다.

이 판의 이 장

2026.11.16판예제 통과 2026년 11월 19이 장에서 8개 예제개 중 8개가 통과한다

영어판 2026.11.16판을 번역한 것이다.

이 절 인용

형식

각 형식은 이 번역이 따르는 영문 원서를 출처로 표기한다.

모든 형식은 이 판을 명시한다. 링크는 현재 판을 열며, 여기서 절의 제목은 본문이 마지막으로 바뀐 시점을 알려 준다. 접근 날짜와 검색 날짜는 이 자료를 여는 날짜다.

이 페이지의 내용

11장 중 1장: 다음 단어 예측하기

  1. Load the store's text
  2. 어떤 단어 다음에 어떤 단어가 오는지 세기
  3. Turn counts into probabilities
  4. Suggest the next word as a shopper types
  5. Generate names one word at a time
  6. Score a model with perplexity
  7. Unseen word pairs break the model
  8. Give unseen pairs a little probability
  9. 운영 환경에서 생기는 문제
  10. 이 장에서 결정한 것

맨 위로 돌아가기전체 장