Sub topic 8
Working in log space
This chapter assumes you know the naive Bayes decision rule and how to estimate priors and smoothed likelihoods. It explains why a direct implementation fails on real documents, and how to fix it with logarithms.
The underflow problem
The naive Bayes score for class c is a product: the prior times one likelihood per feature.
P(c) · P(x₁ | c) · P(x₂ | c) · … · P(xₙ | c)
Each likelihood is a small number, often 0.001 or less. A document with 500 words multiplies 500 of them. A 64-bit float cannot represent values much below about 1e-308, so the product rounds to exactly 0.0. This is called numerical underflow. When every class score underflows to zero, the classifier has no way to rank the classes.
p = 1.0
for _ in range(200):
p *= 0.001
print(p) # 0.0, because 1e-600 is below the float rangeThe log fix
The logarithm turns products into sums: log(a · b) = log a + log b. The log is also increasing, so the class with the largest score is the same before and after taking logs. The decision rule becomes:
ŷ = argmax over c of [ log P(c) + Σᵢ log P(xᵢ | c) ]
Sums of log values stay in a safe range. Two hundred factors of 0.001 give 200 · log(0.001) ≈ −1381.55, which is an ordinary float.
import math
p = 1.0
log_p = 0.0
for _ in range(200):
p *= 0.001
log_p += math.log(0.001)
print(p) # 0.0
print(log_p) # about -1381.55Scores are now negative numbers. A score closer to zero means a more probable class.
Compute the logs once
In the from-scratch classifier, train stores log_prior and log_like. It takes each logarithm once during training. predict then only adds numbers that are already stored. This is faster than calling math.log on every prediction. It also shows why smoothing matters: math.log(0) raises an error, and a zero likelihood would otherwise give a score of minus infinity.
import math
log_prior = {"spam": math.log(0.5), "ham": math.log(0.5)}
log_like = {
"spam": {"free": math.log(0.3), "meeting": math.log(0.05)},
"ham": {"free": math.log(0.05), "meeting": math.log(0.3)},
}
doc = ["free", "free", "meeting"]
scores = {
c: log_prior[c] + sum(log_like[c][w] for w in doc) for c in log_prior
}
print(scores)
print(max(scores, key=scores.get)) # spamRepeated words are counted each time, which matches the multinomial model.
Recovering probabilities
Sometimes you need real posterior probabilities, not just the winning class. Do not exponentiate the raw scores, because they would underflow again. Subtract the largest score first, then normalize. This is the log-sum-exp trick.
import math
scores = {"spam": -1400.2, "ham": -1403.9}
m = max(scores.values())
exp = {c: math.exp(s - m) for c, s in scores.items()}
total = sum(exp.values())
print({c: v / total for c, v in exp.items()})The best class now has exp(0) = 1, so at least one term is safe. Terms far below it may round to 0, which is correct for practical purposes. scikit-learn's predict_proba does the same thing internally.
Common errors
- Multiplying probabilities in a loop and getting 0.0 for every class.
- Calling
math.logon an unsmoothed likelihood of 0. - Exponentiating raw log scores before subtracting the maximum.
- Mixing log priors with plain likelihoods in the same sum.
Exercise
A document has 300 words, and each word has likelihood 0.0001 under class A. Why does the direct product fail, and what is the log score, ignoring the prior? Use log base 10 to keep the arithmetic simple.
Show answer
The product is 1e-1200, below the smallest float (about 1e-308), so it underflows to 0.0. In log base 10, each word contributes −4, so the score is 300 · (−4) = −1200, which is easy to store and compare.