Evaluating language models
Practical and theoretical notes on how to measure and compare language models, covering intrinsic and extrinsic evaluation, common metrics (perplexity, cross-entropy, precision/recall/F1, BLEU, ROUGE, METEOR, ranking metrics), statistical checks, and worked examples.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Evaluating a language model tells an engineer whether the model approximates real language well and whether it will work in a downstream system (search, translation, summarisation, chatbot). Good evaluation avoids shipping models that look good on training data but fail in production or amplify bias.
Key ideas
Start from first principles: a language model is a probability distribution over sequences of words. Formally, a language model assigns a probability P(w1 … wN) to any sequence of tokens w1 … wN. We use evaluation to estimate how close the model's distribution is to the true (unknown) distribution of language, and how useful its outputs are for tasks.
Define evaluation types:
- Intrinsic evaluation: measure a property of the model itself (e.g., likelihood, perplexity, token-level accuracy). Intrinsic metrics test the model directly.
- Extrinsic evaluation: measure the impact of the model within a downstream task (e.g., BLEU score for machine translation, F1 for named-entity recognition). Extrinsic evaluation runs the model inside the application pipeline and measures task-level performance.
Before using any metric, state the assumptions: most intrinsic metrics assume the test set is an independent sample from the true distribution and that there is no train/test leakage. Extrinsic metrics assume the task evaluation is well-defined and that references (gold labels) are reliable.
Key statistical definitions used in evaluation:
- Cross-entropy between true distribution p and model q over sequences (or tokens) measures average log-loss. It is defined in information-theoretic terms and is the expected negative log-likelihood of the model under the true distribution.
- Perplexity converts cross-entropy into a more interpretable positive number: lower perplexity means the model assigns higher probability to observed data.
Classification / tagging metrics (useful in many NLP tasks): define the confusion matrix and then precision, recall, F1-score. Always draw the confusion matrix on the exam: a 2×2 table with rows as actual classes (Positive, Negative) and columns as predicted classes (Positive, Negative). Label cells TP (true positive), FP (false positive), FN (false negative), TN (true negative). For multi-class or multi-label settings, also state whether you report micro- or macro-averaged (or weighted macro) precision/recall/F1.
For generation tasks (translation, summarisation) automatic metrics attempt to compare a candidate output to one or more references:
- BLEU compares n-gram matches (with clipping) and applies a brevity penalty to avoid very short candidates scoring artificially high. BLEU is geometric mean of n-gram precisions with an exponential brevity penalty.
- ROUGE measures overlap, commonly used for summarisation. ROUGE-N uses n-gram recall; ROUGE-L uses the length of the Longest Common Subsequence (LCS) between candidate and reference to compute recall/precision.
- METEOR aligns unigrams between candidate and reference, scoring matches with weights, and penalises fragmented matches; it often correlates better with human judgements for certain tasks.
Ranking metrics (search, retrieval): Mean Reciprocal Rank (MRR), Mean Average Precision (MAP), Normalized Discounted Cumulative Gain (NDCG) and Hit@K measure how well the model orders relevant items. Define the relevance notion clearly for the task.
Statistical significance and reliability:
- Report confidence intervals (e.g., bootstrap sampling over test examples) for metric estimates. A single number without confidence is fragile.
- Use paired tests (bootstrap, approximate randomization) when comparing two systems on the same test set.
Calibration and bias:
- Calibration asks whether predicted probabilities reflect true frequencies. Use reliability diagrams or expected calibration error (ECE).
- Expected Calibration Error (ECE): partition predictions into B confidence bins;
ECE = Σ_{b=1..B} (n_b/N) · |acc(b) − conf(b)|where n_b is the number of predictions in bin b, acc(b) is empirical accuracy, and conf(b) is mean confidence. - Check the model for known biases and data leakage; automatic metrics will not reveal systematic unfair behaviour.
Human evaluation:
- For many generative tasks automatic metrics are imperfect. Design human studies (clear instructions, multiple annotators, inter-annotator agreement) and use them as the final arbiter.
Draw diagrams when asked: for confusion matrix draw a 2×2 table with TP, FP, FN, TN labels; for BLEU draw candidate and reference sentences and highlight matching n-grams and the lengths c and r used for BP.
Formulas
CrossEntropy = - (1/N) · Σ_{i=1..N} log q(w_i | context_i)
- q(w_i | context_i): model probability of token w_i given its context. N: number of tokens in test set. Units: nats per token if natural log used (unit: nats/token). Applies to evaluation of sequence or token-level language models.
Perplexity = exp(CrossEntropy)
- CrossEntropy as above. Perplexity is unitless > 0 and applies when CrossEntropy uses natural log; it can also be defined with base-2 logs giving perplexity = 2^{CrossEntropy}. In that case cross-entropy units are bits/token, while perplexity remains unitless. Verify which log base is used.
Precision = TP / (TP + FP)
- TP: true positives count; FP: false positives count. Unitless fraction in [0,1]. Applies to classification/tagging.
Recall = TP / (TP + FN)
- FN: false negatives count. Unitless fraction in [0,1].
F1 = 2 · (Precision · Recall) / (Precision + Recall)
- Harmonic mean of precision and recall; unitless in [0,1].
Accuracy = (TP + TN) / (TP + TN + FP + FN) - Overall fraction correct; can be misleading under class imbalance.
BLEU = BP · exp( Σ_{n=1..N} w_n · log p_n )
- p_n: modified (clipped) n-gram precision for n-grams of order n. w_n: weight for order n (commonly 1/N). BP: brevity penalty.
BP = 1 if c > r, else exp(1 - r/c)
- c: length of candidate; r: effective reference length (for multiple references choose r closest to c). Applies in BLEU.
ROUGE-L precision = LCS_len / |candidate| and ROUGE-L recall = LCS_len / |reference|
- LCS_len: length of longest common subsequence between candidate and reference. Units: tokens; apply to summarisation overlap.
ROUGE-L Fβ = (1+β^2) · (P · R) / (β^2 · P + R)(commonly β ≈ 1.2 to weight recall more in summarisation).
MRR = (1/M) · Σ_{i=1..M} (1 / rank_i)
- rank_i: rank position of first relevant document for query i. Unitless; average over M queries.
AP(q) = (1/R) · Σ_{k=1..K} P@k · rel_kandMAP = (1/M) · Σ_{i=1..M} AP(q_i) - rel_k ∈ {0,1} indicates relevance at rank k; P@k is precision at cutoff k; R is the number of relevant items for that query.
Hit@K = (1/M) · Σ_{i=1..M} 1{∃ relevant in top-K for query i} - Fraction of queries with at least one relevant item in the top K.
NDCG@K = DCG@K / IDCG@K with DCG@K = Σ_{i=1..K} (2^{rel_i} - 1) / log2(i+1)
- rel_i: graded relevance of item at rank i. IDCG@K: ideal DCG (sorted by relevance). Unitless in [0,1].
Worked examples
Example 1 — Classification metrics (numerical):
Given a test set with counts TP = 70, FP = 30, FN = 20, TN = 80. Compute precision, recall and F1.
Step 1: Precision formula.
Precision = TP / (TP + FP) = 70 / (70 + 30) = 70 / 100 = 0.70.
Step 2: Recall formula.
Recall = TP / (TP + FN) = 70 / (70 + 20) = 70 / 90 ≈ 0.7777778.
Step 3: F1 formula.
F1 = 2 · (Precision · Recall) / (Precision + Recall)
Compute: 2·(0.70·0.7777778)/(0.70+0.7777778) = 1.0888889 / 1.4777778 ≈ 0.7368421.
Final answers: Precision = 0.70, Recall = 0.7778, F1 = 0.7368 (unitless fractions).
Example 2 — Perplexity for a short sequence (numerical): A model gives probabilities P(w1) = 0.1, P(w2 | w1) = 0.01, P(w3 | w1,w2) = 0.2 for a 3-token test sentence w1 w2 w3. Compute cross-entropy per token and perplexity (use natural log). Step 1: Sequence probability: P(seq) = 0.1 · 0.01 · 0.2 = 0.0002. Step 2: Cross-entropy per token = - (1/N) ln P(seq) = - (1/3) ln(0.0002). Compute ln(0.0002) = ln(2·10^{-4}) = ln 2 + ln(10^{-4}) ≈ 0.693147 − 9.210340 = −8.517193. So cross-entropy = −(1/3)·(−8.517193) = 8.517193/3 ≈ 2.8390643 nats per token. Step 3: Perplexity = exp(Cross-entropy) = exp(2.8390643) ≈ 17.095 (unitless).
Example 3 — BLEU-2 calculation (theory + numbers): Candidate: "the cat is on the mat" (6 tokens). Reference: "there is a cat on the mat" (7 tokens). Unigram matches (clipped): candidate counts {the:2, cat:1, is:1, on:1, mat:1}; reference counts {there:1, is:1, a:1, cat:1, on:1, the:1, mat:1}. Clipped unigram sum = 1 (the) + 1 (cat) + 1 (is) + 1 (on) + 1 (mat) = 5. Unigram precision p1 = 5/6 ≈ 0.8333333. Bigram matches: candidate bigrams {(the cat),(cat is),(is on),(on the),(the mat)} reference bigrams {(there is),(is a),(a cat),(cat on),(on the),(the mat)} overlap = {(on the),(the mat)} so p2 = 2/5 = 0.4. Use BLEU with N=2 and w1 = w2 = 0.5. Geometric mean = exp(0.5·ln p1 + 0.5·ln p2) = sqrt(p1·p2) = sqrt(0.8333333·0.4) ≈ 0.57735027. Compute brevity penalty: candidate length c = 6, reference length r = 7, c < r so BP = exp(1 − r/c) = exp(1 − 7/6) = exp(−1/6) ≈ 0.8464817. BLEU = BP · geometric mean ≈ 0.8464817 · 0.57735027 ≈ 0.4886.
Common mistakes
- Using arithmetic mean instead of geometric mean in BLEU; for sentence-level BLEU, forgetting to apply smoothing when any higher-order p_n = 0 (otherwise BLEU becomes 0).
- Mixing log bases: when giving cross-entropy and perplexity be explicit whether logs are natural or base-2.
- Reporting a single metric value with no confidence interval or test-set size; metrics have sampling variance.
- Using accuracy alone for imbalanced classification tasks; accuracy can be misleading.
- For ROUGE-L, computing longest common substring instead of longest common subsequence (these are different).
- Not checking multiple references in BLEU / not choosing r (reference length) closest to c for BP.
- Treating BLEU/ROUGE/METEOR as perfect proxies for human judgment—always state limitations.
For your exam
Possible question types:
- Define and contrast intrinsic vs extrinsic evaluation. Full marks: clear definitions, one example of each, and advantages/disadvantages.
- Derive relationship between negative log-likelihood, cross-entropy and perplexity. Full marks: show step-by-step derivation from sequence likelihood to average negative log-likelihood to cross-entropy per token and then to perplexity with log base stated.
- Compute precision/recall/F1 from a confusion matrix. Full marks: draw matrix, compute three numbers with formulas and units.
- Compute BLEU (manual) for small candidate and reference. Full marks: show clipped counts, compute p_n, geometric mean, brevity penalty and final BLEU.
- Describe how to perform a statistical significance test comparing two systems. Full marks: name test (bootstrap or approximate randomization), outline resampling steps and how to compute p-value or confidence interval.
- Short note on calibration and reliability diagrams. Full marks: define calibration, describe how to draw reliability diagram and how to compute ECE.
Always: state assumptions, show steps, label diagrams, and give numerical answers with correct rounding.
Quick check
Q1: What does a lower perplexity mean for a language model? (one line) Q2: In BLEU, why use geometric mean of n-gram precisions rather than arithmetic mean? (one line) Q3: Which metric (precision or recall) should you prefer when false positives are more costly than false negatives? (one line) Answers: Lower perplexity means the model assigns higher probability to the test data (better fit).; Geometric mean penalises zero for any n-gram order and balances multiplicatively across orders (so one very bad order cannot be compensated additively).; Precision (because it measures fraction of predicted positives that are correct).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?