How predictable is this text? Perplexity, and error rates for transcripts
Fit a word n-gram language model and read held-out perplexity order by order, see why smoothing matters, and score transcripts with word and character error rates.
What runs in CodeSplash
- N-gram language model perplexity Not verified yet
- Generated-text metrics (BLEU, chrF, ROUGE) Verified in Python and R
You will be able to
- Read perplexity, bits per word and the unknown-word rate of a held-out text
- Explain why Kneser–Ney smoothing beats add-one and why training perplexity flatters
- Report WER and CER with their substitutions, deletions and insertions
Read first
A model of the 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 for the next word given the words before it. 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 looks back n − 1 words: a trigram model predicts each word from the two before it.
The model is fitted to some rows and scored on rows it never saw. Its perplexityPerplexity (language model)exp of the average negative log probability per word: how many equally likely words the model is choosing between. is the exponential of the average negative log probability per held-out word. Read it as "the model is choosing between this many equally likely words". Lower is better.
Three orders on one text
Read3-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"}],
})
The text column has 46 training rows and 15 held-out rows. Single words give perplexity 15.3. Word pairs bring it to 12.8 and the trigram model to 11.6, which is 3.54 bits per wordBits per wordlog₂ of perplexity: the average number of bits needed to encode each held-out word with the model..
View data
| month | index |
|---|---|
| 1,262,304,000,000 | 11.190 |
| 1,264,982,400,000 | 9.010 |
| 1,267,401,600,000 | 10.200 |
| 1,270,080,000,000 | 11.720 |
| 1,272,672,000,000 | 10.110 |
| 1,275,350,400,000 | 11.700 |
| 1,277,942,400,000 | 12.030 |
| 1,280,620,800,000 | 9.680 |
| 1,283,299,200,000 | 8.220 |
| 1,285,891,200,000 | 9.540 |
| 1,288,569,600,000 | 11.370 |
| 1,291,161,600,000 | 12.550 |
| 1,293,840,000,000 | 9.930 |
| 1,296,518,400,000 | 9.460 |
| 1,298,937,600,000 | 11.740 |
| 1,301,616,000,000 | 11.090 |
| 1,304,208,000,000 | 10.580 |
| 1,306,886,400,000 | 10.630 |
| 1,309,478,400,000 | 11.030 |
| 1,312,156,800,000 | 11.600 |
| 1,314,835,200,000 | 12.180 |
| 1,317,427,200,000 | 11.100 |
| 1,320,105,600,000 | 11.650 |
| 1,322,697,600,000 | 9.980 |
| 1,325,376,000,000 | 10.020 |
| 1,328,054,400,000 | 9.710 |
| 1,330,560,000,000 | 9 |
| 1,333,238,400,000 | 9.620 |
| 1,335,830,400,000 | 9.500 |
| 1,338,508,800,000 | 9.450 |
| 1,341,100,800,000 | 9.110 |
| 1,343,779,200,000 | 8.700 |
| 1,346,457,600,000 | 11.130 |
| 1,349,049,600,000 | 11.160 |
| 1,351,728,000,000 | 10 |
| 1,354,320,000,000 | 10.100 |
| 1,356,998,400,000 | 9.540 |
| 1,359,676,800,000 | 8.240 |
| 1,362,096,000,000 | 11.990 |
| 1,364,774,400,000 | 9.490 |
| 1,367,366,400,000 | 7.490 |
| 1,370,044,800,000 | 9.140 |
| 1,372,636,800,000 | 9.670 |
| 1,375,315,200,000 | 10.170 |
| 1,377,993,600,000 | 10.300 |
| 1,380,585,600,000 | 9.460 |
| 1,383,264,000,000 | 10.770 |
| 1,385,856,000,000 | 9.880 |
| 1,388,534,400,000 | 9.900 |
| 1,391,212,800,000 | 10.540 |
| 1,393,632,000,000 | 12.060 |
| 1,396,310,400,000 | 11.380 |
| 1,398,902,400,000 | 8.100 |
| 1,401,580,800,000 | 9.060 |
| 1,404,172,800,000 | 10.890 |
| 1,406,851,200,000 | 10.100 |
| 1,409,529,600,000 | 10.320 |
| 1,412,121,600,000 | 12.830 |
| 1,414,800,000,000 | 12.010 |
| 1,417,392,000,000 | 11.980 |
First 60 of 120 rows.
The training rows tell a different story. Their trigram perplexity is 5.6, far below the held-out value. Longer contexts mostly repeat word sequences the model has already seen. Only the held-out line says how well it predicts new text.
Check yourself
A trigram model has training perplexity 6 and held-out perplexity 14. What should you report?
Show the answer
Answer: b
Training perplexity always flatters, and the gap grows with the order. Report the held-out value, with its interval.
Unknown words and smoothing
ReadA word the model never saw would get probability zero, and one zero makes perplexity infinite. So rare training words become <unk>, and so do new words at test time: they are unknown wordsUnknown-word rateShare of held-out words the model maps to <unk> because they were rare or absent in training.. Here 49% of held-out words are unknown, which the card warns about. A cheap prediction for every <unk> makes perplexity look better than it is.
Smoothing
ReadSmoothing moves probability from seen word sequences to unseen ones. Kneser–Ney smoothingKneser–Ney smoothingSubtracts a discount from every seen count and gives the mass to a lower order built from how many contexts a word follows. subtracts a discountKneser–Ney discountThe count subtracted from each seen sequence at one order (one value, or one each for counts 1, 2 and 3+), estimated from the counts. from every seen count. It gives that mass to a lower order built from how many different words come before each word, so "Francisco" (always after "San") gets little weight on its own.
Add-one smoothing
ReadAdd-one smoothing adds 1 to every count:
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
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"}],
})
Add-one gives perplexity 16.1 on single words, against 15.3 with modified Kneser–Ney on the same rows. The gap widens at higher orders, where most sequences are unseen and adding 1 to each of them takes most of the probability.
Check yourself
Model A (minimum word count 1) has perplexity 40; model B (minimum count 5) has 25 on the same held-out rows. Is B better?
Show the answer
Answer: b
Perplexities compare models only with the same words and the same unknown-word rule. Check the unknown-word rate before comparing.
Without a training/test column, the method holds out a random share of rows on the shared random stream, so Python and R hold out the same rows:
2-gram Kneser–Ney: perplexity 13.2 on 15 held-out rows (3.72 bits per word).
- Held-out perplexity
- 13.158
- Bits per word
- 3.718
- Training perplexity
- 7.744
- Unknown-word rate
- 0.4356
- Vocabulary
- 76
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 | 24.241 |
| Training | 2 | 7.744 |
| Held out | 1 | 17.129 |
| Held out | 2 | 13.158 |
Assumptions
- Scored on held-out rows — Scored on 15 held-out rows drawn at random (15 of 61); the training rows never include them.
- Same words and vocabulary — 43.6% 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 | 24.241 | 17.129 |
| 2 | 7.744 | 13.158 |
Least predictable held-out rows
| Row | Words | Unknown | Bits per word |
|---|---|---|---|
| 58 | 11 | 4 | 4.788 |
| 54 | 11 | 5 | 4.409 |
| 60 | 8 | 3 | 4.301 |
| 11 | 12 | 3 | 4.066 |
| 12 | 13 | 6 | 3.955 |
| 26 | 12 | 6 | 3.923 |
| 59 | 11 | 4 | 3.745 |
| 33 | 11 | 6 | 3.725 |
| 23 | 11 | 5 | 3.692 |
| 6 | 13 | 6 | 3.620 |
- 1 rows have no text (or no words) and are left out.
- 44% 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 b453844b944cad14
# 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 <- NULL
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.25, SEED)
}
train_docs <- docs[!is_test]
test_docs <- docs[is_test]
# %% Fit: vocabulary from the training rows, counts and discounts for every order
ORDER <- 2L
SMOOTHING <- "kneser_ney"
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 <- 300
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/kn_bigram_random_holdout/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"))
))
2-gram Kneser–Ney: perplexity 13.2 on 15 held-out rows (3.72 bits per word).
- Held-out perplexity
- 13.158
- Bits per word
- 3.718
- Training perplexity
- 7.744
- Unknown-word rate
- 0.4356
- Vocabulary
- 76
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 drawn at random (15 of 61); the training rows never include them.
- Same words and vocabulary — 43.6% 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 | 24.241 | 17.129 |
| 2 | 7.744 | 13.158 |
Least predictable held-out rows
| Row | Words | Unknown | Bits per word |
|---|---|---|---|
| 58 | 11 | 4 | 4.788 |
| 54 | 11 | 5 | 4.409 |
| 60 | 8 | 3 | 4.301 |
| 11 | 12 | 3 | 4.066 |
| 12 | 13 | 6 | 3.955 |
| 26 | 12 | 6 | 3.923 |
| 59 | 11 | 4 | 3.745 |
| 33 | 11 | 6 | 3.725 |
| 23 | 11 | 5 | 3.692 |
| 6 | 13 | 6 | 3.620 |
- 1 rows have no text (or no words) and are left out.
- 44% 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 b453844b944cad14
# 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 = None
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.25, 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 = 2
SMOOTHING = "kneser_ney"
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 = 300
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/kn_bigram_random_holdout/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"}],
})
The interval, 10.9 to 15.5, comes from resampling whole held-out rows.
Error rates for transcripts
ReadFor speech transcripts and other outputs that should match a reference word for word, overlap scores like BLEU are the wrong tool. The word error rateWord error rateSubstitutions + deletions + insertions needed to turn the output into its closest reference, over reference words, in %. counts the edits needed to turn the output into the reference. The edits are substitutions, deletions and insertionsSubstitutions, deletions and insertionsWords the output got wrong, left out, or added, in the alignment with the fewest edits., divided by the number of reference words. The character error rateCharacter error rateThe same edit count per reference character (spaces included), in %; useful for languages written without spaces. does the same per character. Turn on Word and character error rates in the generated-text metrics:
system_a: BLEU 68.8, chrF 82.9, ROUGE-L F1 85.6 on 30 rows. WER 23.5%, CER 15.4%.
- BLEU
- 68.780
- chrF
- 82.896
- ROUGE-1 F1
- 90.323
- ROUGE-2 F1
- 74.155
- ROUGE-L F1
- 85.566
- Brevity penalty
- 0.9770
- WER (%)
- 23.478
- CER (%)
- 15.367
Plots
Row-level BLEU uses the effective order and exponential smoothing; corpus BLEU is not their mean.
View data
| Metric | Score (0–100) | System |
|---|---|---|
| BLEU | 100 | system_a |
| BLEU | 71.894 | system_a |
| BLEU | 59.695 | system_a |
| BLEU | 52.474 | system_a |
| BLEU | 70.711 | system_a |
| BLEU | 68.037 | system_a |
| BLEU | 53.077 | system_a |
| BLEU | 61.020 | system_a |
| BLEU | 73.111 | system_a |
| BLEU | 100 | system_a |
| BLEU | 69.144 | system_a |
| BLEU | 33.913 | system_a |
| BLEU | 100 | system_a |
| BLEU | 15.881 | system_a |
| BLEU | 35.495 | system_a |
| BLEU | 51.311 | system_a |
| BLEU | 58.143 | system_a |
| BLEU | 65.804 | system_a |
| BLEU | 100 | system_a |
| BLEU | 34.192 | system_a |
| BLEU | 48.110 | system_a |
| BLEU | 100 | system_a |
| BLEU | 100 | system_a |
| BLEU | 84.090 | system_a |
| BLEU | 100 | system_a |
| BLEU | 35.084 | system_a |
| BLEU | 100 | system_a |
| BLEU | 61.020 | system_a |
| BLEU | 52.474 | system_a |
| BLEU | 79.527 | system_a |
| chrF | 100 | system_a |
| chrF | 85.516 | system_a |
| chrF | 80.294 | system_a |
| chrF | 74.648 | system_a |
| chrF | 80.006 | system_a |
| chrF | 91.414 | system_a |
| chrF | 70.693 | system_a |
| chrF | 89.889 | system_a |
| chrF | 83.741 | system_a |
| chrF | 100 | system_a |
| chrF | 78.501 | system_a |
| chrF | 67.629 | system_a |
| chrF | 100 | system_a |
| chrF | 54.242 | system_a |
| chrF | 67.280 | system_a |
| chrF | 75.106 | system_a |
| chrF | 75.818 | system_a |
| chrF | 77.961 | system_a |
| chrF | 100 | system_a |
| chrF | 70.190 | system_a |
| chrF | 88.069 | system_a |
| chrF | 100 | system_a |
| chrF | 100 | system_a |
| chrF | 86.455 | system_a |
| chrF | 100 | system_a |
| chrF | 60.563 | system_a |
| chrF | 100 | system_a |
| chrF | 72.993 | system_a |
| chrF | 69.859 | system_a |
| chrF | 85.124 | system_a |
First 60 of 300 rows.
View data
| Score | Upper | Lower | Metric | System |
|---|---|---|---|---|
| 68.780 | 76.930 | 61.650 | BLEU | system_a |
| 82.896 | 87.800 | 78.599 | chrF | system_a |
| 90.323 | 93.341 | 87.562 | ROUGE-1 | system_a |
| 74.155 | 81.246 | 68.267 | ROUGE-2 | system_a |
| 85.566 | 89.656 | 81.928 | ROUGE-L | system_a |
| 3.528 | 4.648 | 1.892 | BLEU | system_b |
| 30.737 | 34.696 | 27.366 | chrF | system_b |
| 35.673 | 42.156 | 29.616 | ROUGE-1 | system_b |
| 11.440 | 15.618 | 7.736 | ROUGE-2 | system_b |
| 32.967 | 39.014 | 27.797 | ROUGE-L | system_b |
Edits needed to turn each output into its closest reference, per reference word (WER) or character (CER); lower is better and it can exceed 100%.
View data
| Metric | Error rate (%) | System |
|---|---|---|
| WER | 0 | system_a |
| CER | 0 | system_a |
| WER | 12.500 | system_a |
| CER | 7.692 | system_a |
| WER | 28.571 | system_a |
| CER | 14.286 | system_a |
| WER | 25 | system_a |
| CER | 13.636 | system_a |
| WER | 11.111 | system_a |
| CER | 7.143 | system_a |
| WER | 14.286 | system_a |
| CER | 8.889 | system_a |
| WER | 25 | system_a |
| CER | 21.739 | system_a |
| WER | 12.500 | system_a |
| CER | 7.843 | system_a |
| WER | 14.286 | system_a |
| CER | 4.762 | system_a |
| WER | 0 | system_a |
| CER | 0 | system_a |
| WER | 14.286 | system_a |
| CER | 14.894 | system_a |
| WER | 42.857 | system_a |
| CER | 25 | system_a |
| WER | 0 | system_a |
| CER | 0 | system_a |
| WER | 55.556 | system_a |
| CER | 45.652 | system_a |
| WER | 33.333 | system_a |
| CER | 18.367 | system_a |
| WER | 37.500 | system_a |
| CER | 34.091 | system_a |
| WER | 14.286 | system_a |
| CER | 13.333 | system_a |
| WER | 11.111 | system_a |
| CER | 11.111 | system_a |
| WER | 0 | system_a |
| CER | 0 | system_a |
| WER | 62.500 | system_a |
| CER | 41.667 | system_a |
| WER | 71.429 | system_a |
| CER | 59.524 | system_a |
| WER | 0 | system_a |
| CER | 0 | system_a |
| WER | 0 | system_a |
| CER | 0 | system_a |
| WER | 25 | system_a |
| CER | 12.500 | system_a |
| WER | 0 | system_a |
| CER | 0 | system_a |
| WER | 62.500 | system_a |
| CER | 34.884 | system_a |
| WER | 33.333 | system_a |
| CER | 2.703 | system_a |
| WER | 37.500 | system_a |
| CER | 26.316 | system_a |
| WER | 25 | system_a |
| CER | 19.512 | system_a |
| WER | 28.571 | system_a |
| CER | 13.043 | system_a |
First 60 of 120 rows.
Assumptions
- Good references — 2 reference column(s); rows have 1–2 usable references. More references make overlap scores fairer to correct rewordings.
- Same rows for every system — Every system is scored on the same rows, so the comparison is paired.
- Wording, not meaning — Overlap metrics miss meaning, facts and safety; review a sample by hand or with LLM-as-judge.
Corpus scores by system
| System | BLEU | chrF | ROUGE-1 | ROUGE-2 | ROUGE-L | p (BLEU vs first) |
|---|---|---|---|---|---|---|
| system_a | 68.780 | 82.896 | 90.323 | 74.155 | 85.566 | — |
| system_b | 3.528 | 30.737 | 35.673 | 11.440 | 32.967 | .003 |
Word and character error rates by system
| System | WER (%) | CER (%) | Substitutions | Deletions | Insertions | Reference words | p (WER vs first) |
|---|---|---|---|---|---|---|---|
| system_a | 23.478 | 15.367 | 27 | 15 | 12 | 230 | — |
| system_b | 81.250 | 60.812 | 80 | 100 | 2 | 224 | .003 |
- 2 rows have a missing output or no reference and are left out.
The exact R script · R R version 4.5.1 (2025-06-13)
# Generated-text metrics (BLEU, chrF, ROUGE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.text 1.1.1 · spec ab60482aa541a57b
# Dataset: ml_gentext (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Rows: every candidate present and at least one non-empty reference
CANDIDATES <- c("system_a", "system_b")
REFERENCES <- c("ref1", "ref2")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_gentext.parquet", col_select = unique(c(CANDIDATES, REFERENCES))))
warnings <- list()
has_cand <- Reduce(`&`, lapply(CANDIDATES, function(c) !is.na(df[[c]])))
ref_lists <- lapply(seq_len(nrow(df)), function(i) {
v <- vapply(REFERENCES, function(c) as.character(df[[c]][i]), "")
unname(v[!is.na(v) & nzchar(v)])
})
has_ref <- lengths(ref_lists) > 0
rows <- which(has_cand & has_ref)
n_dropped <- nrow(df) - length(rows)
if (n_dropped) warnings <- c(warnings, sprintf("%d rows have a missing output or no reference and are left out.", n_dropped))
if (!length(rows)) cs_error("CS_E_NO_ROWS") # no row has every output and at least one reference
refs <- ref_lists[rows]
# %% Segment statistics per system (sacreBLEU-compatible BLEU and chrF, rouge-score ROUGE)
TOKENIZE <- "13a"
LOWER <- FALSE
WORD_ORDER <- as.integer("0")
segs <- lapply(CANDIDATES, function(c) cs_tm_segments(as.character(df[[c]][rows]), refs, tokenize = TOKENIZE, lowercase = LOWER, word_order = WORD_ORDER))
scores <- lapply(segs, cs_tm_corpus)
METRICS <- c("bleu", "chrf", "rouge1", "rouge2", "rougeL")
ROUGE <- c("rouge1", "rouge2", "rougeL")
# %% Paired bootstrap over rows (shared Wichmann-Hill stream)
B <- 300
CONF <- 0.95
reps <- if (B > 0) cs_tm_bootstrap(segs, B, 42) else NULL
# %% Word and character error rates (only with the option on; closest reference per row, same resamples)
ERROR_RATES <- TRUE
esegs <- if (ERROR_RATES) lapply(CANDIDATES, function(c) cs_tm_error_segments(as.character(df[[c]][rows]), refs, lowercase = LOWER)) else NULL
ereps <- if (ERROR_RATES && B > 0) cs_tm_error_bootstrap(esegs, B, 42) else NULL
# %% Artifacts: one row per input row and system
out <- cs_ml_out_dir("target/academy-parity/run-8142/evaluate.text/wer_cer_two_systems/out-r")
per_row <- do.call(rbind, lapply(seq_along(CANDIDATES), function(s) {
seg <- segs[[s]]
data.frame(row = as.integer(rows - 1L), system = CANDIDATES[s], bleu = seg$sent_bleu, chrf = seg$sent_chrf,
rouge1 = seg$rouge[, 3], rouge2 = seg$rouge[, 6], rougeL = seg$rouge[, 9])
}))
if (ERROR_RATES) {
per_row$wer <- unlist(lapply(esegs, function(e) ifelse(e[, 2] > 0, 100 * e[, 1] / e[, 2], NA_real_)))
per_row$cer <- unlist(lapply(esegs, function(e) ifelse(e[, 7] > 0, 100 * e[, 6] / e[, 7], NA_real_)))
}
nanoparquet::write_parquet(per_row, file.path(out, "scores.parquet"))
# %% Result
LABELS <- c(bleu = "BLEU", chrf = if (WORD_ORDER) "chrF++" else "chrF", rouge1 = "ROUGE-1", rouge2 = "ROUGE-2", rougeL = "ROUGE-L")
first <- segs[[1]]
b0 <- cs_tm_bleu_score(colSums(first$bleu_stats))
values <- list(n = length(rows), n_dropped = n_dropped, n_systems = length(CANDIDATES), n_refs = length(REFERENCES),
bleu = b0$score, bleu_bp = b0$bp, bleu_ratio = b0$ratio,
bleu_p1 = b0$p1, bleu_p2 = b0$p2, bleu_p3 = b0$p3, bleu_p4 = b0$p4,
hyp_len = b0$hyp_len, ref_len = b0$ref_len, chrf = scores[[1]]$chrf,
sent_bleu_mean = mean(first$sent_bleu), sent_chrf_mean = mean(first$sent_chrf),
tokenize = TOKENIZE, chrf_label = unname(LABELS["chrf"]))
for (j in seq_along(ROUGE)) {
k <- ROUGE[j]
values[[k]] <- scores[[1]][[k]]
values[[paste0(k, "_p")]] <- 100 * mean(first$rouge[, 3 * j - 2])
values[[paste0(k, "_r")]] <- 100 * mean(first$rouge[, 3 * j - 1])
}
ci_rows <- list()
for (s in seq_along(CANDIDATES)) {
c <- CANDIDATES[s]
values[[sprintf("system[%d]", s)]] <- c
for (m in seq_along(METRICS)) {
k <- METRICS[m]
values[[sprintf("%s[%s]", k, c)]] <- scores[[s]][[k]]
lo <- NULL; hi <- NULL
if (!is.null(reps)) {
ci <- cs_tm_percentile_ci(reps[s, , m], CONF)
lo <- ci[1]; hi <- ci[2]
if (s == 1) { values[[paste0(k, "_ci_low")]] <- lo; values[[paste0(k, "_ci_high")]] <- hi }
if (s > 1) {
d <- scores[[s]][[k]] - scores[[1]][[k]]
values[[sprintf("diff_%s[%s]", k, c)]] <- d
values[[sprintf("p_%s[%s]", k, c)]] <- cs_tm_paired_p(d, reps[s, , m] - reps[1, , m])
}
} else if (s > 1) {
values[[sprintf("diff_%s[%s]", k, c)]] <- scores[[s]][[k]] - scores[[1]][[k]]
}
ci_rows[[length(ci_rows) + 1]] <- list(system = c, metric = unname(LABELS[k]), estimate = scores[[s]][[k]], low = lo, high = hi)
}
}
if (is.null(reps)) for (k in METRICS) { values[paste0(k, "_ci_low")] <- list(NULL); values[paste0(k, "_ci_high")] <- list(NULL) }
assumptions <- list(
list(key = "references", label = "Good references", status = "info",
detail = sprintf("%d reference column(s); rows have %d–%d usable references. More references make overlap scores fairer to correct rewordings.",
length(REFERENCES), min(lengths(refs)), max(lengths(refs)))),
list(key = "same_rows", label = "Same rows for every system", status = if (length(CANDIDATES) > 1) "pass" else "info",
detail = if (length(CANDIDATES) > 1) "Every system is scored on the same rows, so the comparison is paired." else "One system: nothing to pair."),
list(key = "wording_not_meaning", label = "Wording, not meaning", status = "info",
detail = "Overlap metrics miss meaning, facts and safety; review a sample by hand or with LLM-as-judge.")
)
if (is.finite(b0$ratio) && b0$ratio < 0.8) {
warnings <- c(warnings, sprintf("%s is much shorter than the references (length ratio %.2f); BLEU's brevity penalty is %.3f.", CANDIDATES[1], b0$ratio, b0$bp))
}
table_rows <- lapply(seq_along(CANDIDATES), function(s) {
row <- list(system = CANDIDATES[s])
for (k in METRICS) row[[k]] <- scores[[s]][[k]]
if (s > 1 && !is.null(reps)) row$p_bleu <- values[[sprintf("p_bleu[%s]", CANDIDATES[s])]]
row
})
cols <- c(list(list(key = "system", label = "System")), lapply(METRICS, function(k) list(key = k, label = unname(LABELS[k]), type = "number")))
if (length(CANDIDATES) > 1 && !is.null(reps)) cols[[length(cols) + 1]] <- list(key = "p_bleu", label = "p (BLEU vs first)", type = "pvalue")
metric_col <- character(0); score_col <- numeric(0); system_col <- character(0)
for (s in seq_along(CANDIDATES)) {
seg <- segs[[s]]
parts <- list(bleu = seg$sent_bleu, chrf = seg$sent_chrf, rouge1 = 100 * seg$rouge[, 3], rouge2 = 100 * seg$rouge[, 6], rougeL = 100 * seg$rouge[, 9])
for (k in METRICS) {
metric_col <- c(metric_col, rep(unname(LABELS[k]), length(parts[[k]])))
score_col <- c(score_col, parts[[k]])
system_col <- c(system_col, rep(CANDIDATES[s], length(parts[[k]])))
}
}
metric_levels <- unname(LABELS[METRICS])
seg_roles <- list(metric = cs_col("Metric", metric_col, "categorical", metric_levels), score = cs_col("Score (0–100)", score_col, "numeric"))
if (length(CANDIDATES) > 1) seg_roles$system <- cs_col("System", system_col, "categorical", CANDIDATES)
charts <- list(cs_chart("segments", "text-metric-scores", "Scores per row", seg_roles,
note = "Row-level BLEU uses the effective order and exponential smoothing; corpus BLEU is not their mean."))
if (!is.null(reps)) {
ci_roles <- list(
metric = cs_col("Metric", vapply(ci_rows, `[[`, "", "metric"), "categorical", metric_levels),
estimate = cs_col("Score", vapply(ci_rows, `[[`, 0, "estimate"), "numeric"),
low = cs_col("Lower", vapply(ci_rows, `[[`, 0, "low"), "numeric"),
high = cs_col("Upper", vapply(ci_rows, `[[`, 0, "high"), "numeric"))
if (length(CANDIDATES) > 1) ci_roles$system <- cs_col("System", vapply(ci_rows, `[[`, "", "system"), "categorical", CANDIDATES)
charts[[2]] <- cs_chart("corpus", "text-metric-ci", sprintf("Corpus scores with %s bootstrap intervals", paste0(round(CONF * 100), "%")), ci_roles)
}
extra_stats <- list(); extra_tables <- list(); summary_extra <- ""
if (ERROR_RATES) {
e0 <- colSums(esegs[[1]])
values$wer <- cs_tm_error_rate(e0[1], e0[2]); values$cer <- cs_tm_error_rate(e0[6], e0[7])
if (is.null(values$wer)) values["wer"] <- list(NULL)
if (is.null(values$cer)) values["cer"] <- list(NULL)
values$wer_sub <- as.integer(e0[3]); values$wer_del <- as.integer(e0[4]); values$wer_ins <- as.integer(e0[5])
values$wer_ref_words <- as.integer(e0[2]); values$cer_ref_chars <- as.integer(e0[7])
er_rows <- list()
rates <- list()
for (s in seq_along(CANDIDATES)) {
c <- CANDIDATES[s]
t <- colSums(esegs[[s]])
row <- list(system = c, wer = cs_tm_error_rate(t[1], t[2]), cer = cs_tm_error_rate(t[6], t[7]), sub = as.integer(t[3]),
del = as.integer(t[4]), ins = as.integer(t[5]), words = as.integer(t[2]))
rates[[s]] <- list(wer = row$wer, cer = row$cer)
for (m in 1:2) {
k <- c("wer", "cer")[m]
est <- rates[[s]][[k]]; base <- rates[[1]][[k]]
values[sprintf("%s[%s]", k, c)] <- list(est)
d <- if (s > 1 && !is.null(est) && !is.null(base)) est - base else NULL
if (s > 1) values[sprintf("diff_%s[%s]", k, c)] <- list(d)
if (!is.null(ereps)) {
col <- ereps[s, , m]
if (s == 1) {
ci <- if (!anyNA(col)) cs_tm_percentile_ci(col, CONF) else NULL
values[paste0(k, "_ci_low")] <- list(if (is.null(ci)) NULL else ci[1])
values[paste0(k, "_ci_high")] <- list(if (is.null(ci)) NULL else ci[2])
} else {
dif <- col - ereps[1, , m]
values[sprintf("p_%s[%s]", k, c)] <- list(if (!is.null(d) && !anyNA(dif)) cs_tm_paired_p(d, dif) else NULL)
}
}
}
if (s > 1 && !is.null(ereps)) row$p_wer <- values[[sprintf("p_wer[%s]", c)]]
er_rows[[s]] <- row
}
if (is.null(ereps)) for (k in c("wer", "cer")) { values[paste0(k, "_ci_low")] <- list(NULL); values[paste0(k, "_ci_high")] <- list(NULL) }
er_cols <- list(list(key = "system", label = "System"), list(key = "wer", label = "WER (%)", type = "number"), list(key = "cer", label = "CER (%)", type = "number"),
list(key = "sub", label = "Substitutions", type = "number"), list(key = "del", label = "Deletions", type = "number"),
list(key = "ins", label = "Insertions", type = "number"), list(key = "words", label = "Reference words", type = "number"))
if (length(CANDIDATES) > 1 && !is.null(ereps)) er_cols[[length(er_cols) + 1]] <- list(key = "p_wer", label = "p (WER vs first)", type = "pvalue")
extra_tables <- list(list(key = "error_rates", title = "Word and character error rates by system", columns = er_cols, rows = er_rows))
extra_stats <- list(list(key = "wer", label = "WER (%)", value = values$wer), list(key = "cer", label = "CER (%)", value = values$cer))
if (!is.null(values$wer) && !is.null(values$cer)) summary_extra <- sprintf(" WER %.1f%%, CER %.1f%%.", values$wer, values$cer)
em_col <- character(0); es_col <- numeric(0); esys_col <- character(0)
for (s in seq_along(CANDIDATES)) {
e <- esegs[[s]]
for (i in seq_len(nrow(e))) {
if (e[i, 2] > 0) { em_col <- c(em_col, "WER"); es_col <- c(es_col, 100 * e[i, 1] / e[i, 2]); esys_col <- c(esys_col, CANDIDATES[s]) }
if (e[i, 7] > 0) { em_col <- c(em_col, "CER"); es_col <- c(es_col, 100 * e[i, 6] / e[i, 7]); esys_col <- c(esys_col, CANDIDATES[s]) }
}
}
er_roles <- list(metric = cs_col("Metric", em_col, "categorical", c("WER", "CER")), score = cs_col("Error rate (%)", es_col, "numeric"))
if (length(CANDIDATES) > 1) er_roles$system <- cs_col("System", esys_col, "categorical", CANDIDATES)
charts[[length(charts) + 1]] <- cs_chart("error_rates", "text-metric-scores", "Error rates per row", er_roles,
note = "Edits needed to turn each output into its closest reference, per reference word (WER) or character (CER); lower is better and it can exceed 100%.")
}
cs_publish(list(
title = "Generated-text metrics (BLEU, chrF, ROUGE)",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = length(rows),
summary = paste0(sprintf("%s: BLEU %.1f, %s %.1f, ROUGE-L F1 %.1f on %d rows.", CANDIDATES[1], values$bleu, LABELS[["chrf"]], values$chrf, values$rougeL, length(rows)), summary_extra),
statistics = list(
list(key = "bleu", label = "BLEU", value = values$bleu),
list(key = "chrf", label = unname(LABELS["chrf"]), value = values$chrf),
list(key = "rouge1", label = "ROUGE-1 F1", value = values$rouge1),
list(key = "rouge2", label = "ROUGE-2 F1", value = values$rouge2),
list(key = "rougeL", label = "ROUGE-L F1", value = values$rougeL),
list(key = "bleu_bp", label = "Brevity penalty", value = values$bleu_bp)
) |> c(extra_stats),
tables = c(list(list(key = "systems", title = "Corpus scores by system", columns = cols, rows = table_rows)), extra_tables),
assumptions = assumptions,
charts = charts,
values = values,
warnings = warnings,
artifacts = list(list(key = "scores", path = file.path(out, "scores.parquet"), format = "parquet"))
))
system_a: BLEU 68.8, chrF 82.9, ROUGE-L F1 85.6 on 30 rows. WER 23.5%, CER 15.4%.
- BLEU
- 68.780
- chrF
- 82.896
- ROUGE-1 F1
- 90.323
- ROUGE-2 F1
- 74.155
- ROUGE-L F1
- 85.566
- Brevity penalty
- 0.9770
- WER (%)
- 23.478
- CER (%)
- 15.367
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Good references — 2 reference column(s); rows have 1–2 usable references. More references make overlap scores fairer to correct rewordings.
- Same rows for every system — Every system is scored on the same rows, so the comparison is paired.
- Wording, not meaning — Overlap metrics miss meaning, facts and safety; review a sample by hand or with LLM-as-judge.
Corpus scores by system
| System | BLEU | chrF | ROUGE-1 | ROUGE-2 | ROUGE-L | p (BLEU vs first) |
|---|---|---|---|---|---|---|
| system_a | 68.780 | 82.896 | 90.323 | 74.155 | 85.566 | — |
| system_b | 3.528 | 30.737 | 35.673 | 11.440 | 32.967 | .003 |
Word and character error rates by system
| System | WER (%) | CER (%) | Substitutions | Deletions | Insertions | Reference words | p (WER vs first) |
|---|---|---|---|---|---|---|---|
| system_a | 23.478 | 15.367 | 27 | 15 | 12 | 230 | — |
| system_b | 81.250 | 60.812 | 80 | 100 | 2 | 224 | .003 |
- 2 rows have a missing output or no reference and are left out.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Generated-text metrics (BLEU, chrF, ROUGE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.text 1.1.1 · spec ab60482aa541a57b
# Dataset: ml_gentext (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.text import error_rates as er
from codesplash.text import metrics as tm
# %% Rows: every candidate present and at least one non-empty reference
CANDIDATES = ["system_a", "system_b"]
REFERENCES = ["ref1", "ref2"]
df = pd.read_parquet("tests/parity/fixtures/ml_gentext.parquet", columns=list(dict.fromkeys(CANDIDATES + REFERENCES)))
warnings = []
has_cand = df[CANDIDATES].notna().all(axis=1).to_numpy()
ref_lists = [[str(v) for v in row if not pd.isna(v) and str(v) != ""] for row in df[REFERENCES].itertuples(index=False)] # None, NaN, pd.NA: none
has_ref = np.array([len(r) > 0 for r in ref_lists])
rows = np.flatnonzero(has_cand & has_ref)
n_dropped = len(df) - len(rows)
if n_dropped:
warnings.append(f"{n_dropped} rows have a missing output or no reference and are left out.")
if not len(rows):
cs.cs_error("CS_E_NO_ROWS") # no row has every output and at least one reference
refs = [ref_lists[i] for i in rows]
# %% Segment statistics per system (sacreBLEU-compatible BLEU and chrF, rouge-score ROUGE)
TOKENIZE = "13a"
LOWER = False
WORD_ORDER = int("0")
segs = [tm.segments([str(v) for v in df[c].iloc[rows]], refs, tokenize=TOKENIZE, lowercase=LOWER, word_order=WORD_ORDER) for c in CANDIDATES]
scores = [tm.corpus_scores(s) for s in segs]
# %% Paired bootstrap over rows (shared Wichmann–Hill stream)
B = 300
CONF = 0.95
reps = tm.bootstrap(segs, B, 42) if B > 0 else None
# %% Word and character error rates (only with the option on; closest reference per row, same resamples)
ERROR_RATES = True
esegs = [er.segments([str(v) for v in df[c].iloc[rows]], refs, lowercase=LOWER) for c in CANDIDATES] if ERROR_RATES else None
ereps = er.bootstrap(esegs, B, 42) if ERROR_RATES and B > 0 else None
# %% Artifacts: one row per input row and system
out = csml.out_dir("target/academy-parity/run-8142/evaluate.text/wer_cer_two_systems/out-python")
per_row = []
for s, c in enumerate(CANDIDATES):
seg = segs[s]
for i, r in enumerate(rows):
per_row.append({"row": int(r), "system": c, "bleu": float(seg["sent_bleu"][i]), "chrf": float(seg["sent_chrf"][i]),
"rouge1": float(seg["rouge"][i, 2]), "rouge2": float(seg["rouge"][i, 5]), "rougeL": float(seg["rouge"][i, 8])})
if ERROR_RATES:
e = esegs[s][i]
per_row[-1].update({"wer": er.rate(e[0], e[1]), "cer": er.rate(e[5], e[6])})
pd.DataFrame(per_row).to_parquet(os.path.join(out, "scores.parquet"), index=False)
# %% Result
LABELS = {"bleu": "BLEU", "chrf": "chrF++" if WORD_ORDER else "chrF", "rouge1": "ROUGE-1", "rouge2": "ROUGE-2", "rougeL": "ROUGE-L"}
first = segs[0]
b0 = tm.bleu_score(first["bleu_stats"].sum(axis=0))
values = {
"n": len(rows), "n_dropped": n_dropped, "n_systems": len(CANDIDATES), "n_refs": len(REFERENCES),
"bleu": b0["score"], "bleu_bp": b0["bp"], "bleu_ratio": b0["ratio"],
"bleu_p1": b0["p1"], "bleu_p2": b0["p2"], "bleu_p3": b0["p3"], "bleu_p4": b0["p4"],
"hyp_len": b0["hyp_len"], "ref_len": b0["ref_len"], "chrf": scores[0]["chrf"],
"sent_bleu_mean": float(first["sent_bleu"].mean()), "sent_chrf_mean": float(first["sent_chrf"].mean()),
"tokenize": TOKENIZE, "chrf_label": LABELS["chrf"],
}
for j, k in enumerate(tm.ROUGE):
values[k] = scores[0][k]
values[f"{k}_p"] = 100.0 * float(first["rouge"][:, 3 * j].mean())
values[f"{k}_r"] = 100.0 * float(first["rouge"][:, 3 * j + 1].mean())
ci_rows = []
for s, c in enumerate(CANDIDATES):
values[f"system[{s + 1}]"] = c
for m, k in enumerate(tm.METRICS):
values[f"{k}[{c}]"] = scores[s][k]
lo = hi = None
if reps is not None:
lo, hi = tm.percentile_ci(reps[s, :, m], CONF)
if s == 0:
values[f"{k}_ci_low"], values[f"{k}_ci_high"] = lo, hi
if s > 0:
d = scores[s][k] - scores[0][k]
values[f"diff_{k}[{c}]"] = d
values[f"p_{k}[{c}]"] = tm.paired_p(d, reps[s, :, m] - reps[0, :, m])
elif s > 0:
values[f"diff_{k}[{c}]"] = scores[s][k] - scores[0][k]
ci_rows.append({"system": c, "metric": LABELS[k], "estimate": scores[s][k], "low": lo, "high": hi})
if reps is None:
for k in tm.METRICS:
values[f"{k}_ci_low"] = values[f"{k}_ci_high"] = None
assumptions = [
{"key": "references", "label": "Good references", "status": "info",
"detail": f"{len(REFERENCES)} reference column(s); rows have {min(len(r) for r in refs)}–{max(len(r) for r in refs)} usable references. More references make overlap scores fairer to correct rewordings."},
{"key": "same_rows", "label": "Same rows for every system", "status": "pass" if len(CANDIDATES) > 1 else "info",
"detail": "Every system is scored on the same rows, so the comparison is paired." if len(CANDIDATES) > 1 else "One system: nothing to pair."},
{"key": "wording_not_meaning", "label": "Wording, not meaning", "status": "info",
"detail": "Overlap metrics miss meaning, facts and safety; review a sample by hand or with LLM-as-judge."},
]
if b0["ratio"] == b0["ratio"] and b0["ratio"] < 0.8:
warnings.append(f"{CANDIDATES[0]} is much shorter than the references (length ratio {b0['ratio']:.2f}); BLEU's brevity penalty is {b0['bp']:.3f}.")
table_rows = []
for s, c in enumerate(CANDIDATES):
row = {"system": c}
for k in tm.METRICS:
row[k] = scores[s][k]
if s > 0 and reps is not None:
row["p_bleu"] = values[f"p_bleu[{c}]"]
table_rows.append(row)
cols = [{"key": "system", "label": "System"}] + [{"key": k, "label": LABELS[k], "type": "number"} for k in tm.METRICS]
if len(CANDIDATES) > 1 and reps is not None:
cols.append({"key": "p_bleu", "label": "p (BLEU vs first)", "type": "pvalue"})
metric_col, score_col, system_col = [], [], []
for s, c in enumerate(CANDIDATES):
seg = segs[s]
for k, v in (("bleu", seg["sent_bleu"]), ("chrf", seg["sent_chrf"]), ("rouge1", 100 * seg["rouge"][:, 2]), ("rouge2", 100 * seg["rouge"][:, 5]), ("rougeL", 100 * seg["rouge"][:, 8])):
metric_col += [LABELS[k]] * len(v)
score_col += [float(x) for x in v]
system_col += [c] * len(v)
metric_levels = [LABELS[k] for k in tm.METRICS]
charts = [cs.chart("segments", "text-metric-scores", "Scores per row", {
"metric": cs.col("Metric", metric_col, "categorical", metric_levels),
"score": cs.col("Score (0–100)", score_col, "numeric"),
**({"system": cs.col("System", system_col, "categorical", list(CANDIDATES))} if len(CANDIDATES) > 1 else {}),
}, note="Row-level BLEU uses the effective order and exponential smoothing; corpus BLEU is not their mean.")]
if reps is not None:
charts.append(cs.chart("corpus", "text-metric-ci", f"Corpus scores with {CONF:.0%} bootstrap intervals", {
"metric": cs.col("Metric", [r["metric"] for r in ci_rows], "categorical", metric_levels),
"estimate": cs.col("Score", [r["estimate"] for r in ci_rows], "numeric"),
"low": cs.col("Lower", [r["low"] for r in ci_rows], "numeric"),
"high": cs.col("Upper", [r["high"] for r in ci_rows], "numeric"),
**({"system": cs.col("System", [r["system"] for r in ci_rows], "categorical", list(CANDIDATES))} if len(CANDIDATES) > 1 else {}),
}))
extra_stats, extra_tables, summary_extra = [], [], ""
if ERROR_RATES:
e0 = esegs[0].sum(axis=0)
values.update({"wer": er.rate(e0[0], e0[1]), "cer": er.rate(e0[5], e0[6]), "wer_sub": int(e0[2]), "wer_del": int(e0[3]),
"wer_ins": int(e0[4]), "wer_ref_words": int(e0[1]), "cer_ref_chars": int(e0[6])})
er_rows = []
for s, c in enumerate(CANDIDATES):
t = esegs[s].sum(axis=0)
row = {"system": c, "wer": er.rate(t[0], t[1]), "cer": er.rate(t[5], t[6]), "sub": int(t[2]), "del": int(t[3]), "ins": int(t[4]), "words": int(t[1])}
for m, k in enumerate(("wer", "cer")):
values[f"{k}[{c}]"] = row[k]
base = values[f"{k}[{CANDIDATES[0]}]"]
d = row[k] - base if (s > 0 and row[k] is not None and base is not None) else None
if s > 0:
values[f"diff_{k}[{c}]"] = d
if ereps is not None:
col = ereps[s, :, m]
if s == 0:
values[f"{k}_ci_low"], values[f"{k}_ci_high"] = tm.percentile_ci(col, CONF) if not np.isnan(col).any() else (None, None)
else:
dif = col - ereps[0, :, m]
values[f"p_{k}[{c}]"] = tm.paired_p(d, dif) if d is not None and not np.isnan(dif).any() else None
if s > 0 and ereps is not None:
row["p_wer"] = values[f"p_wer[{c}]"]
er_rows.append(row)
if ereps is None:
for k in ("wer", "cer"):
values[f"{k}_ci_low"] = values[f"{k}_ci_high"] = None
er_cols = [{"key": "system", "label": "System"}, {"key": "wer", "label": "WER (%)", "type": "number"}, {"key": "cer", "label": "CER (%)", "type": "number"},
{"key": "sub", "label": "Substitutions", "type": "number"}, {"key": "del", "label": "Deletions", "type": "number"},
{"key": "ins", "label": "Insertions", "type": "number"}, {"key": "words", "label": "Reference words", "type": "number"}]
if len(CANDIDATES) > 1 and ereps is not None:
er_cols.append({"key": "p_wer", "label": "p (WER vs first)", "type": "pvalue"})
extra_tables.append({"key": "error_rates", "title": "Word and character error rates by system", "columns": er_cols, "rows": er_rows})
extra_stats = [{"key": "wer", "label": "WER (%)", "value": values["wer"]}, {"key": "cer", "label": "CER (%)", "value": values["cer"]}]
if values["wer"] is not None and values["cer"] is not None:
summary_extra = f" WER {values['wer']:.1f}%, CER {values['cer']:.1f}%."
em_col, es_col, esys_col = [], [], []
for s, c in enumerate(CANDIDATES):
for i in range(esegs[s].shape[0]):
e = esegs[s][i]
for lab, num, den in (("WER", e[0], e[1]), ("CER", e[5], e[6])):
if den > 0:
em_col.append(lab)
es_col.append(100.0 * float(num) / float(den))
esys_col.append(c)
charts.append(cs.chart("error_rates", "text-metric-scores", "Error rates per row", {
"metric": cs.col("Metric", em_col, "categorical", ["WER", "CER"]),
"score": cs.col("Error rate (%)", es_col, "numeric"),
**({"system": cs.col("System", esys_col, "categorical", list(CANDIDATES))} if len(CANDIDATES) > 1 else {}),
}, note="Edits needed to turn each output into its closest reference, per reference word (WER) or character (CER); lower is better and it can exceed 100%."))
cs.publish({
"title": "Generated-text metrics (BLEU, chrF, ROUGE)",
"engine": cs.engine_info("numpy", "pandas"),
"n": len(rows),
"summary": f"{CANDIDATES[0]}: BLEU {values['bleu']:.1f}, {LABELS['chrf']} {values['chrf']:.1f}, ROUGE-L F1 {values['rougeL']:.1f} on {len(rows)} rows." + summary_extra,
"statistics": [
{"key": "bleu", "label": "BLEU", "value": values["bleu"]},
{"key": "chrf", "label": LABELS["chrf"], "value": values["chrf"]},
{"key": "rouge1", "label": "ROUGE-1 F1", "value": values["rouge1"]},
{"key": "rouge2", "label": "ROUGE-2 F1", "value": values["rouge2"]},
{"key": "rougeL", "label": "ROUGE-L F1", "value": values["rougeL"]},
{"key": "bleu_bp", "label": "Brevity penalty", "value": values["bleu_bp"]},
] + extra_stats,
"tables": [{"key": "systems", "title": "Corpus scores by system", "columns": cols, "rows": table_rows}] + extra_tables,
"assumptions": assumptions,
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": [{"key": "scores", "path": os.path.join(out, "scores.parquet"), "format": "parquet"}],
})
The first system has WER 23.5% and CER 15.4%. It makes 27 substitutions, 15 deletions and 12 insertions over 230 reference words. With two references, each row uses the one that needs the fewest edits.
View data
| metric | score | system |
|---|---|---|
| BLEU | 63.400 | baseline |
| BLEU | 15.700 | baseline |
| BLEU | 52.800 | baseline |
| BLEU | 71.500 | baseline |
| BLEU | 31.600 | baseline |
| BLEU | 71.800 | baseline |
| BLEU | 66.300 | baseline |
| BLEU | 21.700 | baseline |
| BLEU | 12.300 | baseline |
| BLEU | 46.500 | baseline |
| BLEU | 70 | baseline |
| BLEU | 78 | baseline |
| BLEU | 22.400 | baseline |
| BLEU | 32.800 | baseline |
| BLEU | 77.200 | baseline |
| BLEU | 49 | baseline |
| BLEU | 44.600 | baseline |
| BLEU | 49.200 | baseline |
| BLEU | 55.900 | baseline |
| BLEU | 63.300 | baseline |
| BLEU | 69.800 | baseline |
| BLEU | 46 | baseline |
| BLEU | 63.800 | baseline |
| BLEU | 29.700 | baseline |
| BLEU | 42.600 | baseline |
| BLEU | 36.600 | baseline |
| BLEU | 26.200 | baseline |
| BLEU | 42.400 | baseline |
| BLEU | 35.700 | baseline |
| BLEU | 35.700 | baseline |
| BLEU | 30 | baseline |
| BLEU | 25 | baseline |
| BLEU | 71.700 | baseline |
| BLEU | 54.700 | baseline |
| BLEU | 33.600 | baseline |
| BLEU | 43.800 | baseline |
| BLEU | 33 | baseline |
| BLEU | 13.600 | baseline |
| BLEU | 90.500 | baseline |
| BLEU | 18.600 | baseline |
| chrF | 36.300 | baseline |
| chrF | 65.700 | baseline |
| chrF | 64.200 | baseline |
| chrF | 67.700 | baseline |
| chrF | 66.800 | baseline |
| chrF | 56 | baseline |
| chrF | 75.900 | baseline |
| chrF | 58.800 | baseline |
| chrF | 63.300 | baseline |
| chrF | 71 | baseline |
| chrF | 86.200 | baseline |
| chrF | 70.700 | baseline |
| chrF | 34.500 | baseline |
| chrF | 61.900 | baseline |
| chrF | 79.200 | baseline |
| chrF | 60.900 | baseline |
| chrF | 67.400 | baseline |
| chrF | 96.400 | baseline |
| chrF | 74.500 | baseline |
| chrF | 78.100 | baseline |
First 60 of 400 rows.
Check yourself
A system's WER is 120%. What happened?
Show the answer
Answer: b
WER divides all edits, insertions included, by the reference length, so a long, rambling output can pass 100%.
Concepts in this lesson