NLP & Speech

N-gram Language Models

N-gram language models turn local sequence counts into next-token probabilities, exposing both the power of count-based prediction and the zero-probability problem that motivates smoothing.

status: reviewimportance: criticaldifficulty 3/5math: undergraduateread: 16mlive demo

Concept Structure

N-gram Language Models

01Intuition

Start with the picture, metaphor, or geometric mechanism.

02Math

Make the objects explicit and connect them with notation.

03Code

Mirror the equations with runnable implementation details.

04Interactive Demo

Manipulate the mechanism and watch the idea respond.

3prerequisites
4next concepts
3related links

Learner Contract

What this page should let you do.

You are here becauseN-gram language models turn local sequence counts into next-token probabilities, exposing both the power of count-based prediction and the zero-probability problem that motivates smoothing.

This NLP & Speech concept is the current idea: keep the same invariant visible across Intuition, Math, Code, Interactive Demo.

By the end4/4 sections ready | runnable code expected | live demo

Explain the mechanism, trace the main notation, and test one prediction in the live demo.

Do this firstIntuition

Read the intuition before the notation; the math should name a mechanism you already felt.

Test the linkManipulate one control and predict the visible change.Then continue to Smoothing: Laplace and Kneser-Ney (review)

Claim/source review status

Substantive review recorded

1/1 claims have bounded review metadata; still check caveats and source scope.Metadata-derived; review may be AI-assisted. Not a human certification.
Claims1/1 reviewed
Sources3 cited
Codeattached
Demolive
Reviewed2026-07-03
Updatedpage 2026-07-03

Learning item flow

4/4 sections readyAsk about thisResearch room
ConceptN-gram Language ModelsNLP & Speech
3 sources attachedLocal snapshot ready
concept:nlp-speech/ngram-language-models
01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

Section prompt

An n-gram language model is the simplest honest version of next-token prediction: look at a short local context, count what followed that context in training text, and turn those counts into probabilities.

If the context is the, and the training corpus says the cat happened three times while the dog happened twice, the model gives cat more probability than dog. Nothing mystical is happening. The model is a conditional frequency table.

That simplicity is exactly why n-grams are still worth learning. They make three ideas visible before neural language models hide them inside vectors:

  • a language model assigns probability to a sequence one token at a time,
  • local context helps, but only where the corpus has evidence,
  • a single unseen n-gram can collapse an entire sentence probability to zero.

This is the bridge from probability to tokenization and neural LMs. Before a transformer learns dense hidden states, an n-gram model asks the blunt question: “What did this exact local history usually predict?”

Source spine: Jurafsky and Martin, Speech and Language Processing, Chapter 3, Stanford CS224N, and Chen and Goodman, An Empirical Study of Smoothing Techniques for Language Modeling.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

Section prompt

Let a token sequence be w1:T=(w1,,wT)w_{1:T}=(w_1,\dots,w_T). The chain rule says

P(w1:T)=t=1TP(wtw1:t1).P(w_{1:T})=\prod_{t=1}^T P(w_t\mid w_{1:t-1}).

An n-gram model replaces the full history with only the previous n1n-1 tokens:

P(wtw1:t1)P(wtwtn+1:t1).P(w_t\mid w_{1:t-1}) \approx P(w_t\mid w_{t-n+1:t-1}).

For a bigram model, the maximum-likelihood estimate is just a count ratio:

PMLE(wtwt1)=C(wt1,wt)C(wt1).P_{\mathrm{MLE}}(w_t\mid w_{t-1}) = \frac{C(w_{t-1},w_t)}{C(w_{t-1})}.

Here C(wt1,wt)C(w_{t-1},w_t) counts adjacent token pairs, and C(wt1)=vC(wt1,v)C(w_{t-1})=\sum_v C(w_{t-1},v) counts how often the context appeared with any next token.

The problem appears when C(wt1,wt)=0C(w_{t-1},w_t)=0. Then the whole sentence product can become zero, even if the sentence is perfectly reasonable.

A first repair is add-one smoothing:

