Module contents
Lesson 2 of 24Core 100 min

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-nn model receives n−1n-1 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 w1,…,wTw_1,\ldots,w_T, with hth_t equal to the previous n−1n-1 tokens after adding initial markers, the approximation is

Pn(w1:T,</s>)=[∏t=1TP(wt∣ht)]P(</s>∣hT+1).P_n(w_{1:T},\texttt{</s>})= \left[\prod_{t=1}^{T}P(w_t\mid h_t)\right] P(\texttt{</s>}\mid h_{T+1}).

The full product rule is exact; restricting each conditional to hth_t is the Markov assumption. A unigram uses no previous tokens, a bigram uses one and a trigram two. “N-gram order” nn and “Markov dependency order” n−1n-1 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 n>2n>2, state must retain a tuple of up to n−1n-1 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.

InteractiveA walk through the bigram graph

Toy sequence: el gato mira el perro mira el gato duerme. A transition from the last token to the first is added; each arrow represents an observed pair and its width is proportional to its conditional probability.

elgatoperromiraduerme

The highlighted border identifies the inspected state; the colored dot marks the walk position. Faded arrows are still part of the chain.

Outgoing transitions from el: gato: 2/3 = 0.667 · perro: 1/3 = 0.333.

Recent states: el.

TokenUnigramsVisits
el3/9 = 0.333No steps
gato2/9 = 0.222No steps
perro1/9 = 0.111No steps
mira2/9 = 0.222No steps
duerme1/9 = 0.111No steps

Each visit counts the arrival state; the initial state is excluded from the denominator. The seed is 42. Circular closure balances each token’s arrivals and departures, so unigram frequency is stationary. All states communicate in this finite chain: visit frequencies converge almost surely to that distribution, although a finite walk can differ. The chain has period 3: from «el» it returns to «el» every three steps, so the fixed-time distribution does not converge from that state. Circularization is not equivalent to a sentence model with start and EOS.

Walk stateel
Sampled transitions0
Inspect transitions and compare visits with frequencies in a circular toy sequence.

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 hh is followed by ww. Write C(h,w)C(h,w) for that number and C(h)=∑wC(h,w)C(h)=\sum_w C(h,w), counting only scorable successors. When C(h)>0C(h)>0, the maximum likelihood estimate is

P^(w∣h)=C(h,w)C(h).\widehat P(w\mid h)=\frac{C(h,w)}{C(h)}.

To derive it, fix a context and call its probabilities pwp_w. Its contribution to log-likelihood is ℓh(p)=∑wC(h,w)log⁡pw\ell_h(p)=\sum_w C(h,w)\log p_w, with pw≥0p_w\ge 0 and ∑wpw=1\sum_w p_w=1. For observed tokens, a Lagrange multiplier gives C(h,w)/pw=λC(h,w)/p_w=\lambda. Normalization implies λ=C(h)\lambda=C(h) 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 qw=C(h,w)/C(h)q_w=C(h,w)/C(h). For any pp assigning positive mass to tokens with qw>0q_w>0,

ℓh(q)−ℓh(p)=C(h)∑w:qw>0qwlog⁡qwpw=C(h)DKL(q∥p)≥0.\ell_h(q)-\ell_h(p)=C(h)\sum_{w:q_w>0}q_w\log\frac{q_w}{p_w} =C(h)D_{\mathrm{KL}}(q\Vert p)\ge 0.

If pw=0p_w=0 for any observed token, its log-likelihood is −∞-\infty, so it does not improve the optimum either. If C(h)=0C(h)=0, 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 LL and the smallest path probability δ>0\delta>0. From any context, probability of ending within the next LL steps is at least δ\delta. Thus probability of continuing after kLkL steps is at most (1−δ)k(1-\delta)^k, 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 nn always improves a particular sample. A seed makes the draw repeatable; it does not make that sample sufficient statistical evidence.

InteractiveGenerate from windows

Part one, chapter I of Don Quixote, Project Gutenberg work no. 2000. Training: En un lugar de la Mancha, de cuyo nombre no quiero acordarme. This lesson’s cell reproduces both excerpts; these are tiny samples, not complete works or representative evaluations. Text is NFC normalized and lowercased; the MLE model retains all observed tokens and counts one EOS.

Current context: <s>. Outputs are sampled according to counts, without smoothing. Seed 1702 uses the kit generator: it does not aim to reproduce Python sampling.

No tokens generated yet.

