Skip to content

13.3 MLE, Laplace, absolute discounting

The byte bigram at the start of AI Engineering already smooths: it adds one to every count, because a byte pair never seen in training would otherwise get probability 0, the sampler could never produce it, and its NLL on new text would be infinite. That was one formula in one place. Later systems estimate distributions from counts everywhere. The Unigram tokenizer re-estimates its piece probabilities from expected counts on every EM step, the n-gram model with Kneser-Ney estimates the next word for millions of contexts most of which were seen once or never, and PMI divides co-occurrence counts.

Concepts from other sections (9)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

Each of those needs the same three decisions made correctly: what the best estimate from counts is, how much probability to keep for what was not seen, and where that probability goes. This section makes those decisions once, as functions with exact answers. You will prove that the observed frequency is the maximum-likelihood estimate, see why it fails on unseen outcomes, and build the two classical repairs: add-alpha smoothing and absolute discounting, the core of Kneser-Ney.

No code from earlier sections is needed. The reading background is natural logs and nats from Exponents, logs, and units of information and counting from the Discrete math 1 problem set. The reference implementation is course/solutions/python/tinyllm/prob/mle.py, with its contract in mle.pyi.

Learning objectives

  • Prove that ck/Nc_k / N maximizes the log-likelihood of a categorical distribution, using the KL divergence.
  • Explain why the MLE makes unseen outcomes impossible and what that does to perplexity.
  • Implement add-alpha smoothing with the denominator over the whole vocabulary.
  • Implement absolute discounting so that exactly the freed mass goes to a backoff distribution, including for fractional counts.
  • Compute Ney’s discount from counts of counts.
SymbolMeaningType / shape
VVthe vocabulary: every outcome the model can assign probability to; ∣V∣\lvert V \rvert its sizeint
ckc_khow many times outcome kk was observed: an integer from counting, or a fraction when it is an expected count from EMint or float
N=∑kckN = \sum_k c_kthe number of observationsint
qqany distribution over VV: qk≥0q_k \ge 0, ∑kqk=1\sum_k q_k = 1dict[K, float]
ℓ(q)=∑kckln⁡qk\ell(q) = \sum_k c_k \ln q_kthe log-likelihood of the counts under qq, in natsfloat
p^k\hat p_kan estimate of the true probability of kkfloat
α>0\alpha > 0the pseudo-count of add-alpha smoothingfloat
d∈(0,1]d \in (0, 1]the absolute discountfloat
T=∣{k:ck>0}∣T = \lvert \{k : c_k > 0\} \rvertthe number of distinct outcomes seenint
bkb_ka backoff distribution over VV (a simpler model)dict[K, float]
nrn_rthe number of outcomes seen exactly rr times (count of counts)int

If the observations are independent draws from qq, the probability of the data is ∏kqkck\prod_k q_k^{c_k} (each observation of kk contributes a factor qkq_k; the order does not matter for estimating qq). Its log is ℓ(q)=∑kckln⁡qk\ell(q) = \sum_k c_k \ln q_k. Terms with ck=0c_k = 0 contribute nothing, whatever qkq_k is, by the convention 0⋅ln⁡0=00 \cdot \ln 0 = 0. A term with ck>0c_k > 0 and qk=0q_k = 0 is −∞-\infty: the data is impossible under qq.

The maximum-likelihood estimate is the qq that maximizes ℓ(q)\ell(q). It is the observed frequency, p^k=ck/N\hat p_k = c_k / N, and here is why. For any qq,

ℓ(q)−ℓ(p^)=∑kckln⁡qkp^k=N∑kp^kln⁡qkp^k=−N KL(p^ ∥ q)≤0,\ell(q) - \ell(\hat p) = \sum_k c_k \ln \frac{q_k}{\hat p_k} = N \sum_k \hat p_k \ln \frac{q_k}{\hat p_k} = -N \, \mathrm{KL}(\hat p \,\Vert\, q) \le 0,

