Log-Probability and Underflow Mitigation
The Underflow Problem
The Naive Bayes classification rule multiplies many small probabilities:
With Laplace smoothing, a typical might be ~0.001. For a document with 100 words, the product is roughly . Standard 64-bit floating-point numbers can represent values down to approximately before hitting zero. A 100-word document is close to this boundary; longer documents or smaller probabilities push the product to exactly zero on the computer.
Floating-point underflow turns a mathematically valid (but tiny) number into zero. When this happens, the classifier loses all discriminative information: every class product becomes zero, and the argmax is meaningless.
Solution: Work in Log Space
Since is strictly monotonically increasing, the argmax is identical:
The product becomes a sum of log-probabilities. Each is a moderate negative number (e.g., ). For 100 words, the sum is roughly , which is easily representable.
Why This Works
Logarithms map multiplication to addition:
For three probabilities:
Each term is a negative number. The sum grows (becomes more negative) linearly with document length, rather than exponentially shrinking toward zero.
Worked Example
Classify a 10-word document with two classes. Smoothed probabilities:
| Word | ||
|---|---|---|
| 0.001 | 0.002 | |
| 0.003 | 0.001 | |
| 0.0005 | 0.004 | |
| 0.002 | 0.001 | |
| 0.001 | 0.003 | |
| 0.004 | 0.0005 | |
| 0.001 | 0.002 | |
| 0.002 | 0.001 | |
| 0.003 | 0.001 | |
| 0.0005 | 0.002 |
Priors: , .
In probability space (dangerous):
The product is approximately , still representable for 10 words, but for 100 words it would underflow.
In log space (safe):
Sum for A: . Sum for B: .
Since , the classifier predicts Class B. The log-space computation is numerically stable for documents of any length.
Implementation Note
Always convert to log space immediately after computing smoothed probabilities. Pre-compute for every word-class pair during training. At classification time, sum the pre-computed log values for the words in the document and add . The class with the largest (least negative) sum wins.
Summary
| Approach | Operation | Risk |
|---|---|---|
| Probability space | Multiply | Underflow for ~100+ words |
| Log space | Sum | Safe for any document length |
Past paper questions: y2021p3q9(a)