AI Wiki中文/EN

N-gram language models: how much history should a count remember?

n-gram 语言模型

Build conditional counts, derive MLE and additive smoothing, and diagnose zero probability, EOS accounting and incomparable perplexities.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A longer memory can make a familiar sentence impossible

Use four invented, already-tokenized training sentences:

red birds sing
blue birds fly
red birds fly
blue fish swim

After birds, the next word is fly twice and sing once. A bigram model remembers only that previous token, so it can give blue birds sing positive probability even though the whole sentence never appeared. A trigram model remembers two previous tokens. It has seen blue birds followed only by fly, so an unsmoothed estimate gives the next sing probability zero.

More context separates cases, but leaves fewer observations per case. This example is small enough to count by hand. It is not a benchmark corpus, and the three named evaluation conditions below are diagnostic constructions rather than an independent estimate of real-language performance.

Read conditional probability first. Tokenization determines what a unit is; this program deliberately accepts token lists, without changing case or discovering word boundaries.

Add-half distributes probability after blue birds over nine targets. Complete-sentence likelihoods include one EOS; the unsmoothed trigram gives the recombined sentence zero probability.
The other-five bar sums five targets. Ellipses abbreviate labels only: scoring uses complete listed sentences. Green maps to UNK; zero is a true MLE zero.

From full history to a table of short histories

The exact identity and the modeling restriction

For a sequence of predicted events x_1 through x_T, the probability chain rule is exact. An order-n model replaces the full past by a history h_t containing at most the previous n−1 tokens:

P(x1:T)=∏t=1TP(xt∣x1:t−1),Qn(x1:T)=∏t=1Tq(xt∣ht).P(x_{1:T})=\prod_{t=1}^{T}P(x_t\mid x_{1:t-1}),\qquad Q_n(x_{1:T})=\prod_{t=1}^{T}q(x_t\mid h_t).

The second expression defines a different model; the chain rule alone does not justify forgetting context. A unigram has empty history, a bigram keeps one token and a trigram keeps two. The approximation is often called a Markov assumption. SLP3, §3.1.1

We give each sentence n−1 beginning markers, written BOS or <s>, and predict exactly one end marker, EOS or </s>. BOS is context, never a prediction target or a member of our predicted vocabulary V. EOS and the unknown-token class UNK are in V. A sentence with m ordinary tokens therefore contributes m+1 prediction events, even when m is zero. The four training sentences contribute16 events and, without rare-word merging, V has9 members.

EOS gives a model a way to stop and assign a probability to a complete variable-length sentence. A normalized next-token table alone is not a proof that every possible model will eventually stop: a closed cycle that cannot reach EOS would need separate treatment. For the positive additive models below, the finite history space and positive EOS probabilities provide a positive lower bound on the chance of stopping at each step, so the probability of never stopping is zero. A generation length cap is still a computational limit; reaching it is not an EOS event. SLP3, boundary-marker discussion

Derive the count estimate

For a fixed history h, let C(h,w) count training occasions on which w is predicted after h, and let C(h) sum those target counts. Define h using the same padding and sentence boundaries as scoring. We maximize the conditional log likelihood, subject to a normalized table:

max⁡q(⋅∣h)∑w∈VC(h,w)log⁡q(w∣h),∑w∈Vq(w∣h)=1.\max_{q(\cdot\mid h)}\sum_{w\in V}C(h,w)\log q(w\mid h),\qquad \sum_{w\in V}q(w\mid h)=1.

For positive-count entries, the Lagrange-multiplier condition is C(h,w)/q(w|h)=λ. Summing gives λ=C(h), hence the maximum-likelihood estimate when C(h)>0:

qMLE(w∣h)=C(h,w)C(h),C(h)=∑v∈VC(h,v).q_{\mathrm{MLE}}(w\mid h)=\frac{C(h,w)}{C(h)},\qquad C(h)=\sum_{v\in V}C(h,v).