because the Kullback-Leibler divergence is never negative (Gibbs’ inequality, proved in Entropy, cross-entropy, and KL), and it is 0 only when q=p^q = \hat p. So the frequency wins against every other distribution, which can also be checked numerically by scoring random competitors. It needs N>0N > 0: with no data, 0/00/0 is not an estimate.

The MLE’s optimality is also its weakness: it puts all its mass on what was seen. A word with ck=0c_k = 0 gets p^k=0\hat p_k = 0, and new text containing it gets likelihood 0 and perplexity ∞\infty (see Perplexity, bits per byte, and the NLL accumulator). In language most words are rare, so most of the vocabulary has ck=0c_k = 0 in any given context: this is the normal case, not an edge case. The rest of the section is about how to take some probability away from what was seen and give it to what was not.

The bluntest repair is to pretend every word of the vocabulary was seen α\alpha extra times:

p^k=ck+αN+α∣V∣.\hat p_k = \frac{c_k + \alpha}{N + \alpha \lvert V \rvert}.

The denominator adds α\alpha once per word of VV, including the words that are not keys of counts at all; summing the numerator over all of VV gives N+α∣V∣N + \alpha \lvert V \rvert, so the estimate is a distribution. Every word gets at least α/(N+α∣V∣)>0\alpha / (N + \alpha \lvert V \rvert) > 0. α→0\alpha \to 0 recovers the MLE and α→∞\alpha \to \infty the uniform 1/∣V∣1/\lvert V \rvert; with no data it is exactly uniform. (Bayesian reading: this is the posterior mean under a symmetric Dirichlet(α\alpha) prior; α=1\alpha = 1 is Laplace’s rule of succession.)

Its weakness is that it takes mass in proportion to α∣V∣\alpha \lvert V \rvert, which for a 50 000-word vocabulary and a context seen 10 times hands almost everything to unseen words.

A better repair takes mass from seen words in proportion to how much their counts overstate the future. Church and Gale (1991) counted bigrams in one half of a corpus and looked them up in the other: a bigram seen c≥2c \ge 2 times in the first half appeared on average about c−0.75c - 0.75 times in the second. Seen counts overstate the future by a roughly constant amount. So subtract a constant dd from every seen count and give the freed mass to a backoff distribution bb (in Kneser-Ney, the next lower-order model):

p^k=max⁡(ck−d,0)N+λ bk,λ=1N∑kmin⁡(ck,d).\hat p_k = \frac{\max(c_k - d, 0)}{N} + \lambda \, b_k, \qquad \lambda = \frac{1}{N} \sum_k \min(c_k, d).

Each word gives up min⁡(ck,d)\min(c_k, d): dd if it has that much, its whole count if not. So λ\lambda is precisely the freed fraction and ∑kp^k=(N−Nλ)/N+λ∑kbk=1\sum_k \hat p_k = (N - N\lambda)/N + \lambda \sum_k b_k = 1. For integer counts with d≤1d \le 1 every seen word has at least dd and every unseen word has nothing, so λ=dT/N\lambda = dT/N, the form in most textbooks. The max⁡\max matters for keys whose count is 0, and the min⁡\min for the fractional expected counts of EM in the Unigram tokenizer: a word expected 0.3 times cannot lose 0.5. A seen word keeps (ck−d)/N(c_k - d)/N plus its share of the backoff; an unseen one gets only λbk\lambda b_k. With N=0N = 0 there is nothing to discount and the answer is bb itself.

That leaves the question of how large dd should be. Ney, Essen and Kneser (1994) derived D=n1/(n1+2n2)D = n_1 / (n_1 + 2 n_2) from leaving one observation out at a time, where n1n_1 and n2n_2 count the words seen once and twice. It lies in (0,1](0, 1] when n1>0n_1 > 0. Modified Kneser-Ney uses three such discounts, for counts 1, 2, and 3 or more.

Take counts a = 3, b = 2, c = 1, d = 0, over the vocabulary a b c d e (∣V∣=5\lvert V \rvert = 5; e is not even a key). N=6N = 6, T=3T = 3.

