Skip to content

N-gram language models: counting what comes next

Predict each word from the few words before it, using counts. See why unseen pairs need smoothing, what Kneser–Ney adds over add-one, and fit both on the same held-out rows in CodeSplash.

Applied ~13 min9 steps

What runs in CodeSplash

You will be able to

  • Write a text's probability as a product of next-word probabilities with a finite history
  • Compute an additive-smoothed next-word distribution and say what it does to unseen words
  • Explain the continuation idea behind Kneser–Ney smoothing
  • Compare two n-gram models fairly on the same held-out rows

Read first

01

A probability for every next word

Read

A language modelLanguage modelA probability for the next word given the words before it; an n-gram model looks back n − 1 words. gives a probability to any text. Any probability of a sequence can be written as a chain of next-word probabilities. An n-gramn-gramA run of n words in a row. "Not good" is a 2-gram, and it says something the two words don't say alone. model makes one simplifying bet: only the last n − 1 words matter.

p(w1:T)=∏t=1Tp(wt∣wt−n+1:t−1)p(w_{1:T}) = \prod_{t=1}^{T} p(w_t \mid w_{t-n+1:t-1})

A bigram model (n = 2) predicts each word from the one before it; a trigram model from the two before. The learned quantities are counts from training text. The order n, the smoothing and the vocabulary cutoff are design choices you make.

02

Counts, plus a little for the unseen

Read

Counting alone gives zero probability to any pair the training text never showed, and one zero makes the whole text impossible. Additive smoothingAdditive smoothingAdds a constant α to every count before turning counts into probabilities, so unseen events keep a small share. adds α to every count:

p(w∣h)=c(h,w)+αc(h)+αVp(w \mid h) = \frac{c(h, w) + \alpha}{c(h) + \alpha V}

The reference program has a history followed three times by one word, once by another and never by a third, with α = 0.5 and V = 3. The probabilities come out as 0.636, 0.273 and 0.091. The never-seen word now gets a share, taken from the seen ones.

Reference · LNG001 · Runs in CodeSplashSmoothed n-gram language modelA finite-history probabilistic baseline that predicts words from preceding words. It is useful for small corpora, transparent scoring, domain adaptation, and testing whether a neural model adds value beyond local…

DExplorable · N-gram smoothing and perplexity

Why does a language model need to give probability to word pairs it never saw, and how much?

Sentences

A tiny training set and three held-out sentences.

Model

A unigram ignores context; a bigram conditions on the previous word.

0.10

Pseudo-count added to every possible next word; 0 is maximum likelihood.

  • Held-out sentences
  • Training sentences
Training perplexity
3.30
Held-out perplexity
5.66
Held-out tokens with probability 0
0
Unseen held-out bigrams
4
Probability of the shown pair
0.1038
  • Puzzle: With the bigram model, find a k that gives the lowest held-out perplexity on the sweep.
  • Puzzle: Make the held-out perplexity infinite.
Bigram model with k = 0.10 over 16 vocabulary entries: training perplexity 3.30, held-out perplexity 5.66. The held-out text has 4 word pairs the model never saw, and smoothing gives each of them some probability. Low training perplexity with infinite held-out perplexity is overfitting in its purest form.

Bigram model with k = 0.10 over 16 vocabulary entries: training perplexity 3.30, held-out perplexity 5.66. The held-out text has 4 word pairs the model never saw, and smoothing gives each of them some probability. Low training perplexity with infinite held-out perplexity is overfitting in its purest form.

03

Turn up α

Predict

Predict first

In the same example you raise α from 0.5 to 5. What happens to the three probabilities?

The distribution moves toward equal sharesThe seen word gets even more probabilityNothing changes, because counts dominate
Reveal

They move toward equal shares, one third each. A large α swamps the counts; a tiny α trusts them. With little training text, α decides a lot, so choose it on development text, never on the test set.

04

A bigram model is a Markov chain

Explore

Think of two words, A and B. A bigram model is exactly a table of next-word probabilities: the chance A follows A, B follows A, and so on. That table is a Markov chain.

AExplorable · A Markov chain playground

When tomorrow depends only on today, where does a process settle in the long run?

In the long run, what share of time does the chain spend in A?

0.50
How sure?
0.80
0.60
500
long-run 0.67

The strip shows the first steps: state A in one color, B in the other. Long runs of one color mean a sticky chain.

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Set P(stay in A) high and generate a path: you get long runs of A, the way a bigram model trained on repetitive text produces repetitive text. A bigram model can never remember more than one word back, however long you let it run.

05

Kneser–Ney: which words start new pairs

Read

Add-one treats every unseen pair alike. Kneser–NeyKneser–Ney smoothingSubtracts a discount from every seen count and gives the mass to a lower order built from how many contexts a word follows. does two smarter things. It subtracts a fixed discount from each seen count and hands that mass to a lower-order model. And its lower-order model counts how many different words a word follows, not how often it occurs.

"Francisco" may be frequent, but almost always after "San". As the next word after an unfamiliar history it deserves little probability, and Kneser–Ney gives it little. Modified Kneser–Ney uses three discounts, for counts of one, two, and three or more.

06

Two models, one set of held-out rows

Read
N-gram language model perplexityRecorded · Python and R agreeRecorded 2026-11-25 · 16 values compared
R

1-gram add-one (Laplace): perplexity 16.1 on 15 held-out rows (4.01 bits per word).

Held-out perplexity
16.112
Bits per word
4.010
Training perplexity
26.403
Unknown-word rate
0.4875
Vocabulary
77

Plots

Perplexity by n-gram orderHow does the series move over time, and where is an estimated break?

Lower is better. A gap that grows with the order means longer contexts are memorized rather than learned.

View data
RowsN-gram orderPerplexity
Training126.403
Held out116.112

Assumptions

  • Scored on held-out rows — Scored on 15 held-out rows marked "test" in split; the training rows never include them.
  • Same words and vocabulary — 48.8% of held-out words are unknown (<unk>, minimum count 2). Compare perplexities only between models with the same tokens and unknown-word rule.
  • Rows are independent — The interval resamples whole rows; repeated or threaded rows make it too narrow.

Perplexity by order

OrderTraining perplexityHeld-out perplexity
126.40316.112

Least predictable held-out rows

RowWordsUnknownBits per word
441034.923
60834.876
401034.862
121364.403
48954.270
56944.193
161154.072
321263.994
81053.854
41263.695
  • 1 rows have no text or no training/test label (or no words) and are left out.
  • 49% of held-out words are unknown to the model; perplexity looks better than it would with a full vocabulary.