P+1(wth)=C(h,wt)+1C(h)+V,P_{+1}(w_t\mid h) = \frac{C(h,w_t)+1}{C(h)+|\mathcal V|},

where hh is the n-gram history and V\mathcal V is the next-token vocabulary. Add-one smoothing is easy to see, but it is usually too blunt for serious systems. Its job here is pedagogical: it shows why probability mass must be reserved for unseen events.

For a held-out sequence with NN predicted tokens, perplexity is

PPL(w1:N)=exp(1Nt=1NlogP(wtht)).\operatorname{PPL}(w_{1:N}) = \exp\left(-\frac{1}{N}\sum_{t=1}^N \log P(w_t\mid h_t)\right).

Lower perplexity means the model assigned more probability to the held-out text. If any unsmoothed probability is zero, the log probability is -\infty and perplexity becomes infinite.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

Section prompt

This small script computes bigram MLE and add-one probabilities on a tiny corpus. It stays deliberately small so the count table and sentence probability are inspectable.

from collections import Counter, defaultdict
from math import exp, log, isinf

train = [
    "the cat sat",
    "the cat slept",
    "the cat purred",
    "the dog sat",
    "a dog barked",
    "the dog barked",
]

def tokens(sentence):
    return ["<s>"] + sentence.split() + ["</s>"]

pairs = Counter()
contexts = Counter()
vocab = set(["</s>"])

for sentence in train:
    seq = tokens(sentence)
    vocab.update(seq[1:])
    for left, right in zip(seq, seq[1:]):
        pairs[(left, right)] += 1
        contexts[left] += 1

def prob(left, right, alpha=0.0):
    return (pairs[(left, right)] + alpha) / (contexts[left] + alpha * len(vocab))

def score(sentence, alpha=0.0):
    seq = tokens(sentence)
    logp = 0.0
    zero = []
    for left, right in zip(seq, seq[1:]):
        p = prob(left, right, alpha)
        if p == 0:
            zero.append((left, right))
        else:
            logp += log(p)
    if zero:
        return 0.0, float("inf"), zero
    n = len(seq) - 1
    return exp(logp), exp(-logp / n), zero

for word in ["cat", "dog", "barked", "slept"]:
    print(f"P({word} | the) =", round(prob("the", word), 3))

print("MLE:", score("the dog slept", alpha=0.0))
print("add-one:", score("the dog slept", alpha=1.0))

The unsmoothed model gives the dog slept zero probability because it never saw dog slept. Add-one smoothing gives that unseen bigram a small nonzero probability, so the sentence probability and perplexity become finite.

04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

Section prompt

Prediction check: choose the model order and smoothing setting, then predict which next word wins and whether the held-out sentence gets zero probability before revealing the table.

The lab hides the winning next token, token-by-token held-out probabilities, zero-probability transitions, sentence probability, and perplexity until you commit. The goal is to feel how local count evidence becomes sequence-level probability, and why smoothing is not optional once held-out text contains unseen n-grams.

Live Concept Demo

Explore N-gram Language Models

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 3/5undergraduatecode-aligned
Demo Prediction Checkpoint

Manipulate one control and predict the visible change.

Commit to what N-gram Language Models should make visible before reading the result.

After The First Pass

Turn the concept into an inspected object.

Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.

Mechanism Storyboard

See the idea move before the page explains it

N-gram language models turn local sequence counts into next-token probabilities, exposing both the power of count-based prediction and the zero-probability problem that motivates smoothing.

Prediction open01 / Intuition
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change N-gram Language Models should make visible.

Visual Inquiry

Make the image answer a mathematical question

N-gram language models turn local sequence counts into next-token probabilities, exposing both the power of count-based prediction and the zero-probability problem that motivates smoothing.

4/4 stages readyLive demo connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make N-gram Language Models easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

book · 2026Speech and Language Processing, Chapter 3: N-gram Language ModelsJurafsky and Martin

Source for n-gram language models, Markov context truncation, maximum-likelihood n-gram probabilities from counts, sentence probability, sparsity, smoothing motivation, and perplexity evaluation.