MLE. p^=(3/6,2/6,1/6,0)=(0.5,0.3333,0.1667,0)\hat p = (3/6, 2/6, 1/6, 0) = (0.5, 0.3333, 0.1667, 0) for a b c d, and e would be 0 too.

Log-likelihood. ℓ(p^)=3ln⁡12+2ln⁡13+ln⁡16=−2.0794−2.1972−1.7918=−6.0684\ell(\hat p) = 3 \ln \tfrac12 + 2 \ln \tfrac13 + \ln \tfrac16 = -2.0794 - 2.1972 - 1.7918 = -6.0684 nats. The d term is 0⋅ln⁡0=00 \cdot \ln 0 = 0.

Laplace, α=1\alpha = 1. The denominator is 6+1⋅5=116 + 1 \cdot 5 = 11, giving:

wordabcde (not a key)
ck+1c_k + 143211
p^k\hat p_k4/113/112/111/111/11

The five sum to 11/1111/11. Dividing by 6+1⋅46 + 1 \cdot 4 (only the keys) would give 4/10+3/10+2/10+1/10=14/10 + 3/10 + 2/10 + 1/10 = 1 over the keys and leave 1/101/10 for e on top: a total of 1.11.1. The Laplace estimate’s log-likelihood is 3ln⁡411+2ln⁡311+ln⁡211=−7.33823 \ln \tfrac4{11} + 2 \ln \tfrac3{11} + \ln \tfrac2{11} = -7.3382, lower than the MLE’s, as it must be.

Absolute discounting, d=1/2d = 1/2, uniform backoff bk=1/5b_k = 1/5. The freed mass is λ=dT/N=0.5⋅3/6=1/4\lambda = d T / N = 0.5 \cdot 3 / 6 = 1/4, so each word gets λbk=1/20\lambda b_k = 1/20 from the backoff:

wordmax⁡(ck−d,0)/N\max(c_k - d, 0)/N+λbk+ \lambda b_kp^k\hat p_k
a2.5/6=5/122.5/6 = 5/121/201/207/15=0.46677/15 = 0.4667
b1.5/6=1/41.5/6 = 1/41/201/203/103/10
c0.5/6=1/120.5/6 = 1/121/201/202/15=0.13332/15 = 0.1333
dmax⁡(−0.5,0)/6=0\max(-0.5, 0)/6 = 01/201/201/201/20
e001/201/201/201/20

Sum: 28/60+18/60+8/60+3/60+3/60=128/60 + 18/60 + 8/60 + 3/60 + 3/60 = 1. Without the clamp, d would get −1/12+1/20<0-1/12 + 1/20 < 0.

Ney’s discount. One word seen once (c), one seen twice (b): D=1/(1+2⋅1)=1/3D = 1/(1 + 2 \cdot 1) = 1/3.

These numbers are the first five test cases a correct implementation must reproduce.

Five functions cover the section:

python/tinyllm/prob/mle.py
def mle(counts: Mapping[K, int]) -> dict[K, float] # c_k / N
def log_likelihood(counts: Mapping[K, int], probs: Mapping[K, float]) -> float # nats; -inf if impossible
def laplace(counts: Mapping[K, int], vocab_size: int, alpha: float = 1.0) -> dict[K, float]
def absolute_discount(counts: Mapping[K, int], d: float, backoff: Mapping[K, float]) -> dict[K, float]
def ney_discount(counts: Mapping[K, int]) -> float # n1 / (n1 + 2 n2)

Counts are finite non-negative numbers: integers from counting (numpy integers are fine) or floats from EM; NaN, infinity, bools, and strings are a ValueError. laplace returns the keys of counts only; the contract states the probability of every other word. absolute_discount returns every key of backoff.

