This NLP & Speech concept is the current idea: keep the same invariant visible across Intuition, Math, Code, Interactive Demo.
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.
Concept Structure
N-gram Language Models
Start with the picture, metaphor, or geometric mechanism.
Make the objects explicit and connect them with notation.
Mirror the equations with runnable implementation details.
Manipulate the mechanism and watch the idea respond.
Learner Contract
What this page should let you do.
3 prerequisites listed; refresh them before leaning on the math or code.
Explain the mechanism, trace the main notation, and test one prediction in the live demo.
Read the intuition before the notation; the math should name a mechanism you already felt.
Follow this edge after making one prediction here; the next page should reuse the result, not restart the route.
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.01
Intuition
Build the mental picture first so the rest of the page has something to attach to.
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
Math
Translate the story into symbols, assumptions, and a derivation you can inspect.
Let a token sequence be . The chain rule says
An n-gram model replaces the full history with only the previous tokens:
For a bigram model, the maximum-likelihood estimate is just a count ratio:
Here counts adjacent token pairs, and counts how often the context appeared with any next token.
The problem appears when . Then the whole sentence product can become zero, even if the sentence is perfectly reasonable.
A first repair is add-one smoothing:
where is the n-gram history and 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 predicted tokens, perplexity is
Lower perplexity means the model assigned more probability to the held-out text. If any unsmoothed probability is zero, the log probability is and perplexity becomes infinite.
03
Code
Keep the implementation aligned with the notation so the algorithm is legible.
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
Interactive Demo
Use direct manipulation to connect the explanation to a moving system.
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.
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.
Start with the picture, metaphor, or geometric mechanism.
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.
Which visible object should carry the first intuition?
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.
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 sourceCourse-level source for the classical-to-neural NLP route and for treating language modeling as a central sequence prediction problem.
Open sourcePrimary 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 sourceClaim 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.
Claims without a substantive review badge still need exact source-support review.
jurafsky-martin-slp3-ngram, cs224n-course, chen-goodman-1998-smoothing
Use equations, runnable code, and demos to check whether the source support is operational.
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-03Source support candidates
book 2026Speech and Language Processing, Chapter 3: N-gram Language ModelsSource for n-gram language models, Markov context truncation, maximum-likelihood n-gram probabilities from counts, sentence probability, sparsity, smoothing motivation, and perplexity evaluation.
course-notes 2026Stanford CS224N: Natural Language Processing with Deep LearningCourse-level source for the classical-to-neural NLP route and for treating language modeling as a central sequence prediction problem.
paper 1998An Empirical Study of Smoothing Techniques for Language ModelingPrimary 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.
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.
Before touching the demo, predict one visible change that should happen in N-gram Language Models.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
A concrete answer is on the canvas.
The answer names why the claim should hold.
It touches the page context or a neighboring idea.
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.Open the draft below to save one note and next action in this browser.
N-gram Language Models
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
This draft stays in this browser, attached to the selected learning item.
- 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
- 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
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.
concept/concept-notebook/nlp-speech/ngram-language-models
concept:nlp-speech/ngram-language-models