Zero-count entries receive zero. If C(h)=0, this division does not define a conditional distribution; our direct conditional-query interface raises an error for an unseen MLE history. This is distinct from a known history that assigns a particular target probability zero. SLP3, §3.1.2; NLTK MLE formula NLTK models

In the example, q(fly|birds)=2/3 and q(sing|birds)=1/3. At sentence start, red and blue each have probability1/2. Under the bigram model, the probability of the complete sentence red birds fly includes EOS:

Q2(red birds fly EOS)=12⋅1⋅23⋅1=13.Q_2(\text{red birds fly EOS})= \frac12\cdot1\cdot\frac23\cdot1=\frac13.

Under the trigram model, red birds is followed once by sing and once by fly, making the same sentence’s probability1/4. Trigrams have not uniformly improved every sentence’s likelihood, even though their aggregate training fit can be better.

Add positive mass, and count the cost of doing so

An additive or Lidstone baseline adds α to every target count, including EOS and UNK:

qα(w∣h)=C(h,w)+αC(h)+α∣V∣,α>0.q_\alpha(w\mid h)=\frac{C(h,w)+\alpha}{C(h)+\alpha|V|},\qquad\alpha>0.

The numerator sums to the denominator, so the table is normalized. For an unseen history it becomes uniform over V. α=1 is add-one; our example usesα=0.5. The inspected NLTK implementation uses the same count-plus-constant numerator and vocabulary-scaled denominator. NLTK Lidstone

At history blue birds, the one observed target is fly. With V=9 andα=0.5, the denominator is5.5, so fly gets3/11 and each of the other eight targets gets1/11. Previously impossible sing is now possible, but the observed fly also loses probability. Smoothing is a tradeoff, not free improvement; increasing α indefinitely approaches a uniform distribution. Choose hyperparameters on development data, not by repeatedly optimizing a final test result.

Vocabulary construction is part of the probability space

The program builds the vocabulary using training frequencies only. Words below min_count map to UNK in training, and any out-of-vocabulary evaluation token maps to the same class. It never expands V when scoring green birds fly. With threshold1, UNK is in V but has zero observed targets, so merely allocating it a slot does not give it positive MLE probability.

With threshold2, sing, fish and swim are merged into UNK: three training targets change, and V shrinks from9 to6. A resulting perplexity now measures prediction of coarser events. It cannot be directly compared with the full-vocabulary score as evidence of better prediction of the original words. The same issue applies when changing tokenization or case policy.

Compute likelihood without multiplying tiny numbers

A sentence can have positive mathematical probability yet underflow to floating-point zero. Sum natural log probabilities first. For M evaluation sentences, let T_j include exactly one EOS, and set total event count T to their sum:

H=−1T∑j=1M∑t=1Tjlog⁡q(xjt∣hjt),T=∑j=1MTj.H=-\frac{1}{T}\sum_{j=1}^{M}\sum_{t=1}^{T_j}\log q(x_{jt}\mid h_{jt}), \qquad T=\sum_{j=1}^{M}T_j.

This is empirical mean negative log likelihood in nats. Its exponential is perplexity:

PP⁡=eH=(∏j,tq(xjt∣hjt))−1/T.\operatorname{PP}=e^H =\left(\prod_{j,t}q(x_{jt}\mid h_{jt})\right)^{-1/T}.

Equivalently use base2 logs and raise2 to the resulting mean; the inspected NLTK API follows that convention. Its denominator concerns the n-grams supplied by its caller; our denominator explicitly includes one EOS per sentence. Do not silently assume two pipelines score identical event sets. SLP3, §3.3 NLTK API

For the bigram red birds fly, T=4 and PP=3^(1/4), about1.316074. Averaging sentence perplexities is generally wrong: aggregate the log losses and event counts first. A true zero-probability event gives infinite loss and perplexity. Our strict JSON output uses null with zero_probability status for that case. When all log probabilities are finite but their product underflows, the status stays finite and an underflow flag explains the zero product. Exponentiating a finite but huge H can also overflow; that has its own flag. These are different diagnoses.