Seven decisions determine the implementation.

  1. Counts are numbers, checked once. Every function starts from counts, so one validator rejects what is not a finite non-negative real (bools are int subclasses in Python and are rejected explicitly) and returns NN, summed with math.fsum so fractional EM counts do not drift.
  2. The MLE is ck/Nc_k / N, and needs N>0N > 0. The KL argument proves the frequency is optimal; with N=0N = 0 it is 0/00/0, so the function raises instead of returning NaNs.
  3. The log-likelihood skips zero counts before looking up qq. 0ln⁡0=00 \ln 0 = 0 by convention, and a zero-count key need not even be in probs. For ck>0c_k > 0, a missing or zero qkq_k makes the data impossible: return −∞-\infty immediately.
  4. Laplace divides by N+α∣V∣N + \alpha\lvert V \rvert. One pseudo-count per word of the vocabulary, not per key, so the keys plus the unseen words sum to 1. The function returns only the keys; every other word’s probability is α/(N+α∣V∣)\alpha/(N + \alpha\lvert V \rvert) by the same formula.
  5. Absolute discounting: clamp, charge exactly what was taken, spread it by bb. Each key loses min⁡(ck,d)\min(c_k, d); λ\lambda is the sum of those losses over NN; every word of the backoff vocabulary gets max⁡(ck−d,0)/N+λbk\max(c_k - d, 0)/N + \lambda b_k. The output ranges over backoff’s keys because that is the vocabulary the smoothed distribution covers, so every counted key must be in it.
  6. No data means the backoff, as a fresh dict. With N=0N = 0 nothing was freed and nothing was seen; the answer is bb. Returning a copy matters because Kneser-Ney may edit one context’s distribution.
  7. Ney’s D=n1/(n1+2n2)D = n_1/(n_1 + 2n_2) needs a singleton. With n1=0n_1 = 0 the discount would be 0 (no smoothing) or 0/00/0; raise.

The validator, the MLE, and the log-likelihood come first:

def _check_counts(counts: Mapping[Hashable, float]) -> float:
for k, c in counts.items():
# bool is a subclass of int: True would silently count as 1.
if isinstance(c, bool) or not isinstance(c, numbers.Real):
raise ValueError(f"count of {k!r} must be a number, got {c!r}")
if not math.isfinite(c) or c < 0:
raise ValueError(f"count of {k!r} must be finite and >= 0, got {c}")
return math.fsum(float(c) for c in counts.values()) # N, exactly rounded
def mle(counts: Mapping[Hashable, float]) -> dict:
n = _check_counts(counts)
if n == 0:
raise ValueError("mle needs at least one observation (N = 0 gives 0 / 0)")
return {k: float(c) / n for k, c in counts.items()} # divide by N, not by the number of keys
def log_likelihood(counts, probs) -> float:
_check_counts(counts)
terms = []
for k, c in counts.items():
if c == 0:
continue # 0 * log 0 = 0: an unseen outcome costs nothing (and need not be in probs)
q = float(probs.get(k, 0.0))
if q <= 0.0:
return -math.inf # an observed outcome the model calls impossible
terms.append(float(c) * math.log(q))
return math.fsum(terms)

numbers.Real accepts Python ints, floats, and numpy integer and float scalars, which is what counting code produces.

Laplace smoothing is a few lines once the denominator is right:

def laplace(counts, vocab_size: int, alpha: float = 1.0) -> dict:
if not alpha > 0: # also rejects NaN
raise ValueError(f"alpha must be > 0, got {alpha!r}")
if len(counts) > vocab_size: # more keys than words: the vocabulary is wrong
raise ValueError(f"{len(counts)} keys do not fit a vocabulary of {vocab_size}")
n = _check_counts(counts)
# The denominator adds alpha once per outcome of the vocabulary, seen or not.
denom = n + alpha * vocab_size
return {k: (float(c) + alpha) / denom for k, c in counts.items()}

On the hand example, denom is 6+1⋅5=116 + 1 \cdot 5 = 11 and the keys get 4,3,2,14, 3, 2, 1 elevenths; e, not a key, has 1/111/11 by the same formula, and the five sum to 1.

Absolute discounting carries most of the validation, because its inputs come from two places that must agree:

