Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 3 additions & 5 deletions Maths/Softmax.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
// Wikipedia: https://en.wikipedia.org/wiki/Softmax_function

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

return inputs.map((input) => {
const eulerExpInputs = Math.exp(input)
return eulerExpInputs / sumOfEulerExpOfAllInputs
})
return eulerExpOfAllInputs.map((value) => value / sumOfEulerExpOfAllInputs)
}

export { Softmax }
13 changes: 13 additions & 0 deletions Maths/test/Softmax.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,19 @@
import { Softmax } from '../Softmax'

describe('Softmax', () => {
it.each([1000, -1000])(
'should normalize finite logits with a common offset of %i',
(offset) => {
const expected = Softmax([0, 1, 2])
const actual = Softmax([offset, offset + 1, offset + 2])
actual.forEach((value, index) => {
expect(Number.isFinite(value)).toBe(true)
expect(value).toBeCloseTo(expected[index], 14)
})
expect(actual.reduce((sum, value) => sum + value, 0)).toBeCloseTo(1, 14)
}
)

it('should return equal distribution of 1 for equal input values', () => {
expect(Softmax([1, 1])).toEqual([0.5, 0.5])
expect(Softmax([1, 1, 1, 1])).toEqual([0.25, 0.25, 0.25, 0.25])
Expand Down