Fit, score and sample from the same declared model

Save the complete standard-library program as ngram_models.py and run python3 ngram_models.py. It accepts orders1—4, a nonempty collection of tokenized sentences, and finite nonnegative α. An individual sentence may be empty. Input tokens must be nonempty strings without surrogate code points or reserved markers; case is retained. The code does not download data or fit vocabulary on evaluation inputs.

"""Original finite-context language model with an explicit event convention.

Input is pretokenized, case-preserving sentences. Training-only vocabulary,
order-1 BOS pads and exactly one predicted EOS per sentence. Supports MLE and a
declared additive baseline; no advanced smoothing or external model dependency.
"""
import json
import math
import random
from collections import Counter,defaultdict

BOS='<s>';EOS='</s>';UNK='<unk>';SPECIAL={BOS,EOS,UNK}


def checked_sentence(sentence):
    if not isinstance(sentence,(list,tuple)):raise ValueError('A pretokenized list or tuple is required')
    for token in sentence:
        if not isinstance(token,str) or not token or token in SPECIAL or any(0xD800<=ord(c)<=0xDFFF for c in token):
            raise ValueError('Nonempty Unicode tokens without reserved markers or surrogates required')
    return list(sentence)


def fit(sentences,order=2,alpha=0.,min_count=1):
    if type(order) is not int or not 1<=order<=4:raise ValueError('Teaching orders are1–4')
    if type(min_count) is not int or min_count<1:raise ValueError('Positive integer frequency threshold required')
    if isinstance(alpha,bool) or not isinstance(alpha,(int,float)) or not math.isfinite(alpha) or alpha<0:
        raise ValueError('Finite nonnegative additive smoothing required')
    if not isinstance(sentences,(list,tuple)) or not sentences:raise ValueError('Nonempty sentence collection required')
    sentences=[checked_sentence(s) for s in sentences];frequency=Counter(word for s in sentences for word in s)
    kept={w for w,count in frequency.items() if count>=min_count};vocabulary=sorted(kept|{EOS,UNK})
    if not math.isfinite(alpha*len(vocabulary)):raise ValueError('Smoothing mass overflow')
    counts=defaultdict(Counter);unknown=0;events=0
    for sentence in sentences:
        mapped=[word if word in kept else UNK for word in sentence];unknown+=mapped.count(UNK)
        padded=[BOS]*(order-1)+mapped+[EOS]
        for i in range(order-1,len(padded)):
            history=tuple(padded[i-order+1:i]) if order>1 else ()
            counts[history][padded[i]]+=1;events+=1
    return {'order':order,'alpha':float(alpha),'min_count':min_count,'vocabulary':vocabulary,
            'counts':dict(counts),'frequency':dict(frequency),'training_sentences':len(sentences),
            'training_prediction_events':events,'observed_unk_targets':unknown}


def mapped_tokens(model,sentence):
    sentence=checked_sentence(sentence);vocabulary=set(model['vocabulary'])
    return [word if word in vocabulary else UNK for word in sentence]


def context_key(model,history):
    if not isinstance(history,(list,tuple)):raise ValueError('A token-history sequence is required')
    mapped=[];seen_word=False;vocabulary=set(model['vocabulary'])
    for token in history:
        if not isinstance(token,str) or not token or token==EOS or any(0xD800<=ord(c)<=0xDFFF for c in token):raise ValueError('A valid token history before EOS is required')
        if token==BOS:
            if seen_word:raise ValueError('BOS is a prefix marker, not a token in the middle')
            mapped.append(BOS)
        else:seen_word=True;mapped.append(token if token in vocabulary else UNK)
    k=model['order']-1
    return tuple(([BOS]*k+mapped)[-k:]) if k else ()


