Lesson 6.2core3 h⚡ live demo

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

  1. TF-IDF = term frequency × log(N/df): frequent-in-document, rare-in-corpus words dominate; compare documents with cosine similarity.
  2. Sparse lexical vectors match exact strings — great for names, IDs and code, blind to synonyms; BM25 is the production refinement.
  3. 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
  1. Unseen n-grams give zero probability; smoothing (add-k, backoff, interpolation, Kneser–Ney) redistributes mass to unseen events.
  2. 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.
  3. Multinomial Naive Bayes is a one-pass, log-linear bag-of-words classifier and a strong text baseline.
  4. 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