Skip to content

Commit 23b80bd

Browse files
committed
fix: stabilize Softmax for large finite inputs
1 parent 5c39e87 commit 23b80bd

2 files changed

Lines changed: 16 additions & 5 deletions

File tree

‎Maths/Softmax.js‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
// Wikipedia: https://en.wikipedia.org/wiki/Softmax_function
22

33
const Softmax = (inputs) => {
4-
const eulerExpOfAllInputs = inputs.map((input) => Math.exp(input))
4+
const maxInput = inputs.reduce((maximum, input) => Math.max(maximum, input))
5+
const eulerExpOfAllInputs = inputs.map((input) => Math.exp(input - maxInput))
56
const sumOfEulerExpOfAllInputs = eulerExpOfAllInputs.reduce((a, b) => a + b)
67

7-
return inputs.map((input) => {
8-
const eulerExpInputs = Math.exp(input)
9-
return eulerExpInputs / sumOfEulerExpOfAllInputs
10-
})
8+
return eulerExpOfAllInputs.map((value) => value / sumOfEulerExpOfAllInputs)
119
}
1210

1311
export { Softmax }

‎Maths/test/Softmax.test.js‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,19 @@
11
import { Softmax } from '../Softmax'
22

33
describe('Softmax', () => {
4+
it.each([1000, -1000])(
5+
'should normalize finite logits with a common offset of %i',
6+
(offset) => {
7+
const expected = Softmax([0, 1, 2])
8+
const actual = Softmax([offset, offset + 1, offset + 2])
9+
actual.forEach((value, index) => {
10+
expect(Number.isFinite(value)).toBe(true)
11+
expect(value).toBeCloseTo(expected[index], 14)
12+
})
13+
expect(actual.reduce((sum, value) => sum + value, 0)).toBeCloseTo(1, 14)
14+
}
15+
)
16+
417
it('should return equal distribution of 1 for equal input values', () => {
518
expect(Softmax([1, 1])).toEqual([0.5, 0.5])
619
expect(Softmax([1, 1, 1, 1])).toEqual([0.25, 0.25, 0.25, 0.25])

0 commit comments

Comments
 (0)