def conditional_logs(model,history):
    context=context_key(model,history);counts=model['counts'].get(context,{})
    denominator=sum(counts.values())+model['alpha']*len(model['vocabulary'])
    if not math.isfinite(denominator):raise ValueError('Conditional normalizer overflow')
    if denominator==0:raise ValueError('Unseen history has no MLE conditional distribution')
    result={}
    for token in model['vocabulary']:
        numerator=counts.get(token,0)+model['alpha']
        result[token]=math.log(numerator)-math.log(denominator) if numerator else None
    return result


def distribution(model,history):
    return {word:(math.exp(value) if value is not None else 0.) for word,value in conditional_logs(model,history).items()}


def sequence_score(model,sentence):
    mapped=mapped_tokens(model,sentence);history=[BOS]*(model['order']-1);terms=[];events=len(mapped)+1
    for index,token in enumerate(mapped+[EOS]):
        value=conditional_logs(model,history)[token]
        if value is None:
            return {'status':'zero_probability','mapped_tokens':mapped,'prediction_events':events,
                    'first_zero_event':index,'log_probability':None,'probability':0.,'mean_nll_nats':None,
                    'perplexity':None,'log_terms_before_zero':terms,'note':'Null NLL/perplexity represents positive infinity; EOS is included.'}
        terms.append(value);history=(history+[token])[-(model['order']-1):] if model['order']>1 else []
    logp=math.fsum(terms);mean_nll=-logp/events;probability=math.exp(logp)
    try:perplexity=math.exp(mean_nll)
    except OverflowError:perplexity=None
    return {'status':'finite_log_probability','mapped_tokens':mapped,'prediction_events':events,
            'log_probability':logp,'probability':probability,'probability_underflow':probability==0.,
            'mean_nll_nats':mean_nll,'perplexity':perplexity,'perplexity_overflow':perplexity is None,'log_terms':terms}


def evaluate(model,sentences):
    if not isinstance(sentences,(list,tuple)) or not sentences:raise ValueError('A nonempty evaluation collection is required')
    scores=[sequence_score(model,s) for s in sentences];events=sum(s['prediction_events'] for s in scores)
    impossible=sum(s['status']=='zero_probability' for s in scores)
    mean_nll=None if impossible else -math.fsum(s['log_probability'] for s in scores)/events
    try:perplexity=math.exp(mean_nll) if mean_nll is not None else None
    except OverflowError:perplexity=None
    return {'sentences':len(scores),'prediction_events':events,'zero_probability_sentences':impossible,
            'mean_nll_nats':mean_nll,'perplexity':perplexity,
            'null_scope':'Null means mathematically infinite after a zero event, or numeric exp overflow; inspect zero_probability_sentences and mean_nll_nats.'}


def generate(model,seed=7,max_new_tokens=20,prefix=()):
    if type(seed) is not int or type(max_new_tokens) is not int or max_new_tokens<0:raise ValueError('Integer seed and nonnegative generation cap required')
    prefix=mapped_tokens(model,prefix);history=list(context_key(model,prefix));rng=random.Random(seed);generated=[];ended=False
    for _ in range(max_new_tokens):
        probabilities=distribution(model,history);positive=[(w,p) for w,p in probabilities.items() if p>0]
        threshold=rng.random()*math.fsum(p for _,p in positive);cumulative=0.;chosen=positive[-1][0]
        for word,probability in positive:
            cumulative+=probability
            if threshold<cumulative:chosen=word;break
        if chosen==EOS:ended=True;break
        generated.append(chosen);history=(history+[chosen])[-(model['order']-1):] if model['order']>1 else []
    return {'mapped_prefix':prefix,'generated':generated,'ended_with_eos':ended,
            'stop_reason':'EOS' if ended else 'length_cap','prediction_draws':len(generated)+int(ended),
            'seed':seed,'max_new_tokens':max_new_tokens}


def demo():
    train=[['red','birds','sing'],['blue','birds','fly'],['red','birds','fly'],['blue','fish','swim']]
    tests={'seen':['red','birds','fly'],'recombined':['blue','birds','sing'],'unknown':['green','birds','fly']}
    configurations=[('unigram_mle',1,0.),('bigram_mle',2,0.),('trigram_mle',3,0.),('trigram_add_half',3,.5)]
    models={name:fit(train,order,alpha) for name,order,alpha in configurations};results={}
    for name,model in models.items():
        results[name]={'order':model['order'],'alpha':model['alpha'],'vocabulary':model['vocabulary'],
                       'training':evaluate(model,train),'test_scores':{key:sequence_score(model,s) for key,s in tests.items()},
                       'sample':generate(model),'contexts':len(model['counts'])}
    coarse=fit(train,2,.5,min_count=2)
    return {'training_sentences':train,'training_prediction_events':16,'conditions':tests,'results':results,
            'bigram_birds_distribution':distribution(models['bigram_mle'],['birds']),
            'vocabulary_change':{'vocabulary':coarse['vocabulary'],'observed_unk_targets':coarse['observed_unk_targets'],
                                 'mapped_training':[mapped_tokens(coarse,s) for s in train],
                                 'scores':{name:sequence_score(coarse,s) for name,s in tests.items()},
                                 'comparable_to_full_vocabulary':False},
            'scope':'Original tiny pretokenized corpus, training-only vocabulary and one scored EOS per sentence. Add-half is a baseline, not advanced smoothing. Perplexity compares the same events/vocabulary convention; no real-language benchmark.'}


if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2,allow_nan=False))

The resulting probabilities for the three diagnostic sentences are:

Modelred birds flyblue birds singgreen birds fly
Bigram MLE1/31/120
Trigram MLE1/400
Trigram add-half0.01004042950.00168280920.0002793140

Every entry includes EOS; green maps to UNK. Compare the two MLE rows before viewing smoothing. The zero for the recombined trigram is a missing conditional event, not a failure to tokenize or a numeric underflow. The sampled output also records whether it ended at EOS or the cap and uses a local seeded random generator.

For E training prediction events and fixed order n, count construction takes expected O(En), treating token hashing/equality as fixed cost and ignoring the cost of reading character strings; vocabulary sorting adds O(|V|log|V|). Sparse count storage is O(En+|V|) in the worst case. This deliberately transparent scorer constructs a full |V|-entry distribution for each event, so scoring T events costs O(T(|V|+n)) and uses O(T+|V|+n) additional space for log traces and temporary tables. It does not materialize a |V|^n dense tensor. A production scorer could directly retrieve the target probability, cache context totals and avoid full tables; that optimization is not present here.

The accompanying tests check counts and EOS by hand, normalization and probability products, fixed vocabulary, event-weighted perplexity, extreme smoothing, genuine zero events versus underflow, and generation caps. These checks do not establish useful language generation on real data.

What the count table cannot remember

A fixed short history cannot distinguish two contexts with the same final n−1 tokens. Increasing n splits those contexts but grows the number of possible histories and makes data sparse. Additive smoothing supplies missing mass uniformly over targets; it does not use the structure of related histories. Backoff, interpolation and more sophisticated smoothing address that issue in separate topics; neural language models use learned representations rather than this explicit count table.

Perplexity measures prediction under a particular event convention, not factual correctness, grammaticality of every sample or usefulness to a reader. The four invented training sentences deliberately make conditional differences visible. A real evaluation needs documented data provenance, a fixed tokenizer/vocabulary mapping, held-out text and an unmodified baseline. Report train and evaluation losses separately, and do not interpret a short fluent sample as coverage of the underlying distribution.

Count the event that a casual calculation forgets

  1. Why do the four three-token training sentences contribute16 events rather than12 or20 in this program?

Answer: Each contributes three ordinary targets and one EOS, so4×4=16. BOS markers provide history and are never predicted. Even a trigram’s two BOS markers do not add prediction events.

  1. Compute the bigram probability and perplexity of blue birds sing.