The exact R script · R R version 4.5.1 (2025-06-13)
# N-gram language model perplexity
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.perplexity 1.1.1 · spec 5090259e35b5c176
# Dataset: txt1_lm (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Rows: text present (and a training/test label when that column is used), at least one word
TEXT <- "text"
SPLIT <- "split"
TOKENS <- "words"
LOWER <- TRUE
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/txt1_lm.parquet", col_select = c(TEXT, SPLIT)))
warnings <- list()
ok <- !is.na(df[[TEXT]])
if (!is.null(SPLIT)) ok <- ok & !is.na(df[[SPLIT]])
docs_all <- lapply(seq_len(nrow(df)), function(i) if (ok[i]) cs_lm_tokenize(as.character(df[[TEXT]][i]), TOKENS, LOWER) else character(0))
rows <- which(ok & lengths(docs_all) > 0)
n_dropped <- nrow(df) - length(rows)
if (n_dropped) warnings <- c(warnings, sprintf("%d rows have no text%s (or no words) and are left out.", n_dropped, if (!is.null(SPLIT)) " or no training/test label" else ""))
if (!length(rows)) cs_error("CS_E_NO_ROWS")  # no row has any words
docs <- docs_all[rows]

# %% Held-out rows: the test label, or a random share on the shared Wichmann-Hill stream
SEED <- 42
if (!is.null(SPLIT)) {
  TEST_LEVEL <- "test"
  is_test <- as.character(df[[SPLIT]][rows]) == TEST_LEVEL
  if (all(is_test) || !any(is_test)) cs_error("CS_E_TOO_FEW_GROUPS", column = SPLIT, min = 2, k = 1)  # needs both training and test rows
} else {
  if (length(rows) < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "A held-out perplexity", min = 2, n = length(rows))
  is_test <- cs_lm_holdout(length(rows), 0.2, SEED)
}
train_docs <- docs[!is_test]
test_docs <- docs[is_test]

# %% Fit: vocabulary from the training rows, counts and discounts for every order
ORDER <- 1L
SMOOTHING <- "laplace"
vocab <- cs_lm_vocabulary(train_docs, 2)
train_ids <- cs_lm_encode(train_docs, vocab)
test_ids <- cs_lm_encode(test_docs, vocab)
model <- cs_lm_fit(train_ids, ORDER, SMOOTHING, length(vocab))

# %% Perplexity for every order up to the chosen one (training and held-out rows)
by_order <- list()
for (k in seq_len(ORDER)) {
  tr <- cs_lm_row_scores(model, train_ids, k)
  te <- cs_lm_row_scores(model, test_ids, k)
  by_order[[k]] <- list(order = k, train = cs_lm_perplexity(tr$lp, tr$n), test = cs_lm_perplexity(te$lp, te$n))
  if (k == ORDER) { lp <- te$lp; n_pred <- te$n; unk <- te$unk }
}

# %% Bootstrap over held-out rows (shared Wichmann-Hill stream)
B <- 0
CONF <- 0.95
ppl <- by_order[[ORDER]]$test
lo <- NULL; hi <- NULL
if (B > 0) {
  reps <- cs_lm_bootstrap(lp, n_pred, B, SEED + 1)
  ci <- cs_tm_percentile_ci(reps, CONF)
  lo <- ci[1]; hi <- ci[2]
}

# %% Artifacts: one row per input row
out <- cs_ml_out_dir("target/academy-parity/run-8142/evaluate.perplexity/laplace_unigram/out-r")
trs <- cs_lm_row_scores(model, train_ids, ORDER)
ti <- 0L; ri <- 0L
art <- vector("list", length(rows))
for (j in seq_along(rows)) {
  if (is_test[j]) { ti <- ti + 1L; a <- lp[ti]; m <- n_pred[ti]; u <- unk[ti]; which_split <- "test" }
  else { ri <- ri + 1L; a <- trs$lp[ri]; m <- trs$n[ri]; u <- trs$unk[ri]; which_split <- "train" }
  art[[j]] <- data.frame(row = as.integer(rows[j] - 1L), split = which_split, tokens = as.integer(m - 1), unknown = as.integer(u),
                         logprob = a, perplexity = exp(-a / m))
}
nanoparquet::write_parquet(do.call(rbind, art), file.path(out, "scores.parquet"))

# %% Result
LABELS <- c(modified_kn = "modified Kneser–Ney", kneser_ney = "Kneser–Ney", laplace = "add-one (Laplace)")
test_words <- sum(n_pred) - length(test_ids)
values <- list(
  n_train = length(train_ids), n_test = length(test_ids), n_dropped = n_dropped,
  train_tokens = sum(lengths(train_ids)), test_tokens = test_words,
  vocab_size = length(vocab), oov_rate = sum(unk) / test_words,
  order = ORDER, smoothing = unname(LABELS[SMOOTHING]),
  perplexity = ppl, perplexity_ci_low = lo, perplexity_ci_high = hi,
  cross_entropy = log2(ppl), train_perplexity = by_order[[ORDER]]$train
)
for (row in by_order) {
  values[[sprintf("perplexity[%d]", row$order)]] <- row$test
  values[[sprintf("train_perplexity[%d]", row$order)]] <- row$train
}
if (SMOOTHING != "laplace") {
  for (k in seq_len(ORDER)) {
    disc <- (if (k == ORDER) model$raw[[k]] else model$cont[[k]])$disc
    if (SMOOTHING == "kneser_ney") {
      values[[sprintf("discount[%d]", k)]] <- disc[1]
    } else {
      values[[sprintf("discount1[%d]", k)]] <- disc[1]
      values[[sprintf("discount2[%d]", k)]] <- disc[2]
      values[[sprintf("discount3[%d]", k)]] <- disc[3]
    }
  }
}
if (is.null(lo)) { values["perplexity_ci_low"] <- list(NULL); values["perplexity_ci_high"] <- list(NULL) }

held <- paste0(sprintf("Scored on %d held-out rows ", length(test_ids)),
               if (!is.null(SPLIT)) sprintf("marked \"%s\" in %s", TEST_LEVEL, SPLIT) else sprintf("drawn at random (%d of %d)", length(test_ids), length(rows)),
               "; the training rows never include them.")
assumptions <- list(
  list(key = "held_out", label = "Scored on held-out rows", status = "pass", detail = held),
  list(key = "same_vocabulary", label = "Same words and vocabulary", status = if (values$oov_rate > 0.1) "warn" else "info",
       detail = sprintf("%.1f%% of held-out words are unknown (<unk>, minimum count 2). Compare perplexities only between models with the same tokens and unknown-word rule.", 100 * values$oov_rate)),
  list(key = "rows_independent", label = "Rows are independent", status = "info",
       detail = "The interval resamples whole rows; repeated or threaded rows make it too narrow.")
)
if (values$oov_rate > 0.1) warnings <- c(warnings, sprintf("%.0f%% of held-out words are unknown to the model; perplexity looks better than it would with a full vocabulary.", 100 * values$oov_rate))
if (by_order[[ORDER]]$train < 0.5 * ppl && ORDER > 1) {
  warnings <- c(warnings, sprintf("Training perplexity (%.1f) is far below held-out perplexity (%.1f): the model has memorized the training rows.", by_order[[ORDER]]$train, ppl))
}

order_rows <- lapply(by_order, function(r) list(order = r$order, train = r$train, test = r$test))
order_cols <- list(list(key = "order", label = "Order", type = "number"), list(key = "train", label = "Training perplexity", type = "number"),
                   list(key = "test", label = "Held-out perplexity", type = "number"))
bits <- (-lp / n_pred) / log(2)
test_rows_idx <- rows[is_test]
top <- head(order(-bits, seq_along(bits), method = "radix"), 10)
surprise_rows <- lapply(top, function(i) list(row = as.integer(test_rows_idx[i]), words = as.integer(n_pred[i] - 1), unknown = as.integer(unk[i]), bits = bits[i]))
surprise_cols <- list(list(key = "row", label = "Row", type = "number"), list(key = "words", label = "Words", type = "number"),
                      list(key = "unknown", label = "Unknown", type = "number"), list(key = "bits", label = "Bits per word", type = "number"))
xs <- rep(vapply(by_order, function(r) r$order, numeric(1)), 2)
ys <- c(vapply(by_order, function(r) r$train, numeric(1)), vapply(by_order, function(r) r$test, numeric(1)))
gs <- c(rep("Training", ORDER), rep("Held out", ORDER))
charts <- list(cs_chart("orders", "series-line", "Perplexity by n-gram order", list(
  x = cs_col("N-gram order", xs, "numeric"),
  y = cs_col("Perplexity", ys, "numeric"),
  group = cs_col("Rows", gs, "categorical", c("Training", "Held out"))
), note = "Lower is better. A gap that grows with the order means longer contexts are memorized rather than learned."))
cs_publish(list(
  title = "N-gram language model perplexity",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = sprintf("%d-gram %s: perplexity %.1f on %d held-out rows (%.2f bits per word).", ORDER, LABELS[[SMOOTHING]], ppl, length(test_ids), log2(ppl)),
  statistics = list(
    list(key = "perplexity", label = "Held-out perplexity", value = ppl),
    list(key = "cross_entropy", label = "Bits per word", value = values$cross_entropy),
    list(key = "train_perplexity", label = "Training perplexity", value = values$train_perplexity),
    list(key = "oov_rate", label = "Unknown-word rate", value = values$oov_rate),
    list(key = "vocab_size", label = "Vocabulary", value = length(vocab))
  ),
  tables = list(
    list(key = "orders", title = "Perplexity by order", columns = order_cols, rows = order_rows),
    list(key = "surprising", title = "Least predictable held-out rows", columns = surprise_cols, rows = surprise_rows)
  ),
  assumptions = assumptions,
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "scores", path = file.path(out, "scores.parquet"), format = "parquet"))
))
Python

1-gram add-one (Laplace): perplexity 16.1 on 15 held-out rows (4.01 bits per word).

Held-out perplexity
16.112
Bits per word
4.010
Training perplexity
26.403
Unknown-word rate
0.4875
Vocabulary
77

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Scored on held-out rows — Scored on 15 held-out rows marked "test" in split; the training rows never include them.
  • Same words and vocabulary — 48.8% of held-out words are unknown (<unk>, minimum count 2). Compare perplexities only between models with the same tokens and unknown-word rule.
  • Rows are independent — The interval resamples whole rows; repeated or threaded rows make it too narrow.

Perplexity by order

OrderTraining perplexityHeld-out perplexity
126.40316.112

Least predictable held-out rows

RowWordsUnknownBits per word
441034.923
60834.876
401034.862
121364.403
48954.270
56944.193
161154.072
321263.994
81053.854
41263.695
  • 1 rows have no text or no training/test label (or no words) and are left out.
  • 49% of held-out words are unknown to the model; perplexity looks better than it would with a full vocabulary.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# N-gram language model perplexity
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.perplexity 1.1.1 · spec 5090259e35b5c176
# Dataset: txt1_lm (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.text import metrics as tm
from codesplash.text import ngram_lm as lm

# %% Rows: text present (and a training/test label when that column is used), at least one word
TEXT = "text"
SPLIT = "split"
TOKENS = "words"
LOWER = True
df = pd.read_parquet("tests/parity/fixtures/txt1_lm.parquet", columns=[TEXT] + ([SPLIT] if SPLIT else []))
warnings = []
ok = df[TEXT].notna().to_numpy()
if SPLIT:
    ok = ok & df[SPLIT].notna().to_numpy()
docs_all = [lm.tokenize(t, TOKENS, LOWER) if o else [] for t, o in zip(df[TEXT], ok)]
rows = np.array([i for i in range(len(df)) if ok[i] and len(docs_all[i]) > 0], dtype=int)
n_dropped = len(df) - len(rows)
if n_dropped:
    warnings.append(f"{n_dropped} rows have no text{' or no training/test label' if SPLIT else ''} (or no words) and are left out.")
if not len(rows):
    cs.cs_error("CS_E_NO_ROWS")  # no row has any words
docs = [docs_all[i] for i in rows]

# %% Held-out rows: the test label, or a random share on the shared Wichmann–Hill stream
SEED = 42
if SPLIT:
    TEST_LEVEL = "test"
    is_test = np.array([str(v) == TEST_LEVEL for v in df[SPLIT].iloc[rows]])
    if is_test.all() or not is_test.any():
        cs.cs_error("CS_E_TOO_FEW_GROUPS", column=SPLIT, min=2, k=1)  # needs both training and test rows
else:
    if len(rows) < 2:
        cs.cs_error("CS_E_TOO_FEW_ROWS", what="A held-out perplexity", min=2, n=len(rows))
    is_test = lm.holdout(len(rows), 0.2, SEED)
train_docs = [d for d, t in zip(docs, is_test) if not t]
test_docs = [d for d, t in zip(docs, is_test) if t]

# %% Fit: vocabulary from the training rows, counts and discounts for every order
ORDER = 1
SMOOTHING = "laplace"
vocab = lm.vocabulary(train_docs, 2)
train_ids = lm.encode(train_docs, vocab)
test_ids = lm.encode(test_docs, vocab)
model = lm.fit(train_ids, ORDER, SMOOTHING, len(vocab))

# %% Perplexity for every order up to the chosen one (training and held-out rows)
by_order = []
for k in range(1, ORDER + 1):
    tr_lp, tr_n, _ = lm.row_scores(model, train_ids, k)
    te_lp, te_n, te_unk = lm.row_scores(model, test_ids, k)
    by_order.append({"order": k, "train": lm.perplexity(tr_lp, tr_n), "test": lm.perplexity(te_lp, te_n)})
    if k == ORDER:
        lp, n_pred, unk = te_lp, te_n, te_unk

# %% Bootstrap over held-out rows (shared Wichmann–Hill stream)
B = 0
CONF = 0.95
ppl = by_order[-1]["test"]
lo = hi = None
if B > 0:
    reps = lm.bootstrap_ppl(lp, n_pred, B, SEED + 1)
    lo, hi = tm.percentile_ci(reps, CONF)

# %% Artifacts: one row per input row
out = csml.out_dir("target/academy-parity/run-8142/evaluate.perplexity/laplace_unigram/out-python")
tr_lp, tr_n, tr_unk = lm.row_scores(model, train_ids, ORDER)
art_rows, ti, ri = [], 0, 0
for j, r in enumerate(rows):
    if is_test[j]:
        a, m, u, which = lp[ti], n_pred[ti], unk[ti], "test"
        ti += 1
    else:
        a, m, u, which = tr_lp[ri], tr_n[ri], tr_unk[ri], "train"
        ri += 1
    art_rows.append({"row": int(r), "split": which, "tokens": int(m) - 1, "unknown": int(u), "logprob": float(a), "perplexity": math.exp(-float(a) / float(m))})
pd.DataFrame(art_rows).to_parquet(os.path.join(out, "scores.parquet"), index=False)

# %% Result
LABELS = {"modified_kn": "modified Kneser–Ney", "kneser_ney": "Kneser–Ney", "laplace": "add-one (Laplace)"}
test_words = float(np.sum(n_pred) - len(test_ids))
values = {
    "n_train": len(train_ids), "n_test": len(test_ids), "n_dropped": n_dropped,
    "train_tokens": int(sum(len(d) for d in train_ids)), "test_tokens": int(test_words),
    "vocab_size": len(vocab), "oov_rate": float(np.sum(unk)) / test_words,
    "order": ORDER, "smoothing": LABELS[SMOOTHING],
    "perplexity": ppl, "perplexity_ci_low": lo, "perplexity_ci_high": hi,
    "cross_entropy": math.log2(ppl), "train_perplexity": by_order[-1]["train"],
}
for row in by_order:
    values[f"perplexity[{row['order']}]"] = row["test"]
    values[f"train_perplexity[{row['order']}]"] = row["train"]
if SMOOTHING != "laplace":
    for k in range(1, ORDER + 1):
        disc = (model["raw"][k] if k == ORDER else model["cont"][k])["disc"]
        if SMOOTHING == "kneser_ney":
            values[f"discount[{k}]"] = disc[0]
        else:
            values[f"discount1[{k}]"], values[f"discount2[{k}]"], values[f"discount3[{k}]"] = disc

held = f"Scored on {len(test_ids)} held-out rows " + (f'marked "{TEST_LEVEL}" in {SPLIT}' if SPLIT else f"drawn at random ({len(test_ids)} of {len(rows)})") + "; the training rows never include them."
assumptions = [
    {"key": "held_out", "label": "Scored on held-out rows", "status": "pass", "detail": held},
    {"key": "same_vocabulary", "label": "Same words and vocabulary", "status": "warn" if values["oov_rate"] > 0.1 else "info",
     "detail": f"{values['oov_rate']:.1%} of held-out words are unknown (<unk>, minimum count 2). Compare perplexities only between models with the same tokens and unknown-word rule."},
    {"key": "rows_independent", "label": "Rows are independent", "status": "info",
     "detail": "The interval resamples whole rows; repeated or threaded rows make it too narrow."},
]
if values["oov_rate"] > 0.1:
    warnings.append(f"{values['oov_rate']:.0%} of held-out words are unknown to the model; perplexity looks better than it would with a full vocabulary.")
if by_order[-1]["train"] < 0.5 * ppl and ORDER > 1:
    warnings.append(f"Training perplexity ({by_order[-1]['train']:.1f}) is far below held-out perplexity ({ppl:.1f}): the model has memorized the training rows.")

order_rows = [{"order": r["order"], "train": r["train"], "test": r["test"]} for r in by_order]
order_cols = [{"key": "order", "label": "Order", "type": "number"}, {"key": "train", "label": "Training perplexity", "type": "number"}, {"key": "test", "label": "Held-out perplexity", "type": "number"}]
bits = [(-float(a) / float(m)) / math.log(2) for a, m in zip(lp, n_pred)]
test_rows_idx = [int(r) for r, t in zip(rows, is_test) if t]
top = sorted(range(len(bits)), key=lambda i: (-bits[i], i))[:10]
surprise_rows = [{"row": test_rows_idx[i] + 1, "words": int(n_pred[i]) - 1, "unknown": int(unk[i]), "bits": bits[i]} for i in top]
surprise_cols = [{"key": "row", "label": "Row", "type": "number"}, {"key": "words", "label": "Words", "type": "number"},
                 {"key": "unknown", "label": "Unknown", "type": "number"}, {"key": "bits", "label": "Bits per word", "type": "number"}]
xs = [r["order"] for r in by_order] * 2
ys = [r["train"] for r in by_order] + [r["test"] for r in by_order]
gs = ["Training"] * ORDER + ["Held out"] * ORDER
charts = [cs.chart("orders", "series-line", "Perplexity by n-gram order", {
    "x": cs.col("N-gram order", xs, "numeric"),
    "y": cs.col("Perplexity", ys, "numeric"),
    "group": cs.col("Rows", gs, "categorical", ["Training", "Held out"]),
}, note="Lower is better. A gap that grows with the order means longer contexts are memorized rather than learned.")]
cs.publish({
    "title": "N-gram language model perplexity",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": len(rows),
    "summary": f"{ORDER}-gram {LABELS[SMOOTHING]}: perplexity {ppl:.1f} on {len(test_ids)} held-out rows ({math.log2(ppl):.2f} bits per word).",
    "statistics": [
        {"key": "perplexity", "label": "Held-out perplexity", "value": ppl},
        {"key": "cross_entropy", "label": "Bits per word", "value": values["cross_entropy"]},
        {"key": "train_perplexity", "label": "Training perplexity", "value": values["train_perplexity"]},
        {"key": "oov_rate", "label": "Unknown-word rate", "value": values["oov_rate"]},
        {"key": "vocab_size", "label": "Vocabulary", "value": len(vocab)},
    ],
    "tables": [
        {"key": "orders", "title": "Perplexity by order", "columns": order_cols, "rows": order_rows},
        {"key": "surprising", "title": "Least predictable held-out rows", "columns": surprise_cols, "rows": surprise_rows},
    ],
    "assumptions": assumptions,
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "scores", "path": os.path.join(out, "scores.parquet"), "format": "parquet"}],
})
N-gram language model perplexityRecorded · Python and R agreeRecorded 2026-11-25 · 29 values compared
R

3-gram modified Kneser–Ney: perplexity 11.6 on 15 held-out rows (3.54 bits per word).

Held-out perplexity
11.598
Bits per word
3.536
Training perplexity
5.560
Unknown-word rate
0.4875
Vocabulary
77

Plots

Perplexity by n-gram orderHow does the series move over time, and where is an estimated break?

Lower is better. A gap that grows with the order means longer contexts are memorized rather than learned.

View data
RowsN-gram orderPerplexity
Training126.124
Training210.443
Training35.560
Held out115.336
Held out212.849
Held out311.598

Assumptions

  • Scored on held-out rows — Scored on 15 held-out rows marked "test" in split; the training rows never include them.
  • Same words and vocabulary — 48.8% of held-out words are unknown (<unk>, minimum count 2). Compare perplexities only between models with the same tokens and unknown-word rule.
  • Rows are independent — The interval resamples whole rows; repeated or threaded rows make it too narrow.

Perplexity by order

OrderTraining perplexityHeld-out perplexity
126.12415.336
210.44312.849
35.56011.598

Least predictable held-out rows

RowWordsUnknownBits per word
441034.863
48954.648
60834.635
121364.102
56943.879
401033.832
321263.594
81053.484
521063.386
41263.284
  • 1 rows have no text or no training/test label (or no words) and are left out.
  • 49% of held-out words are unknown to the model; perplexity looks better than it would with a full vocabulary.
  • Training perplexity (5.6) is far below held-out perplexity (11.6): the model has memorized the training rows.
The exact R script · R R version 4.5.1 (2025-06-13)
# N-gram language model perplexity
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.perplexity 1.1.1 · spec 4951b03decd93f98
# Dataset: txt1_lm (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Rows: text present (and a training/test label when that column is used), at least one word
TEXT <- "text"
SPLIT <- "split"
TOKENS <- "words"
LOWER <- TRUE
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/txt1_lm.parquet", col_select = c(TEXT, SPLIT)))
warnings <- list()
ok <- !is.na(df[[TEXT]])
if (!is.null(SPLIT)) ok <- ok & !is.na(df[[SPLIT]])
docs_all <- lapply(seq_len(nrow(df)), function(i) if (ok[i]) cs_lm_tokenize(as.character(df[[TEXT]][i]), TOKENS, LOWER) else character(0))
rows <- which(ok & lengths(docs_all) > 0)
n_dropped <- nrow(df) - length(rows)
if (n_dropped) warnings <- c(warnings, sprintf("%d rows have no text%s (or no words) and are left out.", n_dropped, if (!is.null(SPLIT)) " or no training/test label" else ""))
if (!length(rows)) cs_error("CS_E_NO_ROWS")  # no row has any words
docs <- docs_all[rows]

# %% Held-out rows: the test label, or a random share on the shared Wichmann-Hill stream
SEED <- 42
if (!is.null(SPLIT)) {
  TEST_LEVEL <- "test"
  is_test <- as.character(df[[SPLIT]][rows]) == TEST_LEVEL
  if (all(is_test) || !any(is_test)) cs_error("CS_E_TOO_FEW_GROUPS", column = SPLIT, min = 2, k = 1)  # needs both training and test rows
} else {
  if (length(rows) < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "A held-out perplexity", min = 2, n = length(rows))
  is_test <- cs_lm_holdout(length(rows), 0.2, SEED)
}
train_docs <- docs[!is_test]
test_docs <- docs[is_test]

# %% Fit: vocabulary from the training rows, counts and discounts for every order
ORDER <- 3L
SMOOTHING <- "modified_kn"
vocab <- cs_lm_vocabulary(train_docs, 2)
train_ids <- cs_lm_encode(train_docs, vocab)
test_ids <- cs_lm_encode(test_docs, vocab)
model <- cs_lm_fit(train_ids, ORDER, SMOOTHING, length(vocab))

# %% Perplexity for every order up to the chosen one (training and held-out rows)
by_order <- list()
for (k in seq_len(ORDER)) {
  tr <- cs_lm_row_scores(model, train_ids, k)
  te <- cs_lm_row_scores(model, test_ids, k)
  by_order[[k]] <- list(order = k, train = cs_lm_perplexity(tr$lp, tr$n), test = cs_lm_perplexity(te$lp, te$n))
  if (k == ORDER) { lp <- te$lp; n_pred <- te$n; unk <- te$unk }
}

# %% Bootstrap over held-out rows (shared Wichmann-Hill stream)
B <- 1000
CONF <- 0.95
ppl <- by_order[[ORDER]]$test
lo <- NULL; hi <- NULL
if (B > 0) {
  reps <- cs_lm_bootstrap(lp, n_pred, B, SEED + 1)
  ci <- cs_tm_percentile_ci(reps, CONF)
  lo <- ci[1]; hi <- ci[2]
}

# %% Artifacts: one row per input row
out <- cs_ml_out_dir("target/academy-parity/run-8142/evaluate.perplexity/mkn_trigram_split/out-r")
trs <- cs_lm_row_scores(model, train_ids, ORDER)
ti <- 0L; ri <- 0L
art <- vector("list", length(rows))
for (j in seq_along(rows)) {
  if (is_test[j]) { ti <- ti + 1L; a <- lp[ti]; m <- n_pred[ti]; u <- unk[ti]; which_split <- "test" }
  else { ri <- ri + 1L; a <- trs$lp[ri]; m <- trs$n[ri]; u <- trs$unk[ri]; which_split <- "train" }
  art[[j]] <- data.frame(row = as.integer(rows[j] - 1L), split = which_split, tokens = as.integer(m - 1), unknown = as.integer(u),
                         logprob = a, perplexity = exp(-a / m))
}
nanoparquet::write_parquet(do.call(rbind, art), file.path(out, "scores.parquet"))

# %% Result
LABELS <- c(modified_kn = "modified Kneser–Ney", kneser_ney = "Kneser–Ney", laplace = "add-one (Laplace)")
test_words <- sum(n_pred) - length(test_ids)
values <- list(
  n_train = length(train_ids), n_test = length(test_ids), n_dropped = n_dropped,
  train_tokens = sum(lengths(train_ids)), test_tokens = test_words,
  vocab_size = length(vocab), oov_rate = sum(unk) / test_words,
  order = ORDER, smoothing = unname(LABELS[SMOOTHING]),
  perplexity = ppl, perplexity_ci_low = lo, perplexity_ci_high = hi,
  cross_entropy = log2(ppl), train_perplexity = by_order[[ORDER]]$train
)
for (row in by_order) {
  values[[sprintf("perplexity[%d]", row$order)]] <- row$test
  values[[sprintf("train_perplexity[%d]", row$order)]] <- row$train
}
if (SMOOTHING != "laplace") {
  for (k in seq_len(ORDER)) {
    disc <- (if (k == ORDER) model$raw[[k]] else model$cont[[k]])$disc
    if (SMOOTHING == "kneser_ney") {
      values[[sprintf("discount[%d]", k)]] <- disc[1]
    } else {
      values[[sprintf("discount1[%d]", k)]] <- disc[1]
      values[[sprintf("discount2[%d]", k)]] <- disc[2]
      values[[sprintf("discount3[%d]", k)]] <- disc[3]
    }
  }
}
if (is.null(lo)) { values["perplexity_ci_low"] <- list(NULL); values["perplexity_ci_high"] <- list(NULL) }

held <- paste0(sprintf("Scored on %d held-out rows ", length(test_ids)),
               if (!is.null(SPLIT)) sprintf("marked \"%s\" in %s", TEST_LEVEL, SPLIT) else sprintf("drawn at random (%d of %d)", length(test_ids), length(rows)),
               "; the training rows never include them.")
assumptions <- list(
  list(key = "held_out", label = "Scored on held-out rows", status = "pass", detail = held),
  list(key = "same_vocabulary", label = "Same words and vocabulary", status = if (values$oov_rate > 0.1) "warn" else "info",
       detail = sprintf("%.1f%% of held-out words are unknown (<unk>, minimum count 2). Compare perplexities only between models with the same tokens and unknown-word rule.", 100 * values$oov_rate)),
  list(key = "rows_independent", label = "Rows are independent", status = "info",
       detail = "The interval resamples whole rows; repeated or threaded rows make it too narrow.")
)
if (values$oov_rate > 0.1) warnings <- c(warnings, sprintf("%.0f%% of held-out words are unknown to the model; perplexity looks better than it would with a full vocabulary.", 100 * values$oov_rate))
if (by_order[[ORDER]]$train < 0.5 * ppl && ORDER > 1) {
  warnings <- c(warnings, sprintf("Training perplexity (%.1f) is far below held-out perplexity (%.1f): the model has memorized the training rows.", by_order[[ORDER]]$train, ppl))
}

order_rows <- lapply(by_order, function(r) list(order = r$order, train = r$train, test = r$test))
order_cols <- list(list(key = "order", label = "Order", type = "number"), list(key = "train", label = "Training perplexity", type = "number"),
                   list(key = "test", label = "Held-out perplexity", type = "number"))
bits <- (-lp / n_pred) / log(2)
test_rows_idx <- rows[is_test]
top <- head(order(-bits, seq_along(bits), method = "radix"), 10)
surprise_rows <- lapply(top, function(i) list(row = as.integer(test_rows_idx[i]), words = as.integer(n_pred[i] - 1), unknown = as.integer(unk[i]), bits = bits[i]))
surprise_cols <- list(list(key = "row", label = "Row", type = "number"), list(key = "words", label = "Words", type = "number"),
                      list(key = "unknown", label = "Unknown", type = "number"), list(key = "bits", label = "Bits per word", type = "number"))
xs <- rep(vapply(by_order, function(r) r$order, numeric(1)), 2)
ys <- c(vapply(by_order, function(r) r$train, numeric(1)), vapply(by_order, function(r) r$test, numeric(1)))
gs <- c(rep("Training", ORDER), rep("Held out", ORDER))
charts <- list(cs_chart("orders", "series-line", "Perplexity by n-gram order", list(
  x = cs_col("N-gram order", xs, "numeric"),
  y = cs_col("Perplexity", ys, "numeric"),
  group = cs_col("Rows", gs, "categorical", c("Training", "Held out"))
), note = "Lower is better. A gap that grows with the order means longer contexts are memorized rather than learned."))
cs_publish(list(
  title = "N-gram language model perplexity",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = sprintf("%d-gram %s: perplexity %.1f on %d held-out rows (%.2f bits per word).", ORDER, LABELS[[SMOOTHING]], ppl, length(test_ids), log2(ppl)),
  statistics = list(
    list(key = "perplexity", label = "Held-out perplexity", value = ppl),
    list(key = "cross_entropy", label = "Bits per word", value = values$cross_entropy),
    list(key = "train_perplexity", label = "Training perplexity", value = values$train_perplexity),
    list(key = "oov_rate", label = "Unknown-word rate", value = values$oov_rate),
    list(key = "vocab_size", label = "Vocabulary", value = length(vocab))
  ),
  tables = list(
    list(key = "orders", title = "Perplexity by order", columns = order_cols, rows = order_rows),
    list(key = "surprising", title = "Least predictable held-out rows", columns = surprise_cols, rows = surprise_rows)
  ),
  assumptions = assumptions,
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "scores", path = file.path(out, "scores.parquet"), format = "parquet"))
))
Python

3-gram modified Kneser–Ney: perplexity 11.6 on 15 held-out rows (3.54 bits per word).

Held-out perplexity
11.598
Bits per word
3.536
Training perplexity
5.560
Unknown-word rate
0.4875
Vocabulary
77

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Scored on held-out rows — Scored on 15 held-out rows marked "test" in split; the training rows never include them.
  • Same words and vocabulary — 48.8% of held-out words are unknown (<unk>, minimum count 2). Compare perplexities only between models with the same tokens and unknown-word rule.
  • Rows are independent — The interval resamples whole rows; repeated or threaded rows make it too narrow.

Perplexity by order

OrderTraining perplexityHeld-out perplexity
126.12415.336
210.44312.849
35.56011.598

Least predictable held-out rows

RowWordsUnknownBits per word
441034.863
48954.648
60834.635
121364.102
56943.879
401033.832
321263.594
81053.484
521063.386
41263.284
  • 1 rows have no text or no training/test label (or no words) and are left out.
  • 49% of held-out words are unknown to the model; perplexity looks better than it would with a full vocabulary.
  • Training perplexity (5.6) is far below held-out perplexity (11.6): the model has memorized the training rows.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# N-gram language model perplexity
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.perplexity 1.1.1 · spec 4951b03decd93f98
# Dataset: txt1_lm (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.text import metrics as tm
from codesplash.text import ngram_lm as lm

# %% Rows: text present (and a training/test label when that column is used), at least one word
TEXT = "text"
SPLIT = "split"
TOKENS = "words"
LOWER = True
df = pd.read_parquet("tests/parity/fixtures/txt1_lm.parquet", columns=[TEXT] + ([SPLIT] if SPLIT else []))
warnings = []
ok = df[TEXT].notna().to_numpy()
if SPLIT:
    ok = ok & df[SPLIT].notna().to_numpy()
docs_all = [lm.tokenize(t, TOKENS, LOWER) if o else [] for t, o in zip(df[TEXT], ok)]
rows = np.array([i for i in range(len(df)) if ok[i] and len(docs_all[i]) > 0], dtype=int)
n_dropped = len(df) - len(rows)
if n_dropped:
    warnings.append(f"{n_dropped} rows have no text{' or no training/test label' if SPLIT else ''} (or no words) and are left out.")
if not len(rows):
    cs.cs_error("CS_E_NO_ROWS")  # no row has any words
docs = [docs_all[i] for i in rows]

# %% Held-out rows: the test label, or a random share on the shared Wichmann–Hill stream
SEED = 42
if SPLIT:
    TEST_LEVEL = "test"
    is_test = np.array([str(v) == TEST_LEVEL for v in df[SPLIT].iloc[rows]])
    if is_test.all() or not is_test.any():
        cs.cs_error("CS_E_TOO_FEW_GROUPS", column=SPLIT, min=2, k=1)  # needs both training and test rows
else:
    if len(rows) < 2:
        cs.cs_error("CS_E_TOO_FEW_ROWS", what="A held-out perplexity", min=2, n=len(rows))
    is_test = lm.holdout(len(rows), 0.2, SEED)
train_docs = [d for d, t in zip(docs, is_test) if not t]
test_docs = [d for d, t in zip(docs, is_test) if t]

# %% Fit: vocabulary from the training rows, counts and discounts for every order
ORDER = 3
SMOOTHING = "modified_kn"
vocab = lm.vocabulary(train_docs, 2)
train_ids = lm.encode(train_docs, vocab)
test_ids = lm.encode(test_docs, vocab)
model = lm.fit(train_ids, ORDER, SMOOTHING, len(vocab))

# %% Perplexity for every order up to the chosen one (training and held-out rows)
by_order = []
for k in range(1, ORDER + 1):
    tr_lp, tr_n, _ = lm.row_scores(model, train_ids, k)
    te_lp, te_n, te_unk = lm.row_scores(model, test_ids, k)
    by_order.append({"order": k, "train": lm.perplexity(tr_lp, tr_n), "test": lm.perplexity(te_lp, te_n)})
    if k == ORDER:
        lp, n_pred, unk = te_lp, te_n, te_unk

# %% Bootstrap over held-out rows (shared Wichmann–Hill stream)
B = 1000
CONF = 0.95
ppl = by_order[-1]["test"]
lo = hi = None
if B > 0:
    reps = lm.bootstrap_ppl(lp, n_pred, B, SEED + 1)
    lo, hi = tm.percentile_ci(reps, CONF)

# %% Artifacts: one row per input row
out = csml.out_dir("target/academy-parity/run-8142/evaluate.perplexity/mkn_trigram_split/out-python")
tr_lp, tr_n, tr_unk = lm.row_scores(model, train_ids, ORDER)
art_rows, ti, ri = [], 0, 0
for j, r in enumerate(rows):
    if is_test[j]:
        a, m, u, which = lp[ti], n_pred[ti], unk[ti], "test"
        ti += 1
    else:
        a, m, u, which = tr_lp[ri], tr_n[ri], tr_unk[ri], "train"
        ri += 1
    art_rows.append({"row": int(r), "split": which, "tokens": int(m) - 1, "unknown": int(u), "logprob": float(a), "perplexity": math.exp(-float(a) / float(m))})
pd.DataFrame(art_rows).to_parquet(os.path.join(out, "scores.parquet"), index=False)

# %% Result
LABELS = {"modified_kn": "modified Kneser–Ney", "kneser_ney": "Kneser–Ney", "laplace": "add-one (Laplace)"}
test_words = float(np.sum(n_pred) - len(test_ids))
values = {
    "n_train": len(train_ids), "n_test": len(test_ids), "n_dropped": n_dropped,
    "train_tokens": int(sum(len(d) for d in train_ids)), "test_tokens": int(test_words),
    "vocab_size": len(vocab), "oov_rate": float(np.sum(unk)) / test_words,
    "order": ORDER, "smoothing": LABELS[SMOOTHING],
    "perplexity": ppl, "perplexity_ci_low": lo, "perplexity_ci_high": hi,
    "cross_entropy": math.log2(ppl), "train_perplexity": by_order[-1]["train"],
}
for row in by_order:
    values[f"perplexity[{row['order']}]"] = row["test"]
    values[f"train_perplexity[{row['order']}]"] = row["train"]
