Log inStart free
LESSON 7.01 · 6 STAGES · 3 CONTROLS · 3 CHECKS

N-gram language models

Watch a model count the words of a tiny corpus and predict the next one.


EXPLAINER · 7.01 · N-GRAM BAY
01
Stage 1 of 6 · The corpus
The corpus has 6 sentences and 48 tokens. The window slides over each n-gram of sentence 1: 2 tokens in a row.
Explain it simply

Each chip is one token: a word, or a marker for the start or the end of a sentence. The ochre window covers 2 tokens in a row. A run like that is called an n-gram. A language model built only from counts of these runs is an n-gram model.

Six rows of token chips, one row per sentence. An ochre window of 2 tokens slides along sentence 1. A list on the right shows the 11 tokens the model can predict.

tokens, countsn window, context, kprobabilitiesbefore smoothing, zeroprobability 0
Toy: 6 sentences, 48 tokens, 11 to predict
HOVER OR TAP A SHAPE TO SEE ITS NUMBERS
2 · bigram
Tokens per n-gram; the context is n − 1.
add 1
Extra counts for every token.
the dog sat on the mat
The same six words in two orders.
STAGE 1 / 6
MATH · STAGE 1HOVER A SYMBOL OR A SHAPE
(wi−n+1,…,wi)\sy{g}{data}{(w_{i-n+1}, \dots, w_i)}
n=2:(mat,</s>)n = 2: (\text{mat}, \text{</s>})

An n-gram is n tokens in a row.

Show the code ▾Hide the code ▴ · Try it yourself · Python 3
import math
from collections import Counter

corpus = [
    "the cat sat on the mat",
    "the dog sat on the rug",
    "the cat ran to the dog",
    "a dog sat on a mat",
    "the cat sat on a rug",
    "a cat ran to the mat",
]
test = "the dog sat on the mat"
n, k = 2, 1  # n-gram size, add-k smoothing

def tokens(s):
    return ["<s>"] + s.split() + ["</s>"]

def context(t, i):
    return tuple(t[max(0, i - (n - 1)):i])  # the last n - 1 tokens

vocab = []  # every token a model can predict (not <s>)
for s in corpus:
    for w in s.split():
        if w not in vocab:
            vocab.append(w)
vocab.append("</s>")

counts, totals = Counter(), Counter()
for s in corpus:
    t = tokens(s)
    for i in range(1, len(t)):
        counts[context(t, i), t[i]] += 1
        totals[context(t, i)] += 1

def prob(h, w):
    den = totals[h] + k * len(vocab)
    return (counts[h, w] + k) / den if den else 0.0

t = tokens(test)
log_p = 0.0
for i in range(1, len(t)):
    h = context(t, i)
    p = prob(h, t[i])
    print(" ".join(h) or "(none)", "->", t[i], f"{p:.3f}")
    log_p = log_p + math.log(p) if p > 0 and log_p > -math.inf else -math.inf

N = len(t) - 1  # tokens predicted, with </s>
pp = math.exp(-log_p / N)
print("perplexity", f"{pp:.2f}")

# prints:
# <s> -> the 0.294
# the -> dog 0.158
# dog -> sat 0.214
# sat -> on 0.333
# on -> the 0.200
# the -> mat 0.158
# mat -> </s> 0.286
# perplexity 4.43

Copy it into a file and run it. Change n, k or the test sentence.

Common mix-ups

MYTHA longer context always predicts the test sentence better.

FIXA longer context finds fewer matches, so its counts are thin. With add 1, the trigram perplexity is 5.19 against 4.43 for the bigram.

MYTHAn n-gram that the corpus never shows is impossible.

FIXThe corpus is small, so unseen does not mean impossible. Without smoothing, one zero makes the perplexity infinite.

Predict, then reveal
0 / 3 REVEALED
Q01With n = 1, which test sentence gets the lower perplexity?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q02On dog … mat, before smoothing, is the test token's bar taller or shorter at n = 3 than at n = 2?
1 · GUESS2 · TRY IT IN THE DIAGRAM
Q03With n = 2 and the swapped sentence, what does no smoothing do to the perplexity?
1 · GUESS2 · TRY IT IN THE DIAGRAM

Takeaways

  1. An n-gram model predicts the next token from counts of its context.
  2. A longer context gives sharper predictions but finds fewer matches.
  3. Smoothing keeps unseen n-grams above zero, so the perplexity stays finite.