Living in Log Space
Once you start summing log-probabilities, you sometimes need to combine log-probabilities — for example, the log of a sum of probabilities. The naive way () hits underflow when are very negative. The fix: log-sum-exp.
Subtracting the max keeps the exponentials in a sane range. Adding it back at the end recovers the right answer. scipy.special.logsumexp and torch.logsumexp handle it for you.
Why Softmax Is Really Log-Softmax in Disguise
Softmax: . Naive implementation underflows when is very negative. Modern frameworks subtract first — same trick as log-sum-exp.
If you ever need log(softmax(x)), never compute it as np.log(softmax(x)). Use log_softmax(x) directly — it's numerically stable. PyTorch and NumPy/SciPy provide it.
import numpy as np from scipy.special import logsumexp
logs = np.array([-1000, -1001, -1002])
m = np.max(logs) shifted = logs - m exp_terms = np.exp(shifted) s = np.sum(exp_terms) manual = m + np.log(s)
scipy_result = logsumexp(logs)
print("manual :", manual) print("scipy :", scipy_result) print("diff :", abs(manual - scipy_result))
출력
manual : -999.5923940355556
scipy : -999.5923940355556
diff : 0.0
언더플로우를 방지하려고 하는 기법인가보다. 에러값이 점점 작아질수록 중요한작업인듯,, 잘못하면 에러가있는데도 0으로 처리해버릴수있으니