def absolute_discount(counts, d: float, backoff) -> dict:
if not 0.0 < d <= 1.0:
raise ValueError(f"d must lie in (0, 1], got {d!r}")
total_b = math.fsum(float(v) for v in backoff.values())
if abs(total_b - 1.0) > 1e-9:
raise ValueError(f"backoff must sum to 1, got {total_b!r}")
missing = [k for k in counts if k not in backoff]
if missing: # a counted word outside the output vocabulary would lose its mass
raise ValueError(f"{missing[0]!r} is counted but not in the backoff vocabulary")
n = _check_counts(counts)
if n == 0:
return {k: float(v) for k, v in backoff.items()} # a copy, never the caller's dict
# Exactly the mass the discount removed: d from each seen count, or the
# whole count when it is smaller than d (fractional EM counts). For
# integer counts this is d * T / N with T the number of seen keys.
lam = math.fsum(min(float(c), d) for c in counts.values()) / n
return {
k: max(float(counts.get(k, 0)) - d, 0.0) / n + lam * float(b) # clamp: a zero count stays >= 0
for k, b in backoff.items()
}

On the hand example, min⁡(ck,12)\min(c_k, \tfrac12) is 12,12,12,0\tfrac12, \tfrac12, \tfrac12, 0, so λ=1.5/6=14\lambda = 1.5/6 = \tfrac14; d (count 0) gets max⁡(−12,0)/6+14⋅15=120\max(-\tfrac12, 0)/6 + \tfrac14 \cdot \tfrac15 = \tfrac1{20}. A zero-count key contributes min⁡(0,d)=0\min(0, d) = 0 to λ\lambda, so counting TT only over seen keys falls out of the formula without a separate test.

Ney’s discount is the last piece:

def ney_discount(counts) -> float:
_check_counts(counts)
n1 = sum(1 for c in counts.values() if c == 1) # words seen once
n2 = sum(1 for c in counts.values() if c == 2) # words seen twice
if n1 == 0:
raise ValueError("no outcome was seen exactly once: Ney's discount would be 0")
return n1 / (n1 + 2 * n2) # in (0, 1] once n1 > 0

The full solution is mle.py.

Every function is O(∣keys∣)O(\lvert \text{keys} \rvert) (and absolute_discount O(∣Vb∣)O(\lvert V_b \rvert) over the backoff), one or two passes, with fsum adding a small constant factor for exact summation.

The general λ=∑min⁡(ck,d)/N\lambda = \sum \min(c_k, d)/N is preferred over the textbook dT/NdT/N. They agree for integer counts, but dT/NdT/N is wrong for EM’s fractional counts: a count of 0.3 would be charged 0.5, and the distribution would sum to more than 1. The general form costs nothing extra.

Laplace returns a sparse output. Returning a dict over the whole vocabulary would cost O(∣V∣)O(\lvert V \rvert) per call, and the n-gram model calls this for millions of contexts. Returning the keys and stating the formula for the rest keeps it proportional to what was seen.

Among the alternatives, Good-Turing re-estimates each count from nr+1/nrn_{r+1}/n_r and is noisy for large rr; add-alpha is simple but hands too much mass to a large vocabulary. Absolute discounting with a backoff is the base of Kneser-Ney, the best classical n-gram smoother, which is why the n-gram model builds on it.

One tradeoff is accepted: the backoff check uses a 10−910^{-9} tolerance and the count checks are strict, so a slightly unnormalized backoff from a long float computation is accepted but a negative count never is.

A correct solution reproduces the hand example, satisfies the normalization properties on random inputs, and handles the boundaries. The checks are listed here with why each matters later.