Open source
course-notes · 2026Stanford CS224N: Natural Language Processing with Deep LearningStanford CS224N

Course-level source for the classical-to-neural NLP route and for treating language modeling as a central sequence prediction problem.

Open source
paper · 1998An Empirical Study of Smoothing Techniques for Language ModelingChen and Goodman

Primary source for smoothing as substantive language-modeling machinery; this page only uses add-one as a first visible repair before a later Kneser-Ney page.

Open source

Claim Review

N-gram language models turn local sequence counts into next-token probabilities, exposing both the power of count-based prediction and the zero-probability problem that motivates smoothing.

Status1 substantive review recorded

Claims without a substantive review badge still need exact source-support review.

Sources3 references

jurafsky-martin-slp3-ngram, cs224n-course, chen-goodman-1998-smoothing

Local checks4 local checks

Use equations, runnable code, and demos to check whether the source support is operational.

Substantively reviewedAn n-gram language model estimates next-token probabilities from local context counts; this makes sentence probabilities and perplexity computable, but unseen n-grams can assign zero probability unless smoothing or backoff changes the estimate.Claim metadata: source checked

SLP3 supports the core n-gram count/probability/perplexity/sparsity claims; CS224N supports the NLP route context; Chen-Goodman supports treating smoothing as a substantive follow-up rather than a footnote.

Sources: Speech and Language Processing, Chapter 3: N-gram Language Models, Stanford CS224N: Natural Language Processing with Deep Learning, An Empirical Study of Smoothing Techniques for Language ModelingThe demo uses a tiny corpus, MLE, and add-one smoothing only. It does not claim add-one is state of the art, does not cover interpolation/backoff/Kneser-Ney in full, and does not model neural language-model behavior.A bounded review summary is present; still check caveats and exact reference scope.

Checked SLP3 Chapter 3 for n-gram probability estimation, Markov context truncation, count-based MLE, sentence probability, zero-probability sparsity, smoothing motivation, and perplexity. Checked Stanford CS224N as the route-level NLP/deep-learning course anchor and Chen-Goodman for smoothing as serious language-modeling machinery. GPT Pro/Oracle publication critique is pending because 127.0.0.1:51672 is unavailable.

Reviewer: codex-local-primary-source-audit; reviewed 2026-07-03

Practice Loop

Try the idea before it explains itself

N-gram language models turn local sequence counts into next-token probabilities, exposing both the power of count-based prediction and the zero-probability problem that motivates smoothing.

Readiness0/3 checks ready
Predict

Before touching the demo, predict one visible change that should happen in N-gram Language Models.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Grounded research drawerClose
ConceptN-gram Language ModelsNLP & Speech
Runnable code comparisonN-gram Language Models runnable code 1train = [Prediction before revealN-gram Language Models interactive demoManipulate one control and predict the visible change.
Grounded room questionWhat is the smallest example that makes N-gram Language Models click without losing the math?Local snapshot ready

Research Room

Attach the question to a claim, equation, code, or demo

Pick the concept, equation, source, runnable code, claim, misconception, or demo state before asking for help. The handoff keeps that page item in context.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptNLP & Speech

N-gram Language Models

Attached question

What is the smallest example that makes N-gram Language Models click without losing the math?

Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays in this browser, attached to the selected learning item.

No local draft saved.
Evidence to inspect
  • References to inspect: attached references on this page.
  • Definition, prerequisite, and contrast concept links
  • The equation or runnable code that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Grounded AI handoff

I am working in Continuous Function's research reading room. Object: concept - N-gram Language Models Selected item key: recorded for copy. Context: NLP & Speech Page anchor: recorded for copy. Open question: What is the smallest example that makes N-gram Language Models click without losing the math? Evidence to inspect: - References to inspect: attached references on this page. - Definition, prerequisite, and contrast concept links - The equation or runnable code that makes the concept operational - One demo state that shows the invariant instead of a slogan What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action.

View it in context
concept/concept-notebook/nlp-speech/ngram-language-models concept:nlp-speech/ngram-language-models