Answer: Include EOS: (1/2)×(1/2)×(1/3)×1=1/12. Four predicted events give PP=12^(1/4), about1.861210. The unseen complete sentence has positive probability because each required bigram occurred.

  1. At blue birds, what is the add-half probability of sing? Why is allocating UNK alone insufficient to fix MLE zeros?

Answer: The denominator is1+0.5×9=5.5, and the sing numerator is0.5, giving1/11. In unsmoothed MLE, an allocated but never observed UNK still has count zero. Vocabulary membership and assigned probability are separate decisions.

  1. One evaluation sentence has2 prediction events and total negative log likelihood2 nats; another has8 events and loss16 nats. What is aggregate perplexity, and may a different-UNK vocabulary be compared to it directly?

Answer: Total loss18 divided by10 events gives H=1.8 and PP=e^1.8, about6.049647. Neither averaging the sentence perplexities nor equally averaging their mean losses gives this value. A changed UNK policy changes the predicted events, so such perplexities cannot by themselves establish a better model of the same original words.

Keep the probability model and the scoring protocol together

The August19,2026 SLP3 chapter supplies the scoped Markov, MLE, boundary-marker and perplexity discussion read for this topic. The pinned NLTK files make additive formulas and base2 API conventions inspectable. The corpus, complete implementation, log-domain diagnostics and arithmetic examples are original; we have not reproduced an advanced smoothing benchmark or run the upstream library. The next experiments should expand data while keeping the probability space and evaluation protocol explicit.

Make a prediction, then check

Can lower perplexity after replacing more words by UNK prove a better language model?

Choose one answer

Learning objectives

  • Derive a fixed-history conditional model from the probability chain rule.
  • Fit counts and a vocabulary from training data only.
  • Explain additive smoothing, zero events and log-domain scoring.
  • Compute event-weighted perplexity with explicit EOS and vocabulary conventions.

Prerequisites & connections

Explore related knowledge →

References

  1. Speech and Language Processing, chapter3: N-gram Language Models (August19,2026)
    Daniel Jurafsky; James H. Martin · 2026
  2. NLTK 3.9.2 MLE and Lidstone formulas
    NLTK contributors · 2025
  3. NLTK 3.9.2 language-model logscore, entropy and perplexity
    NLTK contributors · 2025

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-08 · Codex single-AI-author technical check: scoped SLP3 August19,2026 Markov/MLE/EOS/perplexity and pinned NLTK formulas; seven paired equations, MLE derivation, additive denominator, training-only vocabulary, one EOS per sentence, event-weighted log likelihood, true zeros versus underflow/exp overflow, four explained exercises and computed SVGs. Original four-sentence corpus; not real-language performance or human peer review.

  • Compared both languages: chain rule versus fixed-history assumption, constrained MLE derivation, conditional-count denominator, BOS outside target vocabulary and exactly one EOS, additive mass and finite-state stopping qualification, training-only UNK mapping, event-weighted perplexity, log versus numeric-zero distinction, complexity, seven equations and four explained exercises.
  • Formal suite embeds17 independent count/score/generation cases plus hand probabilities/aggregation and6 publication checks. Four invented sentences,16 targets,V9; threshold2 changes3 targets and V6. Bigram recombination positive, unsmoothed trigram zero, all add-half scores finite. These are diagnostic inputs, not a held-out natural-language benchmark.
  • Four original SVGs bind actual output and raw data. Final isolated bilingual, three-width/four-font validation passed and desktop/mobile screenshots were inspected. Full article acceptance is recorded separately. Single-AI-author technical check, not independent human review; no upstream code copied or executed.
  • Post-registration correction: schema kind changed from invalid algorithm to concept. Exact body, code, equations, references and original six-file freeze preserved; production test-module shadowing fixed. Explicit correction diffs retained; repeat formal/content/build checks before publication acceptance.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.