Sub topic 8
Working in log space
This chapter assumes you know the naive Bayes decision rule from the earlier chapters, can read basic Python, and remember that a logarithm turns products into sums. Here you will see why the decision rule is computed with logarithms and how to turn log scores back into probabilities safely.
The problem: products of small numbers
The naive Bayes rule picks the class that maximizes a product:
P(c) × P(x₁ | c) × P(x₂ | c) × … × P(xₙ | c)
Each likelihood is a probability, so it is at most 1. In text classification, a single word often has a likelihood around 0.001 to 0.00001. A document with 100 words multiplies 100 of these numbers together.
A 64-bit float (the default Python float) can represent positive numbers only down to about 5e-324. Anything smaller rounds to exactly 0.0. This failure is called numerical underflow. When it happens, every class gets a score of 0.0, and the classifier cannot tell the classes apart. It silently returns whichever class comes first.
import math
p = 1e-5
product = 1.0
for _ in range(100):
product *= p
print(product)
log_sum = sum(math.log(p) for _ in range(100))
print(log_sum)The first line prints 0.0, because the true value is 1e-500. The second prints about -1151.29, an ordinary number that is easy to store and compare.
Why taking logs is safe
The logarithm is monotonic increasing: if a > b, then log a > log b. So the class with the largest product also has the largest log of that product. Taking logs never changes which class wins.
Logs also turn products into sums:
log P(c | x) ∝ log P(c) + Σᵢ log P(xᵢ | c)
The symbol ∝ means "proportional to". We dropped the evidence term P(x), because it is the same for every class and cannot change the argmax.
| Quantity | Raw probability space | Log space |
|---|---|---|
| Combining features | multiply | add |
| Typical magnitude for 100 words | 1e-500 (underflows) | about -1150 |
| Best class | largest value | largest value (least negative) |
| Zero probability | 0.0 | log(0) is undefined |
The last row matters. A likelihood of exactly 0 has no logarithm. Python's math.log(0) raises ValueError, and NumPy's np.log(0) returns -inf with a warning. This is one more reason for Laplace smoothing, from the previous chapter. With smoothing, every likelihood is strictly positive, so every log is finite.
Where the logs are computed
The efficient design takes logs once, at training time, and stores them. Prediction then only adds numbers. The from-scratch classifier in this tutorial does exactly this:
log_prior[c]stores log P(c).log_like[c][w]stores log P(w | c) for every word in the vocabulary.predictsums the stored values for the words in the document.
Prediction cost is then one dictionary lookup and one addition per word. No exp, no log, and no multiplication happens at prediction time.
Log scores are not probabilities
The sum log_prior[c] + sum(log_like[c][w] ...) is the log of an unnormalized posterior. It is a negative number such as -1200. You cannot read it as a probability.
Two consequences follow:
- Scores from different documents are not comparable. A longer document adds more negative terms, so its scores are lower. Compare classes within one document only.
- If you want a probability, you must normalize across classes. That requires exponentiating, which brings underflow back.
Normalizing without underflow: the log-sum-exp trick
To get P(c | x), divide each class's unnormalized value by their sum:
P(c | x) = exp(sᶜ) / Σk exp(sk)
where sᶜ is the log score of class c. With scores near -1200, exp(-1200) is 0.0 for every class, and you would divide 0 by 0.
The fix is to subtract the largest score from all scores before exponentiating. This multiplies the numerator and denominator by the same constant, so the result is unchanged. The best class now has exponent 0, so exp gives 1.0 for it, and the denominator is at least 1.
import math
def probs_from_log_scores(scores):
m = max(scores.values())
exps = {c: math.exp(s - m) for c, s in scores.items()}
total = sum(exps.values())
return {c: v / total for c, v in exps.items()}
scores = {"spam": -1200.0, "ham": -1203.0}
try:
naive = {c: math.exp(s) for c, s in scores.items()}
print({c: v / sum(naive.values()) for c, v in naive.items()})
except ZeroDivisionError:
print("naive normalization failed: 0.0 / 0.0")
print(probs_from_log_scores(scores))The naive version fails, because both exp calls return 0.0. The stable version prints about {'spam': 0.9526, 'ham': 0.0474}. The gap of 3 in log space means spam is e³ ≈ 20 times more likely than ham.
Log space in the other variants
The same idea applies to every variant, but the terms differ:
- Multinomial: each word contributes
count × log P(w | c). A word that appears three times adds its log likelihood three times. Thepredictfunction in this tutorial gets this by looping over every token in the document. - Bernoulli: each vocabulary word contributes either
log pif present orlog(1 - p)if absent. Absent words still add to the score. - Gaussian: each feature contributes the log of the normal density. A density is not a probability, and it can exceed 1 when the variance is small. The log density can then be positive. This is correct, and nothing is wrong with the model.
Common errors
- Logging after multiplying. Computing
math.log(product_of_likelihoods)does not help, because the product has already underflowed to 0.0. Take logs of each factor, then sum. - Mixing spaces. Adding a raw prior (0.5) to a log likelihood (-7.3) gives a meaningless number. Store
log(0.5). - Comparing scores across documents. Use scores only to rank classes for one input.
- Forgetting unknown words. In the from-scratch code,
if w in vocabskips words never seen in training. Without it, the lookup raisesKeyError. Skipping a word adds the same nothing to every class, so it does not bias the result. - Using base 2 in one place and base e in another. The base does not change the argmax, but you must use the same base throughout, and
expmust match the base you used.
Exercise
A document has two classes with log scores A = -950.2 and B = -948.7. Which class wins? Then compute the normalized posterior of class B using the subtract-the-maximum trick. Give the answer to two decimal places.
Show answer
Class B wins, because -948.7 is larger (less negative) than -950.2. Subtract the maximum, -948.7, from both scores: B becomes 0 and A becomes -1.5. Then exp(0) = 1 and exp(-1.5) ≈ 0.2231, so the total is 1.2231. The posterior of B is 1 / 1.2231 ≈ 0.82, and the posterior of A is about 0.18.
Exercise
Why does Laplace smoothing matter more once you work in log space, and what happens to a score if one likelihood in the sum is exactly 0?
Show answer
A likelihood of exactly 0 has log equal to negative infinity (or a ValueError in Python's math.log). The whole sum then becomes negative infinity, so that class can never win, whatever the other words say. Smoothing keeps every likelihood positive, so every log is finite and a single unseen word cannot veto a class.