mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 00:01:37 +08:00
Added Softmax to Maths folder (#516)
This commit is contained in:
13
Maths/Softmax.js
Normal file
13
Maths/Softmax.js
Normal file
@ -0,0 +1,13 @@
|
||||
// Wikipedia: https://en.wikipedia.org/wiki/Softmax_function
|
||||
|
||||
const Softmax = (inputs) => {
|
||||
const eulerExpOfAllInputs = inputs.map(input => Math.exp(input))
|
||||
const sumOfEulerExpOfAllInputs = eulerExpOfAllInputs.reduce((a, b) => a + b)
|
||||
|
||||
return inputs.map((input) => {
|
||||
const eulerExpInputs = Math.exp(input)
|
||||
return eulerExpInputs / sumOfEulerExpOfAllInputs
|
||||
})
|
||||
}
|
||||
|
||||
export { Softmax }
|
12
Maths/test/Softmax.test.js
Normal file
12
Maths/test/Softmax.test.js
Normal file
@ -0,0 +1,12 @@
|
||||
import { Softmax } from '../Softmax'
|
||||
|
||||
describe('Softmax', () => {
|
||||
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])
|
||||
})
|
||||
|
||||
it('should return values which sum to the value of 1', () => {
|
||||
expect(Softmax([1, 2, 3, 4]).reduce((a, b) => a + b, 0)).toEqual(1)
|
||||
})
|
||||
})
|
Reference in New Issue
Block a user