Econometrics bridge: Maximum likelihood for discrete outcomes
Estimated time: 75 min
Lab: Open browser lab
Code: Python · R
Why this should feel familiar
An n-gram model is a conditional-frequency model. It predicts the next token from a short context. If you understand estimating a multinomial probability from counts, you already understand the core estimator.
Mathematical core
Let tokens be \(w_1, \ldots, w_T\). The chain rule gives
\[ p(w_{1:T})=\prod_{t=1}^T p(w_t\mid w_{1:t-1}). \]An n-gram approximation truncates the conditioning history:
\[ p(w_t\mid w_{1:t-1})\approx p(w_t\mid w_{t-n+1:t-1}). \]The unsmoothed MLE is
\[ \hat p(w\mid c)=\frac{N(c,w)}{N(c)}. \]Cross-entropy on a held-out sequence is the negative average log likelihood; perplexity is
\[ \mathrm{PPL}=\exp\left[-\frac1T\sum_t\log p(w_t\mid c_t)\right]. \]This is the language-model analogue of evaluating an out-of-sample log score.
Plain-English translation
ARIMA conditions on recent numeric observations; n-grams condition on recent discrete symbols. Both deliberately compress history. The key difference is that a language model predicts a categorical distribution over a vocabulary.
What changes when we move from econometrics to AI?
The recurring shift is from a small, analyst-specified representation toward a larger learned representation. The underlying statistical questions do not disappear: What is the sample? What is conditioned on? What is estimated? What objective is optimized? Which observations were used to choose hyperparameters? How will uncertainty and distribution shift be handled?
AI terminology becomes much easier when these questions are kept explicit. Whenever you encounter a new architecture, identify four objects: inputs, parameterized transformation, training objective, and evaluation design.
Interactive browser lab
Edit the corpus, choose n, type a context, and inspect the estimated next-token distribution.
Before changing a control, predict the direction of the effect. Then manipulate one control at a time. The goal is not merely to produce a pretty visualization; it is to connect a parameter change to a mathematical statement.
Python and R lab
The Python and R examples implement the same core object as the browser lab. The Python code intentionally favors NumPy and explicit matrix operations. The R code favors base R and explicit loops/matrix algebra. Once the mechanics are clear, the same ideas can be implemented with PyTorch, TensorFlow, JAX, torch for R, or other frameworks.
Check your understanding
- Identify the random variables, observed variables, and estimated parameters in this module.
- State the objective function or equilibrium condition.
- Name the closest concept you already knew from econometrics and one important difference.
- Predict one failure mode caused by poor data, poor optimization, or poor evaluation.
Learner output
Show with one example why increasing n can improve specificity but worsen sparse-data problems.