Language models, retrieval, prompting, and language adaptation · Count-based and distributed representations · LNG001 · Model
Smoothed n-gram language model
A finite-history probabilistic baseline that predicts words from preceding words. It is useful for small corpora, transparent scoring, domain adaptation, and testing whether a neural model adds value beyond local…
In CodeSplash
A CodeSplash method runs this entry in Python and R. Set it up from the method's page.
- N-gram language model perplexity Not verified yet
Do it in CodeSplash Run it on your own data, in Python or R.
- Availability
- Runs in CodeSplash
- Code example
- Complete calculation
- Who ran it
- CodeSplash's own run
- CodeSplash's run
- The reference's example ran in Python and R here, and they agree.
- The reference's record
- Python: The chapter's authors report running it; there is no record for this entry alone. R: Reviewed but not run: R wasn't available to the reference's authors.
Purpose
A finite-history probabilistic baseline that predicts words from preceding words. It is useful for small corpora, transparent scoring, domain adaptation, and testing whether a neural model adds value beyond local statistics. Smoothing methods are treated as members of this family rather than independent model counts.
Question / objective
How much predictive information is captured by a finite token history, and how should unseen events receive probability mass?
Architecture / computational structure
A history-to-count table and smoothing/backoff rules define the computation. Learned quantities are corpus counts and any fitted smoothing discounts; n and vocabulary thresholds are design choices.
Assumptions
The finite Markov history loses distant dependencies; tokenization and unseen events dominate small-data behavior.
Formula / computational definition
Factorize p(w_1:T)=product_t p(w_t|w_{t-n+1:t-1}). An additive baseline uses p(w|h)=[c(h,w)+alpha]/[c(h)+alpha V], where c denotes counts, V vocabulary size, and alpha positive smoothing; Kneser–Ney instead discounts counts and uses continuation probabilities.
Parameters and notation
Learned parameters: identified in the architecture subsection. Hyperparameters, design and inference choices: Order n, discount or smoothing strength, vocabulary cutoff, unknown-word policy, and sentence boundaries.
Fitting, fine-tuning, and adaptation
Estimate counts only on training text; tune order and smoothing on development perplexity. Domain adaptation can interpolate domain and general count models. Rebuild affected counts when vocabulary changes, preserve a fixed evaluation tokenizer, and inspect forgetting of general-domain events.
How to use and calibrate
Report held-out cross-entropy, perplexity, unknown-token frequency, and corpus/domain splits; compare models using the same tokenization. Use development data for settings and an independent test set for the final estimate. Report uncertainty across examples or seeds when the evaluation design supports it; model scores and self-assessments are not automatically calibrated probabilities of correctness.
Example application
Build an interpretable baseline for predicting maintenance-log vocabulary before training a neural model.
Interpretation / pitfalls
Watch out
Train/test duplication can make perplexity deceptively good. The code below isolates one stated component; successful execution does not validate model quality or reproduce the cited experiment.
Python and R code examples
Full implementation route: Native dictionaries/tables implement the additive teaching baseline in Lab LNG-A. Exact modified Kneser–Ney requires a documented specialized implementation or custom code; do not label additive smoothing as Kneser–Ney.
Example scope: Exact additive-smoothed conditional distribution for a toy history; not Kneser–Ney.
Dependencies: Python 3 standard library; base R; shared setup above. No model downloads or external services.
Validation: Python component executed in the combined example script; R counterpart supplied but not runtime-tested here. All numbers are synthetic.
Python and R
The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.
Complete calculation — Exact additive-smoothed conditional distribution for a toy history; not Kneser–Ney.
Shared setup for this chapter
import math
def softmax(xs):
m = max(xs)
es = [math.exp(x-m) for x in xs]
return [e/sum(es) for e in es]
def dot(a, b):
return sum(x*y for x, y in zip(a, b))
def matvec(matrix, vector):
return [dot(row, vector) for row in matrix]
def meanvec(rows):
return [sum(row[j] for row in rows)/len(rows) for j in range(len(rows[0]))]
def sigmoid(x):
return 1/(1+math.exp(-x))
def nll(probabilities):
return -sum(math.log(p) for p in probabilities)
counts, alpha = [3, 1, 0], 0.5
p = [(c + alpha) / (sum(counts) + alpha * len(counts)) for c in counts]
assert abs(sum(p) - 1) < 1e-12
print(p)
Complete calculation — Exact additive-smoothed conditional distribution for a toy history; not Kneser–Ney.
Shared setup for this chapter
softmax <- function(x) {
shifted <- exp(x-max(x))
shifted/sum(shifted)
}
counts <- c(3, 1, 0); alpha <- 0.5
p <- (counts + alpha) / (sum(counts) + alpha * length(counts))
stopifnot(abs(sum(p) - 1) < 1e-12)
print(p)
Sources
- Source 1aclanthology.org
From the CodeSplash reference, entry LNG001.