Also N-gram Model · Unigram Model · Bigram Model · Trigram Model
An n-gram model is a count-based language model that gives, for each sequence of n − 1 previous tokens, a probability distribution over the next token, estimated by counting n-grams in a training text and normalizing.
Generating text (sampling via cumulative counts). Let V=(v1,…,vm) with counts #v1,…,#vm (for n≥2: the counts of the current context, i.e. the last n−1 generated tokens).
Compute the cumulative counts cj=∑i≤j#vi, j=1,…,m.
Pick a random integer r∈{1,…,cm}.
Find the smallest j with r≤cj.
Output vj.
Exactly #vj values of r map to vj, so vj is generated with probability #vj/cm. A unigram model picks each token independently of the previous ones.
defmake_counts_cumulative(counts: list[int]):
for i in range(1, len(counts)):
counts[i] += counts[i -1]
defrandom_char(cumulative_counts: list[int]) -> str:
r = random.randint(1, cumulative_counts[-1])
for i, ci in enumerate(cumulative_counts):
if r <= cumulative_counts[i]:
return chr(i + ord(" "))
(Lecture code: character tokens, vocabulary = printable ASCII from " " to "~", trained on the ES11 movie plots.)
Size: there are ∣V∣n possible n-grams (∣V∣n−1 contexts), exponential in n, so large n is infeasible. Solution: neural language models.
Unseen contexts and smoothing: many (n−1)-token contexts never occur in the training text, so the model has no distribution for them. Remedy: pick the next token at random (uniformly). This is called smoothing, because it changes the probability distribution.
Tokens: the lecture’s n-gram models use characters as tokens; modern language models use subwords.