Underlining marks contiguous spans of at least three tokens exactly matched against training. The longest span is chosen from each position, then the search continues without overlap. In word mode punctuation is separated by spaces: matches are token matches, not literal quotations with original spacing. Character mode preserves spaces and compares normalized code points.

Possible next tokenCount / totalProbability
en1/11.000

Changing source, unit or order resets state and seed. EOS ends the sequence; reaching 80 tokens is an execution limit, not an EOS emission. A short match can follow directly from counts and does not by itself prove memorization.

Source
Unit
2
Generated tokens0 of 80
StatusIn progress
Sample the next unit and compare output with the training excerpt.

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 N>0N>0 scored events, including sentence endings according to the protocol:

PPL⁡=exp⁡[−1N∑t=1Nlog⁡pt].\operatorname{PPL}=\exp\left[-\frac{1}{N}\sum_{t=1}^{N}\log p_t\right].

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 VV there are VnV^n possible n-grams. A corpus with MM windows can show at most MM 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 nn 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.

InteractiveObserved windows and perplexity

This lesson’s cell uses two short excerpts from Don Quijote: training En un lugar de la Mancha, de cuyo nombre no quiero acordarme and test Hechas, pues, estas prevenciones, no quiso aguardar más tiempo. Here a prefix of the first is used for training and the entire second for evaluation. These are tiny samples, not a representative evaluation.

NFC normalization and lowercasing are applied; vocabulary is rebuilt for each prefix. The threshold is 1 for characters and 2 for words and punctuation. Out-of-vocabulary tokens become UNK and each sequence contributes an EOS. Changing size can change what UNK represents, so perplexities at different sizes do not always score the same events.

Fraction of unseen test events

0.00.51.012345Order n

MLE perplexity, log scale

110.01234∞5Order n

● Training · ● Test. The ∞ symbol is shown outside the scale, not as a finite value.

OrderUnseen / eventsPPL trainPPL test
10/131.9271.531
20/131.8161.574
30/131.6731.685
40/131.4582.134
51/131.219∞

Curves use this interactive’s MLE counts, following the convention of the first cell. A test event with no training context-successor pair has zero probability and makes the full perplexity infinite. The prefix is treated as a sequence with one ending; these results are not extrapolated to larger corpora.

Unit
13 of 13 tokens
Training units13 of 13
Test units12
Test OOV12 of 12
Compare orders and prefix sizes with lab excerpts without truncating infinite perplexities.

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.

[ ]An n-gram model from scratchBrowser
"""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.

[ ]Custom MLE and NLTK on the same eventsLocal GPU
"""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()
This cell needs the local lab (PyTorch with your GPU). Start it with 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 n−1n-1 markers in padded_everygram_pipeline. For n=1n=1 that adds no ending; for n>2n>2 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

ProofThe maximum can lie on the boundary
Prove: Derive the MLE of successor probabilities for an observed context.
0
Let C(h,w) be successor w's count, C(h)>0 and q(w)=C(h,w)/C(h). Probabilities p(w) are nonnegative and sum to one.

Step 1 of 3. Which part of log-likelihood depends on this context?

NumericOne sentence and four decisions
Training contains three sentences: ‘el gato duerme’, ‘el perro duerme’ and ‘el gato come’. Fit an MLE bigram with a start and one ending per sentence. For ‘el gato duerme’, calculate perplexity counting the three words and ending.
NumericHow much can the corpus cover?
A vocabulary has 20,000 symbols. A corpus contains at most 10⁹ trigram windows. What minimum fraction of possible trigrams remains unseen? Give a fraction between 0 and 1.
CodeScore sentences with endings
Implement perplexity(model, sentences). model.n is a positive integer, model.vocab contains known content tokens and '<unk>', and model.prob(token, context) returns probability for a token and a tuple of the previous n−1 tokens. Each sentence is a list of tokens without markers. Replace each token outside model.vocab with '<unk>', start each sentence with n−1 '<s>' markers, score every token and exactly one '</s>', and count the ending in the denominator. Return infinity if any event has zero probability or perplexity exceeds float range; raise ValueError if there are no sentences or a probability is nonfinite or outside 0 to 1.
def perplexity(model, sentences):
  pass
Shift+Enter to run
QuizThe improvement that changes the problem
You raise the frequency threshold and test perplexity drops 30%, but many more words are now replaced by '<unk>'. What do you conclude?
Key idea
An n-gram turns recent history into a state and learns transitions from counts. Its simplicity reveals both the local structure captured and the zeros left when facing new contexts.