class NGramLM:
"""An n-gram language model estimated from counts."""
def __init__(self, tokens, n, vocab_size, alpha=0.01):
self.n, self.vocab_size, self.alpha = n, vocab_size, alpha
cont = collections.defaultdict(collections.Counter)
for gram in zip(*(tokens[i:] for i in range(n))):
cont[gram[:-1]][gram[-1]] += 1
self.cont = dict(cont)
self.total = {ctx: sum(c.values()) for ctx, c in self.cont.items()}
def sample(self, prefix, num_tokens, rng):
"""Extend prefix by sampling from the unsmoothed count model."""
out = list(prefix)
for _ in range(num_tokens):
ctx = tuple(out[len(out) - self.n + 1:])
counts = self.cont[ctx]
out.append(rng.choices(list(counts), counts.values())[0])
return out
vocab_size = len(known) + 1 # The training words and <unk>
models = {n: NGramLM(words_train, n, vocab_size) for n in (1, 2, 3)}