Classical NLP and n-gram language models
Counting words was the first language model — and it still earns its keep
Before neural networks, language was modelled by counting. Those methods are not museum pieces: TF-IDF and BM25 are still the strongest lexical retrievers inside hybrid RAG pipelines (9.5 Retrieval quality: hybrid search, reranking, query transforms and metrics), n-gram models define the language-modelling objective that GPT inherits unchanged (7.6 Decoder-only: GPT and autoregressive generation), and perplexity — derived here from cross-entropy (1.9 Information theory: entropy, cross-entropy and KL divergence) — is still how pretraining progress is measured (8.7 Evaluating LLMs).
You'll be able to
- Compute TF-IDF vectors and cosine similarities for a tiny corpus by hand and explain each term
- Factorize a sequence probability with the chain rule, apply the Markov assumption and estimate n-gram probabilities with smoothing
- Derive perplexity from cross-entropy and interpret it as an effective branching factor
- Explain why sparse lexical methods such as BM25 still matter in modern retrieval
Key ideas
- TF-IDF = term frequency × log(N/df): frequent-in-document, rare-in-corpus words dominate; compare documents with cosine similarity.
- Sparse lexical vectors match exact strings — great for names, IDs and code, blind to synonyms; BM25 is the production refinement.
- A language model factorizes P(w₁…w_T) with the chain rule; n-gram models truncate the history to n−1 tokens and estimate probabilities as count ratios.
Show 4 more key ideas
- Unseen n-grams give zero probability; smoothing (add-k, backoff, interpolation, Kneser–Ney) redistributes mass to unseen events.
- Perplexity = 2^(cross-entropy per token) = P(W)^(−1/N): the effective number of equally likely next tokens; lower is better and only comparable under the same tokenizer.
- Multinomial Naive Bayes is a one-pass, log-linear bag-of-words classifier and a strong text baseline.
- The next-token objective and perplexity are unchanged from n-grams to GPT; neural LMs replace count tables with learned functions of embeddings.
Suggested path through this lesson
Text as a bag of words
The simplest representation of a document ignores order entirely: count how often each vocabulary term appears. The bag-of-words vector of a document has one entry per term. Raw counts over-reward long documents and common words, so we re-weight with TF-IDF:
where is the count of term in (often log-scaled), the number of documents and the number of documents containing . A term that appears everywhere ("the") has ; a term that appears in one document gets the maximum weight. (scikit-learn uses the smoothed form and then L2-normalizes each vector.) Documents and queries are then compared with cosine similarity (1.1 Vectors, dot products and norms).
Worked example. Corpus: = "the cat sat", = "the cat ran", = "dogs ran fast"; . Document frequencies: the 2, cat 2, ran 2, sat 1, dogs 1, fast 1. So and (natural logs). Query = "cat sat" has weights (cat 0.405, sat 1.099), norm . Document has weights (the 0.405, cat 0.405, sat 1.099), norm ; has (0.405, 0.405, 0.405), norm . Then
The rare, specific word sat dominates the ranking — exactly the behaviour you want from a search engine. BM25, the standard in search engines, refines TF-IDF with saturating term frequency and document-length normalization; you will meet its formula in 9.5 Retrieval quality: hybrid search, reranking, query transforms and metrics. These vectors are sparse (one dimension per word) and exact: they match the literal string, which is a strength for names, IDs and code and a weakness for synonyms ("car" vs "automobile") — the gap that dense embeddings close (6.3 Word embeddings, 9.2 Embeddings deep dive).
Language models: assigning probability to text
A language model assigns a probability to a sequence of tokens . The chain rule of probability (1.7 Probability II: Bayes, independence, MLE and MAP) factorizes it exactly:
Conditioning on the entire history is impossible to estimate from counts, so an n-gram model makes the Markov assumption . The maximum-likelihood estimate (1.7 Probability II: Bayes, independence, MLE and MAP) is a ratio of counts; for a bigram,
Worked example (Jurafsky & Martin's corpus): ⟨s⟩ I am Sam ⟨/s⟩ · ⟨s⟩ Sam I am ⟨/s⟩ · ⟨s⟩ I do not like green eggs and ham ⟨/s⟩. Then , , , , so
Any sentence containing an unseen bigram gets probability zero, which is fatal for evaluation and for applications. Smoothing fixes this by moving probability mass to unseen events: add- (Laplace) smoothing ; backoff (use a shorter context when the longer one is unseen); interpolation with weights tuned on held-out data; and Kneser–Ney, the best classical method, which estimates a word's unigram weight by how many distinct contexts it follows ("Francisco" is frequent but follows only "San"). The parameter count explodes with : a trigram model over a 50k vocabulary has possible parameters, almost all unseen — the data-sparsity problem neural LMs solve by sharing statistics through embeddings (6.3 Word embeddings).
Perplexity
How good is a language model? Measure the average surprise it assigns to held-out text. The per-token cross-entropy (1.9 Information theory: entropy, cross-entropy and KL divergence) is , and perplexity is its exponential:
Math check. For a model that spreads probability uniformly over equally likely next tokens at every step, , so and . Perplexity is the effective branching factor: a perplexity of 20 means the model is, on average, as uncertain as if it were choosing uniformly among 20 tokens. Lower is better; it is minimized when the model's distribution equals the true distribution (Gibbs' inequality).
Perplexity only compares models that share a tokenizer and test set: changing the tokenization changes and the numbers. Classical trigram models reached perplexities around 100–150 on standard English benchmarks; GPT-2 pushed word-level WikiText perplexity into the teens, and pretraining curves for today's LLMs are still plotted as cross-entropy per token (7.9 Scaling laws and compute-optimal training).
Naive Bayes for text
The multinomial Naive Bayes classifier from 3.7 Naive Bayes and generative vs discriminative models is a bag-of-words model with class-conditional word probabilities: , estimated with Laplace smoothing and computed in log space. It is a linear classifier in log-count space, trains in one pass, and remains a surprisingly strong baseline for topic and spam classification — always run it before anything neural.
Why sparse methods still matter
Lexical retrieval is cheap, interpretable and exact. On the BEIR zero-shot benchmark BM25 remained a strong baseline that many early dense retrievers failed to beat out of domain, and production RAG systems almost always combine BM25 with dense retrieval (9.5 Retrieval quality: hybrid search, reranking, query transforms and metrics). The n-gram lineage matters for a different reason: the next-token objective, the chain-rule factorization and perplexity are exactly what GPT-style models optimize (7.6 Decoder-only: GPT and autoregressive generation). Bengio's 2003 neural language model simply replaced the count table with a learned function of embedded previous words — the step you take next in 6.3 Word embeddings and reproduce in 6.8 Project: character-level language model.
Where this shows up later
- Dense embeddings replace exact word matching — 6.3 Word embeddings, 9.2 Embeddings deep dive; BM25 and hybrid search — 9.5 Retrieval quality: hybrid search, reranking, query transforms and metrics; chunking a corpus for retrieval — 9.4 Chunking and ingestion.
- The next-token objective and perplexity carry straight into RNN LMs — 6.4 Recurrent neural networks and BPTT, GPT — 7.6 Decoder-only: GPT and autoregressive generation, and scaling-law plots — 7.9 Scaling laws and compute-optimal training; perplexity vs task metrics — 8.7 Evaluating LLMs.
Common pitfalls (4)
- Comparing perplexities across models with different tokenizers or test sets.
- Forgetting smoothing and getting zero probability (infinite perplexity) from a single unseen bigram.
- Fitting the IDF statistics on the query set or test documents instead of the indexed corpus.
- Dismissing TF-IDF/BM25 as obsolete — hybrid retrieval usually beats dense-only retrieval.
Recap: all 7 key points
- TF-IDF = term frequency × log(N/df): frequent-in-document, rare-in-corpus words dominate; compare documents with cosine similarity.
- Sparse lexical vectors match exact strings — great for names, IDs and code, blind to synonyms; BM25 is the production refinement.
- A language model factorizes P(w₁…w_T) with the chain rule; n-gram models truncate the history to n−1 tokens and estimate probabilities as count ratios.
- Unseen n-grams give zero probability; smoothing (add-k, backoff, interpolation, Kneser–Ney) redistributes mass to unseen events.
- Perplexity = 2^(cross-entropy per token) = P(W)^(−1/N): the effective number of equally likely next tokens; lower is better and only comparable under the same tokenizer.
- Multinomial Naive Bayes is a one-pass, log-linear bag-of-words classifier and a strong text baseline.
- The next-token objective and perplexity are unchanged from n-grams to GPT; neural LMs replace count tables with learned functions of embeddings.
Watch
A character-level bigram model built from counts — literally an n-gram LM — then re-derived as a one-layer neural net trained with the same negative log-likelihood. Watch the first 60 minutes now.
Read
Try it live
Interactive demo
runs in your browserExercises
- TF-IDF and cosine by hand
Add a fourth document = "the dogs sat" to the worked corpus. Recompute the IDF of every term (N = 4), the TF-IDF vectors of and , and the cosine similarity between them. Expected: sat and the are shared, but the now has even lower IDF, so the similarity is driven almost entirely by sat.
- Bigram model with smoothing
Implement an add-k bigram model on a small text (a short story). Compute the perplexity of a held-out paragraph for k ∈ {0.001, 0.1, 1}. Expected: too-small k blows up on rare bigrams, too-large k flattens the model; an intermediate k minimizes perplexity. Then sample 5 sentences from the model.
- Mini search engine
Use the TF-IDF retriever demo (or
TfidfVectorizer) on 20–50 paragraphs of a document you know well. Issue 10 queries and note where exact-match retrieval fails (synonyms, paraphrases). Expected: a list of failure cases you will revisit with dense embeddings in 9.2 Embeddings deep dive.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →