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.
What runs in CodeSplash
- LNG001Smoothed n-gram language model Runs in CodeSplash
- N-gram language model perplexity Not verified yet
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
A probability for every next word
ReadA 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.
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.
Counts, plus a little for the unseen
ReadCounting 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:
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.
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.
Turn up α
PredictPredict first
In the same example you raise α from 0.5 to 5. What happens to the three probabilities?
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.
A bigram model is a Markov chain
ExploreThink 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?
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 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.
Kneser–Ney: which words start new pairs
ReadAdd-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.
Two models, one set of held-out rows
Read1-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
Lower is better. A gap that grows with the order means longer contexts are memorized rather than learned.
View data
| Rows | N-gram order | Perplexity |
|---|---|---|
| Training | 1 | 26.403 |
| Held out | 1 | 16.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
| Order | Training perplexity | Held-out perplexity |
|---|---|---|
| 1 | 26.403 | 16.112 |
Least predictable held-out rows
| Row | Words | Unknown | Bits per word |
|---|---|---|---|
| 44 | 10 | 3 | 4.923 |
| 60 | 8 | 3 | 4.876 |
| 40 | 10 | 3 | 4.862 |
| 12 | 13 | 6 | 4.403 |
| 48 | 9 | 5 | 4.270 |
| 56 | 9 | 4 | 4.193 |
| 16 | 11 | 5 | 4.072 |
| 32 | 12 | 6 | 3.994 |
| 8 | 10 | 5 | 3.854 |
| 4 | 12 | 6 | 3.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"))
))
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
| Order | Training perplexity | Held-out perplexity |
|---|---|---|
| 1 | 26.403 | 16.112 |
Least predictable held-out rows
| Row | Words | Unknown | Bits per word |
|---|---|---|---|
| 44 | 10 | 3 | 4.923 |
| 60 | 8 | 3 | 4.876 |
| 40 | 10 | 3 | 4.862 |
| 12 | 13 | 6 | 4.403 |
| 48 | 9 | 5 | 4.270 |
| 56 | 9 | 4 | 4.193 |
| 16 | 11 | 5 | 4.072 |
| 32 | 12 | 6 | 3.994 |
| 8 | 10 | 5 | 3.854 |
| 4 | 12 | 6 | 3.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"}],
})
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
Lower is better. A gap that grows with the order means longer contexts are memorized rather than learned.
View data
| Rows | N-gram order | Perplexity |
|---|---|---|
| Training | 1 | 26.124 |
| Training | 2 | 10.443 |
| Training | 3 | 5.560 |
| Held out | 1 | 15.336 |
| Held out | 2 | 12.849 |
| Held out | 3 | 11.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
| Order | Training perplexity | Held-out perplexity |
|---|---|---|
| 1 | 26.124 | 15.336 |
| 2 | 10.443 | 12.849 |
| 3 | 5.560 | 11.598 |
Least predictable held-out rows
| Row | Words | Unknown | Bits per word |
|---|---|---|---|
| 44 | 10 | 3 | 4.863 |
| 48 | 9 | 5 | 4.648 |
| 60 | 8 | 3 | 4.635 |
| 12 | 13 | 6 | 4.102 |
| 56 | 9 | 4 | 3.879 |
| 40 | 10 | 3 | 3.832 |
| 32 | 12 | 6 | 3.594 |
| 8 | 10 | 5 | 3.484 |
| 52 | 10 | 6 | 3.386 |
| 4 | 12 | 6 | 3.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"))
))
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
| Order | Training perplexity | Held-out perplexity |
|---|---|---|
| 1 | 26.124 | 15.336 |
| 2 | 10.443 | 12.849 |
| 3 | 5.560 | 11.598 |
Least predictable held-out rows
| Row | Words | Unknown | Bits per word |
|---|---|---|---|
| 44 | 10 | 3 | 4.863 |
| 48 | 9 | 5 | 4.648 |
| 60 | 8 | 3 | 4.635 |
| 12 | 13 | 6 | 4.102 |
| 56 | 9 | 4 | 3.879 |
| 40 | 10 | 3 | 3.832 |
| 32 | 12 | 6 | 3.594 |
| 8 | 10 | 5 | 3.484 |
| 52 | 10 | 6 | 3.386 |
| 4 | 12 | 6 | 3.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.
Where it stands in CodeSplash
Read| Entry | In CodeSplash |
|---|---|
| Smoothed n-gram model (LNG001) | Runs in CodeSplash: Language model perplexity, add-one, Kneser–Ney and modified Kneser–Ney |
Check: n-gram models
CheckpointCheck 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.
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