CaseKind of checkChecksWhy it matters downstream
MLE by handunit1/2, 1/3, 1/6, 0everyone agrees on the definition
Laplace by handunit4/11, 3/11, 2/11, 1/11, and 1/11 for ethe denominator counts the whole vocabulary
absolute discounting by handunit7/15, 3/10, 2/15, 1/20, 1/20the formula Kneser-Ney builds on
Ney’s discount by handunitD=1/3D = 1/3the starting discount of Kneser-Ney
log-likelihood by handunit−6.0684-6.0684 for the MLE, −7.3382-7.3382 for Laplacesmoothing costs training likelihood
the MLE maximizes the likelihoodpropertyrandom competitors and small perturbations score lowerthe defining property
the MLE is a distributionpropertysums to 1; zeros stay 0no NaN, no missing key
Laplace over the whole vocabularypropertykeys plus the unseen words sum to 1 for three α\alphathe whole vocabulary is normalized
Laplace limitsunittiny α\alpha is the MLE, huge α\alpha and no data are uniformα\alpha interpolates
absolute discounting sums to 1propertyrandom counts with zeros, random backoffs, four ddλ\lambda is exactly the freed mass
zero-count keysboundarya zero-count key gets only λbk\lambda b_kno negative probability
no databoundaryN=0N = 0 returns a copy of bban unseen context in the n-gram model
d=1d = 1boundarysingletons get only backoff massthe edge of the allowed range
bad argumentsboundarynegative, NaN, infinite, bool, or string counts; no data; bad α\alpha, dd, VV, or backoffupstream counting bugs fail here
fractional counts from EMunitthe MLE of expected counts; λ=∑kmin⁡(ck,d)/N\lambda = \sum_k \min(c_k, d)/N when a count is below ddEM in the Unigram tokenizer produces fractions
Ney’s discount edge casesunitall singletons give 1; no singletons raiseD∈(0,1]D \in (0, 1]
zero terms and impossible databoundary0ln⁡0=00 \ln 0 = 0; an observed outcome with q=0q = 0 gives −∞-\inftyinfinite perplexity

The mistakes behind failures of these checks fall into three groups.

The first group gets the normalizer wrong. Dividing by the number of distinct words instead of NN produces “probabilities” that sum to N/∣keys∣N / \lvert \mathrm{keys} \rvert; the solution divides by n from _check_counts. A Laplace denominator of N+α⋅N + \alpha \cdot (number of keys) makes the keys alone sum to 1, so the unseen words’ mass is extra and the total is above 1; the solution uses denom = n + alpha * vocab_size.

The second group charges the wrong amount in absolute discounting. Counting TT over every key, zero counts included, hands more mass to the backoff than was freed; λ\lambda sums min(c, d), which is 0 for a zero count. Using λ=dT/N\lambda = dT/N with fractional counts charges a count of 0.3 the full 0.5, so the result sums to more than 1. Omitting the clamp at 0 gives a key counted zero times a negative probability; the solution uses max(... - d, 0.0). And Ney’s discount written as n1/(n1+n2)n_1 / (n_1 + n_2) is too large; the factor 2 matters.

Warning: Returning the caller’s backoff dict when N=0N = 0 looks harmless, but Kneser-Ney edits one context’s distribution and would corrupt the shared lower order. Always build a new dict.

The third group mishandles edge inputs. Scoring zero-count terms, or indexing a missing probability, turns 0ln⁡00 \ln 0 into −∞-\infty or a KeyError; the solution does continue on c == 0 and then probs.get(k, 0.0). Accepting NaN or infinite counts, or estimating from no data, yields NaN probabilities or a ZeroDivisionError; _check_counts rejects the former and mle raises on N=0N = 0.