if SMOOTHING != "laplace":
    for k in range(1, ORDER + 1):
        disc = (model["raw"][k] if k == ORDER else model["cont"][k])["disc"]
        if SMOOTHING == "kneser_ney":
            values[f"discount[{k}]"] = disc[0]
        else:
            values[f"discount1[{k}]"], values[f"discount2[{k}]"], values[f"discount3[{k}]"] = disc

held = f"Scored on {len(test_ids)} held-out rows " + (f'marked "{TEST_LEVEL}" in {SPLIT}' if SPLIT else f"drawn at random ({len(test_ids)} of {len(rows)})") + "; the training rows never include them."
assumptions = [
    {"key": "held_out", "label": "Scored on held-out rows", "status": "pass", "detail": held},
    {"key": "same_vocabulary", "label": "Same words and vocabulary", "status": "warn" if values["oov_rate"] > 0.1 else "info",
     "detail": f"{values['oov_rate']:.1%} of held-out words are unknown (<unk>, minimum count 2). Compare perplexities only between models with the same tokens and unknown-word rule."},
    {"key": "rows_independent", "label": "Rows are independent", "status": "info",
     "detail": "The interval resamples whole rows; repeated or threaded rows make it too narrow."},
]
if values["oov_rate"] > 0.1:
    warnings.append(f"{values['oov_rate']:.0%} of held-out words are unknown to the model; perplexity looks better than it would with a full vocabulary.")
if by_order[-1]["train"] < 0.5 * ppl and ORDER > 1:
    warnings.append(f"Training perplexity ({by_order[-1]['train']:.1f}) is far below held-out perplexity ({ppl:.1f}): the model has memorized the training rows.")

order_rows = [{"order": r["order"], "train": r["train"], "test": r["test"]} for r in by_order]
order_cols = [{"key": "order", "label": "Order", "type": "number"}, {"key": "train", "label": "Training perplexity", "type": "number"}, {"key": "test", "label": "Held-out perplexity", "type": "number"}]
bits = [(-float(a) / float(m)) / math.log(2) for a, m in zip(lp, n_pred)]
test_rows_idx = [int(r) for r, t in zip(rows, is_test) if t]
top = sorted(range(len(bits)), key=lambda i: (-bits[i], i))[:10]
surprise_rows = [{"row": test_rows_idx[i] + 1, "words": int(n_pred[i]) - 1, "unknown": int(unk[i]), "bits": bits[i]} for i in top]
surprise_cols = [{"key": "row", "label": "Row", "type": "number"}, {"key": "words", "label": "Words", "type": "number"},
                 {"key": "unknown", "label": "Unknown", "type": "number"}, {"key": "bits", "label": "Bits per word", "type": "number"}]
xs = [r["order"] for r in by_order] * 2
ys = [r["train"] for r in by_order] + [r["test"] for r in by_order]
gs = ["Training"] * ORDER + ["Held out"] * ORDER
charts = [cs.chart("orders", "series-line", "Perplexity by n-gram order", {
    "x": cs.col("N-gram order", xs, "numeric"),
    "y": cs.col("Perplexity", ys, "numeric"),
    "group": cs.col("Rows", gs, "categorical", ["Training", "Held out"]),
}, note="Lower is better. A gap that grows with the order means longer contexts are memorized rather than learned.")]
cs.publish({
    "title": "N-gram language model perplexity",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": len(rows),
    "summary": f"{ORDER}-gram {LABELS[SMOOTHING]}: perplexity {ppl:.1f} on {len(test_ids)} held-out rows ({math.log2(ppl):.2f} bits per word).",
    "statistics": [
        {"key": "perplexity", "label": "Held-out perplexity", "value": ppl},
        {"key": "cross_entropy", "label": "Bits per word", "value": values["cross_entropy"]},
        {"key": "train_perplexity", "label": "Training perplexity", "value": values["train_perplexity"]},
        {"key": "oov_rate", "label": "Unknown-word rate", "value": values["oov_rate"]},
        {"key": "vocab_size", "label": "Vocabulary", "value": len(vocab)},
    ],
    "tables": [
        {"key": "orders", "title": "Perplexity by order", "columns": order_cols, "rows": order_rows},
        {"key": "surprising", "title": "Least predictable held-out rows", "columns": surprise_cols, "rows": surprise_rows},
    ],
    "assumptions": assumptions,
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "scores", "path": os.path.join(out, "scores.parquet"), "format": "parquet"}],
})

Both runs train on the same rows and score the same 15 held-out rows with the same vocabulary. The add-one unigram reaches held-out perplexity 16.1; the modified Kneser–Ney trigram 11.6. Lower is better, and the comparison is fair because only the model changed.

The trigram's training perplexity is 5.56: it knows its own rows far better than new ones. And 48.8% of held-out words were unknown, a warning that this corpus is tiny.

07

Where it stands in CodeSplash

Read
EntryIn CodeSplash
Smoothed n-gram model (LNG001)Runs in CodeSplash: Language model perplexity, add-one, Kneser–Ney and modified Kneser–Ney
08

Check: n-gram models

Checkpoint

Check yourself

A trigram model reads "the bank by the river was". When it predicts the word after "was", what does it use?

Show the answer

Answer: b

A trigram model conditions on the previous two words. Anything earlier, including "bank", is invisible to it: that is the price of a finite history.

Check yourself

Why does an n-gram model need smoothing at all?

Show the answer

Answer: a

The product of next-word probabilities is zero if any factor is zero. Smoothing moves a little probability onto pairs the training text never showed.

Check yourself

In a news corpus "York" is common but almost always follows "New". How does Kneser–Ney's lower-order model treat "York" after an unseen history?

Show the answer

Answer: b

Kneser–Ney's continuation probability counts the distinct contexts a word appears after. A word glued to one context is a poor guess after a new one.

Check yourself

A colleague fits add-one counts and writes "Kneser–Ney model" in the report. Why does the label matter?

Show the answer

Answer: b

Add-one, Kneser–Ney and modified Kneser–Ney redistribute probability differently. A result is only reproducible if its smoothing is named correctly.

09

Recap

Recap
  • An n-gram model predicts each word from the previous n − 1 words, using training counts.
  • Smoothing keeps unseen pairs possible; additive smoothing adds α to every count, Kneser–Ney discounts and backs off to a continuation model.
  • Compare models only on the same held-out rows, tokens and vocabulary. Language model perplexity in CodeSplash fits add-one, Kneser–Ney and modified Kneser–Ney n-gram models in Python and R.

Concepts in this lesson