Combining Values in Log Space
Sometimes you need the log of a sum of probabilities while storing each probability as a log. Directly computing can underflow for very negative inputs and overflow for large positive inputs. The stable form is log-sum-exp:
Subtracting the maximum makes every exponent nonpositive, then adding it back preserves the exact algebra. Use scipy.special.logsumexp or torch.logsumexp.
Stable Softmax Uses the Same Shift
Softmax is . A naive implementation can overflow on large logits and underflow on very negative ones. Subtracting changes neither the normalized probabilities nor their ordering and keeps exponentials in range.
When you need log-probabilities, use a library's log_softmax rather than computing softmax and then taking a log. PyTorch provides torch.nn.functional.log_softmax, and SciPy provides scipy.special.log_softmax.
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으로 처리해버릴수있으니