LogSumExp and Its Numerical Stability
Introduction
When we do large number or small number multiplications, it is easy to overflow or underflow in computer programs so that we would not get our expected result. To avoid these situations, people tend to do all the multiplications in the log domain.
For example, and , and we would like to know . Instead of calculating the explosive , we have , , and $1000 + 2000 = 3000$. Similarly, when and , we have , , and $\log ab = $ .
We would not jump out of the log domain unless it is the final step. However, how should we calculate the log of the sum of exponentials (logsumexp) without leaving the log domain? More formally, given , how to calculate ?
Incorrect Approach
This is not the correct approach. If one of is extremely large, you would be just calculating in the computer program. On the other hand, if all the are extremely small, you would be just calculating in the computer program. In either case, there would be a problem.
Correct Approach
where .
If at least one of the is extremely large, the value of would not be greater than 1.0. If all the are extremely small, there would be at least one that is equal to 1.0, and the rest of might be very close or equal to 0. Taken together, is always in a range of [1, N].
Therefore, when it comes to computer program, instead of using , we use to calculate the logsumexp without jumping out of the log domain.
Miscellaneous
The overflow and underflow problems are common in many problems such as machine learning, hidden Markov model and other probabilistic models. One should be careful handling these problems when implementing something from scratch.
SciPy has the logsumexp function that is ready for use.