N-gram language models
Build and evaluate n-gram language models, including maximum-likelihood estimation, sampling and sparse contexts.
After this lesson you can
- Express n-gram probabilities with start and end conventions.
- Derive maximum-likelihood conditional probabilities, including boundary cases.
- Generate sequences and interpret termination and perplexity.
- Measure sparsity and compare models under consistent tokenization.
Before you start
What word can come next?
Imagine a speech recognizer uncertain between two transcripts. One way to help is to score each sequence by its compatibility with observed language. A spellchecker or statistical translator also needs to combine input evidence with preference for certain output sequences. A language model does not itself know whether a sentence is true: it assigns probabilities to sentence representations.
A model remembering the entire history may have too many distinct contexts to estimate from counts. An n-gram model truncates that history to a fixed window. It is simple enough to build and identify exactly where it fails. You can then distinguish insufficient data from an implementation problem.
A string with a beginning and end
A statistical language model assigns probability to token sequences. First choose vocabulary, normalization, sentence boundaries and treatment of unknown words. We use <s> as an initial context marker and </s> as a possible output ending a sentence. Neither <s> nor <pad> is a predicted word. An order- model receives initial <s> markers, and we score one </s> output at the end. A unigram has no initial context but does have an ending output.
For content tokens , with equal to the previous tokens after adding initial markers, the approximation is
The full product rule is exact; restricting each conditional to is the Markov assumption. A unigram uses no previous tokens, a bigram uses one and a trigram two. “N-gram order” and “Markov dependency order” use different conventions.
A bigram can be viewed as a graph: a state is the previous token and an edge to the next is weighted by its conditional probability. For , state must retain a tuple of up to tokens, not only the last. A generated sentence ends on </s>; to study an indefinite walk, define what happens next, for example restart at <s>. That restart is an additional transition in the construction.
A finite irreducible chain has a unique stationary distribution. Temporal visit frequencies converge to it under the usual finite irreducible chain conditions; convergence of the distribution at a fixed step also requires aperiodicity. Whether that distribution matches particular unigram counts depends on transition construction and whether beginnings and endings are counted. Truncating the graph to a few words can remove mass or create sinks. A drawing of frequent nodes should show omitted mass or explain truncation, not automatically promise that visits reproduce all unigrams.
Estimating transitions
Count in training how often context is followed by . Write for that number and , counting only scorable successors. When , the maximum likelihood estimate is
To derive it, fix a context and call its probabilities . Its contribution to log-likelihood is , with and . For observed tokens, a Lagrange multiplier gives . Normalization implies and the ratio above. If some count is zero, the optimum can lie on the boundary: you cannot derive it assuming all probabilities strictly positive.
A check including the boundary uses . For any assigning positive mass to tokens with ,
If for any observed token, its log-likelihood is , so it does not improve the optimum either. If , by contrast, data determine no distribution for that context. Returning zero for all successors may signal missing coverage, but that row sums to zero and is not a normalized distribution.
Sampling is not choosing the most likely word
In ancestral sampling, calculate the successor distribution for the current context, choose a token from it, add it to context and repeat until emitting </s>. A step limit protects execution and must be distinguished from model termination. If a row is undefined, show the failure; silently backing off to lower order changes the model.
For MLE counts from finitely many complete sentences with one ending each, every context reachable before ending has a path of observed transitions to </s>: follow the rest of one training occurrence of that context. There are finitely many reachable contexts; choose a path for each, call the greatest path length and the smallest path probability . From any context, probability of ending within the next steps is at least . Thus probability of continuing after steps is at most , which tends to zero. Generation starting at <s> terminates almost surely. This does not authorize the same conclusion for an arbitrary table, truncated graph or different backoff rule.
Shannon illustrated increasing-order approximations to English in 1948: examples include independent symbols, character transitions and word transitions. Character examples use 26 letters and space. This is an illustrative generation experiment, not a guarantee that increasing always improves a particular sample. A seed makes the draw repeatable; it does not make that sample sufficient statistical evidence.
You can choose excerpts from Don Quixote, chapter I, and Macbeth, act I, scene I, both in the specified Project Gutenberg editions. The cell reproduces both texts and trains on each; consult source terms and applicable law. The widget uses the kit’s random generator, so its samples need not match Python’s even when distributions agree.
As context increases, a continuation may have fewer training alternatives and copy long excerpts. This depends on corpus, prefix and draw. A short n-gram match is expected by construction; before calling output “memorization,” define how shared fragments are measured and compare more than one generation. Coherence need not increase monotonically.
Evaluate without teaching the test
Build vocabulary and counts on training, decide thresholds or order using training and validation, and reserve test for final evaluation. If you repeatedly explore test, say so: its figures become exploratory. Replacing a new word with <unk> helps only if the model assigns mass to that symbol. Reserving it in the dictionary gives it no counts; an MLE with no <unk> examples assigns it zero probability. You can map rare training words to <unk> using a rule fixed before looking at test.
Intrinsic evaluation can use perplexity over scored events, including sentence endings according to the protocol:
Logarithms avoid underflow from multiplying many small probabilities. When exponentiating mean loss, finite perplexity may exceed representable range and overflow: retain loss in nats if you need to distinguish those values. If any observed probability is zero, loss and perplexity are infinite; do not replace them with a large number without identifying it as a plotting limit. Lower perplexity indicates better prediction of the same events with the same vocabulary, but does not guarantee improvement in a downstream application. Jurafsky and Martin, in a Wall Street Journal example, report perplexities 962, 170 and 109 for uni-, bi- and trigrams respectively, with 38 million training words and 1.5 million test words. These are results of that published protocol, not a run of this lesson, and do not justify assuming unsmoothed MLE avoids zeros.
Comparing surprisal per character requires scoring the same string reversibly. If the word model discards spaces or maps several distinct words to <unk>, dividing surprisal by original length does not recover discarded information. A character model can count code points in the normalized string, including spaces, and state whether it also scores the ending. Word and character perplexity have different denominators and are not interchangeable.
The cost of a large window
Sparsity appears because combinations grow faster than observed windows. With vocabulary size there are possible n-grams. A corpus with windows can show at most distinct types, however often the same windows repeat. This count does not claim all combinations are linguistically possible or equally likely.
The fraction of test events never observed depends on tokenization, boundaries and mapping to <unk>. Measure it for each order and training size on the same test with a declared vocabulary policy. Increasing often yields more zeros and lower training loss, but a particular curve need not be monotonic. Zero probability causes infinite MLE perplexity; the next lesson studies reserving mass for unseen successors.
Labs
An n-gram model from scratch
This cell implements sparse counts, conditional probability, log-probability, perplexity and seeded generation. It builds vocabulary only from training and scores one ending per sequence. At word level, the expression groups Unicode \w characters (letters, numbers and underscore), retains internal apostrophes between those groups, separates other punctuation and discards spaces. The frequency threshold is 2 and rare units, possibly including punctuation, become <unk>; the OOV column counts content units. At character level it retains spaces and uses the entire normalized text as one sequence. The bits-per-character column appears only when there are no unknown characters and is infinite if any event has zero probability. The word model discards separators and does not produce a comparable bits-per-character figure.
The initial excerpts from chapters I and II of part one of Don Quixote, Project Gutenberg edition 2000, only test the pipeline. The edition is attributed to an anonymous volunteer and Joaquín Cuenca Abela; check terms of use before redistribution. To analyze complete chapters, copy part-one text into the cell’s TRAIN and TEST variables and record source and hash. Do not select order by looking at test.
"""MLE de n-gramas con recuentos dispersos, sin dependencias externas.
La muestra offline contiene dos fragmentos de la primera parte de Don Quijote,
Miguel de Cervantes, capítulos I y II, edición Project Gutenberg 2000:
https://www.gutenberg.org/files/2000/2000-0.txt . Preparación atribuida a un
voluntario anónimo y a Joaquín Cuenca Abela. La ficha indica dominio público
en EE. UU.; consulta https://www.gutenberg.org/policy/license.html y la ley
aplicable antes de redistribuir. Para estudiar capítulos completos, sustituye
TRAIN y TEST por los textos correspondientes. Los fragmentos no permiten sacar
conclusiones generales ni son una evaluación representativa del español.
"""
import math
import random
import re
import unicodedata
from collections import Counter, defaultdict
TRAIN = 'En un lugar de la Mancha, de cuyo nombre no quiero acordarme'
TEST = 'Hechas, pues, estas prevenciones, no quiso aguardar más tiempo'
MACBETH = 'When shall we three meet again?\nIn thunder, lightning, or in rain?'
SPECIAL = {'<s>', '</s>', '<unk>', '<pad>'}
TOKEN_PATTERN = re.compile(r"\w+(?:['’]\w+)*|[^\w\s]", re.UNICODE)
def normalize(text):
return unicodedata.normalize('NFC', text).lower()
def tokenize(text, level):
text = normalize(text)
if level == 'caracter':
return list(text)
if level == 'palabra':
return TOKEN_PATTERN.findall(text)
raise ValueError('Nivel desconocido')
class NGramLM:
def __init__(self, n, min_frequency=1):
if not isinstance(n, int) or n < 1 or min_frequency < 1:
raise ValueError('n y frecuencia mínima deben ser positivos')
self.n = n
self.min_frequency = min_frequency
self.vocab = set()
self.counts = defaultdict(Counter)
self.fitted = False
def fit(self, sentences):
sentences = [list(sentence) for sentence in sentences]
if not sentences:
raise ValueError('El entrenamiento necesita al menos una frase')
raw = Counter(token for sentence in sentences for token in sentence)
if SPECIAL.intersection(raw):
raise ValueError('Colisión entre texto y marcadores especiales')
self.vocab = {token for token, count in raw.items() if count >= self.min_frequency}
self.vocab.add('<unk>')
self.counts = defaultdict(Counter)
for sentence in sentences:
for context, token in self.events(sentence):
self.counts[context][token] += 1
self.fitted = True
return self
def events(self, sentence):
context = ['<s>'] * (self.n - 1)
for raw in [*sentence, '</s>']:
token = raw if raw == '</s>' or raw in self.vocab else '<unk>'
yield tuple(context), token
if self.n > 1:
context = (context + [token])[-(self.n - 1):]
def prob(self, token, context):
if not self.fitted:
raise ValueError('Entrena primero el modelo')
context = tuple(context)
if len(context) != self.n - 1:
raise ValueError('Longitud incorrecta del contexto')
context = tuple(part if part in SPECIAL or part in self.vocab else '<unk>' for part in context)
if token in ('<s>', '<pad>'):
return 0.0
token = token if token == '</s>' or token in self.vocab else '<unk>'
counts = self.counts.get(context)
total = sum(counts.values()) if counts else 0
return counts.get(token, 0) / total if total else 0.0
def evaluate(self, sentences):
if not self.fitted:
raise ValueError('Entrena primero el modelo')
logp, count, zeros, oov = 0., 0, 0, 0
for sentence in sentences:
sentence = list(sentence)
if SPECIAL.intersection(sentence):
raise ValueError('Colisión entre texto y marcadores especiales')
oov += sum(token not in self.vocab for token in sentence)
for context, token in self.events(sentence):
p = self.prob(token, context)
count += 1
if p == 0:
zeros += 1
else:
logp += math.log(p)
if count == 0:
raise ValueError('El conjunto no contiene frases')
return {'events': count, 'zero_events': zeros, 'unseen_fraction': zeros / count,
'oov_tokens': oov, 'logprob': -math.inf if zeros else logp,
'perplexity': math.inf if zeros else math.exp(-logp / count)}
def logprob(self, sentence):
return self.evaluate([sentence])['logprob']
def perplexity(self, sentences):
return self.evaluate(sentences)['perplexity']
def generate(self, seed=1702, max_tokens=80):
if not self.fitted or max_tokens < 0:
raise ValueError('Modelo no entrenado o límite negativo')
rng = random.Random(seed)
context = ['<s>'] * (self.n - 1)
output = []
for _ in range(max_tokens):
counts = self.counts.get(tuple(context))
if not counts:
return output, 'contexto sin sucesores'
choices = sorted(counts)
token = rng.choices(choices, weights=[counts[t] for t in choices], k=1)[0]
if token == '</s>':
return output, 'eos'
output.append(token)
if self.n > 1:
context = (context + [token])[-(self.n - 1):]
return output, 'límite'
def self_check():
assert tokenize('abc123_x 42, fin', 'palabra') == ['abc123_x', '42', ',', 'fin']
unigram = NGramLM(1).fit([['a'], ['a'], ['b']])
assert math.isclose(unigram.prob('a', ()), 1 / 3)
assert math.isclose(unigram.prob('</s>', ()), 1 / 2)
assert unigram.prob('desconocido', ()) == 0
assert math.isinf(unigram.perplexity([['desconocido']]))
assert NGramLM(1).fit([[]]).generate(seed=1702, max_tokens=10) == ([], 'eos')
bigram = NGramLM(2).fit([['a']])
assert bigram.prob('a', ('<s>',)) == 1
assert bigram.prob('a', ('contexto ausente',)) == 0
unknown_context = NGramLM(2, min_frequency=2).fit([['a'], ['b']])
assert unknown_context.prob('</s>', ('palabra nueva',)) == 1
assert unknown_context.prob('</s>', ('</s>',)) == 0
assert bigram.generate(seed=1702, max_tokens=10) == (['a'], 'eos')
assert bigram.generate(seed=1702, max_tokens=1) == (['a'], 'límite')
def experiment(train_text, test_text):
for level in ('caracter', 'palabra'):
train, test = tokenize(train_text, level), tokenize(test_text, level)
print('\nNivel:', level, '| tokens train/test:', len(train), len(test))
print('n | eventos test | OOV | eventos no vistos | PPL train | PPL test | bits/carácter test')
for n in range(1, 6):
# El umbral de palabra 2 genera ejemplos train de UNK cuando hay
# hapax. En caracteres, 1 conserva todo carácter visto en train.
model = NGramLM(n, min_frequency=1 if level == 'caracter' else 2).fit([train])
train_result, result = model.evaluate([train]), model.evaluate([test])
bpc = None
if level == 'caracter' and not result['oov_tokens'] and len(test):
bpc = -result['logprob'] / (len(test) * math.log(2))
print(n, result['events'], result['oov_tokens'], result['zero_events'],
train_result['perplexity'], result['perplexity'], bpc)
sample, reason = NGramLM(3, min_frequency=1).fit([train]).generate(seed=1702, max_tokens=30)
print('Muestra trigramas:', ''.join(sample) if level == 'caracter' else ' '.join(sample), '|', reason)
print('None en BPC: los tokens no representan reversiblemente toda la cadena evaluada.')
print('Los resultados dependen del corpus, la tokenización y la partición elegida.')
self_check()
experiment(TRAIN, TEST)
for name, text in [('Quijote', TRAIN), ('Macbeth', MACBETH)]:
for level in ('caracter', 'palabra'):
tokens = tokenize(text, level)
model = NGramLM(3, min_frequency=1).fit([tokens])
sample, reason = model.generate(seed=1702, max_tokens=30)
print('Generador de figura:', name, level, '| tokens:', len(tokens),
'| entrenamiento normalizado:', repr(normalize(text)),
'| muestra:', repr(sample), '| fin:', reason)Comparison with NLTK
You need nltk installed locally. The cell implements counts again and compares probabilities with nltk.lm.MLE for the same events, for orders 1 through 5 and both characters and words. It checks unigrams, contexts without successors and ending, and uses the same seed for external sampling. It also runs padded_everygram_pipeline separately to show its different markers. It needs no external files and does not automatically download corpora.
The cell measures time and peak Python allocations with tracemalloc, which is not total process memory. NLTK measurement includes vocabulary creation and the custom measurement counts construction, so their costs do not cover exactly the same operations. Brief excerpts only verify the pipeline; you can replace TRAIN and TEST with full chapters. Timings depend on machine and load.
"""Contraste autocontenido de MLE propio y nltk.lm, sin corpus externos.
Instala NLTK en el entorno local del lector: `python -m pip install nltk`.
Los fragmentos proceden de Miguel de Cervantes, Don Quijote, primera parte,
capítulos I y II, Project Gutenberg 2000:
https://www.gutenberg.org/files/2000/2000-0.txt . La ficha declara dominio
público en EE. UU.; consulta https://www.gutenberg.org/policy/license.html
y la normativa local antes de redistribuir. Sustituye TRAIN y TEST por los
capítulos completos para el experimento; el ejemplo es solo una prueba pequeña.
"""
import math
import random
import re
import time
import tracemalloc
import unicodedata
from collections import Counter, defaultdict
import nltk
from nltk.lm import MLE, Vocabulary
from nltk.lm.preprocessing import padded_everygram_pipeline
TRAIN = 'En un lugar de la Mancha, de cuyo nombre no quiero acordarme'
TEST = 'Hechas, pues, estas prevenciones, no quiso aguardar más tiempo'
SPECIAL = {'<s>', '</s>', '<unk>', '<pad>'}
PATTERN = re.compile(r"\w+(?:['’]\w+)*|[^\w\s]", re.UNICODE)
def tokenize(text, level):
text = unicodedata.normalize('NFC', text).lower()
return list(text) if level == 'caracter' else PATTERN.findall(text)
def map_vocab(train, test, minimum):
if SPECIAL.intersection(train) or SPECIAL.intersection(test):
raise ValueError('Colisión con marcadores')
counts = Counter(train)
vocab = {token for token, count in counts.items() if count >= minimum} | {'<unk>'}
return vocab, [t if t in vocab else '<unk>' for t in train], [t if t in vocab else '<unk>' for t in test]
def events(sentence, n):
context = ['<s>'] * (n - 1)
for token in [*sentence, '</s>']:
yield tuple(context), token
if n > 1:
context = (context + [token])[-(n - 1):]
def own_fit(sentence, n):
counts = defaultdict(Counter)
for context, token in events(sentence, n):
counts[context][token] += 1
return counts
def own_prob(counts, context, token):
# Los eventos de este contraste ya tienen el vocabulario aplicado.
successors = counts.get(context)
total = sum(successors.values()) if successors else 0
return successors.get(token, 0) / total if total else 0.0
def measured_fit(fn):
# tracemalloc mide asignaciones Python, no RSS ni toda la memoria nativa.
tracemalloc.start()
start = time.perf_counter()
obj = fn()
elapsed = time.perf_counter() - start
_, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
return obj, elapsed, peak
def nltk_aligned_fit(sentence, n, vocabulary):
# Suministramos solo n-gramas puntuados: n−1 inicios y un fin.
# Se proporcionan todos los símbolos por adelantado para que lookup no
# convierta el marcador inicial o final en desconocido.
vocab = Vocabulary(sorted(vocabulary | {'<s>', '</s>', '<unk>'}), unk_label='<unk>')
model = MLE(n, vocabulary=vocab)
model.fit([[(*context, token) for context, token in events(sentence, n)]])
return model
def metrics(probability, sentence, n):
total, count, zero = 0., 0, 0
for context, token in events(sentence, n):
p = probability(context, token)
if not math.isfinite(p) or not 0 <= p <= 1:
raise ValueError('Probabilidad inválida')
count += 1
if p == 0:
zero += 1
else:
total += math.log(p)
return {'events': count, 'zeros': zero,
'logprob': -math.inf if zero else total,
'perplexity': math.inf if zero else math.exp(-total / count)}
def compare(own, other, sentence, n):
one = metrics(lambda c, w: own_prob(own, c, w), sentence, n)
two = metrics(lambda c, w: other.score(w, c if c else None), sentence, n)
assert one['events'] == two['events'] and one['zeros'] == two['zeros']
if not one['zeros']:
assert math.isclose(one['logprob'], two['logprob'], rel_tol=1e-12, abs_tol=1e-12)
assert math.isclose(one['perplexity'], two['perplexity'], rel_tol=1e-12, abs_tol=1e-12)
# Comparar también sucesores ausentes y no solo los eventos de una frase.
contexts = set(own) | {context for context, _ in events(sentence, n)}
for context in contexts:
choices = set(own.get(context, {})) | {'<unk>', '</s>'}
for token in choices:
p = own_prob(own, context, token)
q = other.score(token, context if context else None)
assert math.isclose(p, q, rel_tol=1e-12, abs_tol=1e-12), (n, context, token, p, q)
if n > 1:
# Nunca puntuamos tokens después de EOS en el entrenamiento alineado.
missing_context = ('</s>',) * (n - 1)
assert own_prob(own, missing_context, '</s>') == 0
assert other.score('</s>', missing_context) == 0
return one
def generation_check(own, model, n, seed=1702, limit=30):
# Muestreamos con el mismo algoritmo externo y la misma semilla: comparar
# dos APIs de generación distintas con la misma semilla no obliga a que
# implementen igual el orden de elección ni el consumo de aleatoriedad.
rng = random.Random(seed)
context = ['<s>'] * (n - 1)
sample = []
for _ in range(limit):
counts = own.get(tuple(context))
if not counts:
return sample, 'contexto sin sucesores'
tokens = sorted(counts)
weights = [counts[t] for t in tokens]
for token in tokens:
assert math.isclose(own_prob(own, tuple(context), token),
model.score(token, tuple(context) if context else None), abs_tol=1e-12)
token = rng.choices(tokens, weights=weights, k=1)[0]
if token == '</s>':
return sample, 'eos'
sample.append(token)
if n > 1:
context = (context + [token])[-(n - 1):]
return sample, 'límite'
def main():
print('NLTK:', nltk.__version__, '| tiempos y memoria Python orientativos, carga compartida')
assert tokenize('abc123_x 42, fin', 'palabra') == ['abc123_x', '42', ',', 'fin']
# Una única frase de tres tokens: cuatro eventos, un cierre.
check_train = ['a', 'a', 'b']
own = own_fit(check_train, 1)
aligned = nltk_aligned_fit(check_train, 1, {'a', 'b', '<unk>'})
assert own_prob(own, (), 'a') == aligned.score('a') == .5
assert own_prob(own, (), '</s>') == aligned.score('</s>') == .25
assert own_prob(own, (), '<unk>') == aligned.score('<unk>') == 0
assert generation_check(own_fit([], 1), nltk_aligned_fit([], 1, {'<unk>'}), 1) == ([], 'eos')
# score también aplica lookup al contexto: lo comparamos tras mapear OOV.
unknown_train = ['<unk>']
unknown_own = own_fit(unknown_train, 2)
unknown_nltk = nltk_aligned_fit(unknown_train, 2, {'<unk>'})
assert own_prob(unknown_own, ('<unk>',), '</s>') == unknown_nltk.score('</s>', ('palabra nueva',)) == 1
assert unknown_nltk.score('</s>', ('</s>',)) == 0
for level in ('caracter', 'palabra'):
raw_train, raw_test = tokenize(TRAIN, level), tokenize(TEST, level)
sizes = sorted({min(size, len(raw_train)) for size in (32, 128, len(raw_train)) if size > 0})
if not sizes:
raise ValueError('Falta texto de entrenamiento')
for size in sizes:
# Cada prefijo entrena su propio vocabulario. Las PPL a distintos
# tamaños no son directamente comparables si cambia ese vocabulario.
vocab, train, test = map_vocab(raw_train[:size], raw_test, 1 if level == 'caracter' else 2)
for n in range(1, 6):
own, own_time, own_mem = measured_fit(lambda: own_fit(train, n))
other, nltk_time, nltk_mem = measured_fit(lambda: nltk_aligned_fit(train, n, vocab))
train_result = compare(own, other, train, n)
test_result = compare(own, other, test, n)
sample, reason = generation_check(own, other, n)
print(level, 'tamaño', size, 'n', n, 'train', train_result,
'test', test_result, 'segundos propio/NLTK', own_time, nltk_time,
'bytes Python propio/NLTK', own_mem, nltk_mem,
'muestra', repr(sample), 'fin', reason)
# El pipeline por defecto NO usa la convención anterior.
padded, padded_vocab = padded_everygram_pipeline(n, [train])
default = MLE(n)
default.fit(padded, padded_vocab)
print(' pipeline NLTK: unigramas <s> =', default.counts.unigrams['<s>'],
', </s> =', default.counts.unigrams['</s>'],
'; nuestra convención: cero inicios puntuados y un cierre')
print('La prueba corta usa fragmentos y no constituye un benchmark representativo.')
if __name__ == '__main__':
main()npm run lab and open the connection link.The comparison must use the same events, not merely call two similarly named functions. NLTK pads both ends with markers in padded_everygram_pipeline. For that adds no ending; for it adds several. If our convention scores exactly one </s>, events must be constructed or filtered carefully before comparing probabilities and perplexity. Extra start markers also affect unigram counts if all orders are mixed. Comparison time and memory are measurements of the specific machine and protocol.
Exercises
Step 1 of 3. Which part of log-likelihood depends on this context?
def perplexity(model, sentences):
pass