17/25
Part 4 of 6 · A stable softmaxLearn
Subtract the largest score first, and the answer doesn't change
The fix is to shift the scores before the exponential.
| Step | ||||
|---|---|---|---|---|
| scores | 1000 | 1001 | 1002 | |
| minus the max | -2 | -1 | 0 | |
| e to the power | 0.14 | 0.37 | 1.00 | the largest is exactly 1 |
| divide by the sum | 0.09 | 0.24 | 0.67 | the sum is 1.50 |
Subtract the largest score from every score. Now the largest exponent is , so nothing overflows. The sum is at least 1, so nothing divides by zero.
And the answer doesn't change, because softmax doesn't change when you subtract the same number from every input:
Here is one row of scores and is any number. Subtracting divides the top and the bottom by the same . Pick , the largest score.
Here it is for one row of scores:
def shifted(s):
e = np.exp(s - s.max())
return e / e.sum()
print(shifted(big))
print(shifted(big - 1000))
[0.09003057 0.24472847 0.66524096]
[0.09003057 0.24472847 0.66524096]
The same weights for 1000, 1001, 1002 as for 0, 1, 2. Only the differences between the scores matter.