These estimators reappear wherever counts become probabilities. The Unigram tokenizer seeds its piece probabilities with mle of substring counts, and each EM step is the same estimate over expected counts. Interpolated Kneser-Ney is absolute_discount per context with ney_discount-style D1,D2,D3+D_1, D_2, D_{3+} and a continuation-count backoff. Mutual information, PMI, and PPMI divides joint and marginal MLEs from co-occurrence counts, and in Perplexity, bits per byte, and the NLL accumulator, −ℓ(q)/N-\ell(q)/N is the NLL per token whose exponential is perplexity.

  • Jurafsky and Martin, Speech and Language Processing (3rd ed. draft), chapter 3, “N-gram Language Models”.
  • Chen and Goodman, “An Empirical Study of Smoothing Techniques for Language Modeling” (1998).
  • KenLM, lm/builder/adjust_counts.cc: modified Kneser-Ney with three discounts per order estimated from count-of-counts, on disk-backed sorted n-gram streams.
  • scikit-learn’s MultinomialNB (sklearn/naive_bayes.py): the same add-alpha estimate per class, as its alpha parameter.
  • The SentencePiece Unigram trainer, src/unigram_model_trainer.cc: EM where the M-step is this MLE plus a digamma correction (a Bayesian variant) and pruning.
  • Log-likelihood: ∑kckln⁡qk\sum_k c_k \ln q_k, the log probability of the observed counts under a distribution qq.
  • Maximum-likelihood estimate (MLE): the distribution that maximizes the log-likelihood; for counts, the frequency ck/Nc_k/N.
  • Add-alpha (Laplace) smoothing: adding a pseudo-count α\alpha to every word of the vocabulary before normalizing.
  • Absolute discounting: subtracting a fixed dd from each seen count and giving the freed mass to a backoff distribution.
  • Backoff distribution: a simpler model that receives the probability mass freed by discounting.
  • Count of counts: nrn_r, the number of outcomes seen exactly rr times.
  • Ney’s discount: the estimate D=n1/(n1+2n2)D = n_1/(n_1 + 2n_2) of the absolute discount.
  • The maximum-likelihood estimate of a categorical distribution is the observed frequency ck/Nc_k / N; no other distribution gives the data a higher log-likelihood, because the gap is −N KL(p^∥q)-N\,\mathrm{KL}(\hat p \Vert q).
  • The MLE gives every unseen outcome probability 0, so a single unseen word in new text makes its likelihood 0 and its perplexity infinite.
  • Add-alpha smoothing divides by N+α∣V∣N + \alpha \lvert V \rvert, one pseudo-count per word of the whole vocabulary, seen or not.
  • Absolute discounting takes min⁡(ck,d)\min(c_k, d) from every count and gives exactly that mass, dT/NdT/N for integer counts, to a backoff distribution: the core of Kneser-Ney.
  • Ney’s D=n1/(n1+2n2)D = n_1/(n_1 + 2n_2) gives a principled starting discount and needs at least one singleton.
  1. Why is the Laplace denominator N+α∣V∣N + \alpha\lvert V \rvert and not N+α⋅(number of keys)N + \alpha \cdot (\text{number of keys})?

    Answer

    Every word of the vocabulary receives a pseudo-count, including words that are not keys of counts at all. Summing ck+αc_k + \alpha over all of VV gives N+α∣V∣N + \alpha\lvert V \rvert. With only the keys in the denominator, the keys alone sum to 1 and the unseen words’ α/(⋅)\alpha/(\cdot) comes on top, for a total above 1 (1.1 in the hand example).

  2. Why does absolute_discount clamp with max(c - d, 0) when d≤1d \le 1 and counts are integers?

    Answer

    Keys can have count 0 (they were listed but not seen), and counts.get(k, 0) returns 0 for every backoff word not counted. Without the clamp each of those would get −d/N+λbk-d/N + \lambda b_k, which can be negative (−1/12+1/20-1/12 + 1/20 in the hand example). The clamp says an unseen word loses nothing because it had nothing.

  3. Why does log_likelihood continue on c == 0 before reading probs?

    Answer

    0⋅ln⁡q=00 \cdot \ln q = 0 for any qq, including q=0q = 0 (by the 0ln⁡0=00 \ln 0 = 0 convention). Reading first would either compute 0⋅(−∞)=NaN0 \cdot (-\infty) = \text{NaN} or return −∞-\infty for data that is perfectly possible, and a zero-count key may be absent from probs entirely.

  4. With N=0N = 0, why return a copy of the backoff rather than backoff itself?

    Answer

    The answer is mathematically bb, but the n-gram model stores one distribution per context and may adjust it later. Returning the shared lower-order dict would let an edit to one unseen context change the backoff for every context.

  5. Why does ney_discount raise when no word was seen exactly once?

    Answer

    D=n1/(n1+2n2)D = n_1/(n_1 + 2n_2) is 0 when n1=0n_1 = 0 (or 0/00/0 when n2=0n_2 = 0 too). A zero discount frees no mass, so unseen words would get probability 0, the problem smoothing exists to solve. Raising tells the caller that this count-of-counts gives no usable estimate.