Skip to content

Commit 9c9640c

Browse files
Added Softmax to Maths folder (TheAlgorithms#516)
1 parent 2190b92 commit 9c9640c

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed

DIRECTORY.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,7 @@
119119
* [PrimeCheck](https://github.com/TheAlgorithms/Javascript/blob/master/Maths/PrimeCheck.js)
120120
* [ReversePolishNotation](https://github.com/TheAlgorithms/Javascript/blob/master/Maths/ReversePolishNotation.js)
121121
* [SieveOfEratosthenes](https://github.com/TheAlgorithms/Javascript/blob/master/Maths/SieveOfEratosthenes.js)
122+
* [Softmax](https://github.com/TheAlgorithms/Javascript/blob/master/Maths/Softmax.js)
122123
* test
123124
* [Abs](https://github.com/TheAlgorithms/Javascript/blob/master/Maths/test/Abs.test.js)
124125
* [Area](https://github.com/TheAlgorithms/Javascript/blob/master/Maths/test/Area.test.js)
@@ -145,6 +146,7 @@
145146
* [PrimeCheck](https://github.com/TheAlgorithms/Javascript/blob/master/Maths/test/PrimeCheck.test.js)
146147
* [ReversePolishNotation](https://github.com/TheAlgorithms/Javascript/blob/master/Maths/test/ReversePolishNotation.test.js)
147148
* [SieveOfEratosthenes](https://github.com/TheAlgorithms/Javascript/blob/master/Maths/test/SieveOfEratosthenes.test.js)
149+
* [Softmax](https://github.com/TheAlgorithms/Javascript/blob/master/Maths/test/Softmax.test.js)
148150

149151
## Navigation
150152
* [Haversine](https://github.com/TheAlgorithms/Javascript/blob/master/Navigation/Haversine.js)

Maths/Softmax.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// Wikipedia: https://en.wikipedia.org/wiki/Softmax_function
2+
3+
const Softmax = (inputs) => {
4+
const eulerExpOfAllInputs = inputs.map(input => Math.exp(input))
5+
const sumOfEulerExpOfAllInputs = eulerExpOfAllInputs.reduce((a, b) => a + b)
6+
7+
return inputs.map((input) => {
8+
const eulerExpInputs = Math.exp(input)
9+
return eulerExpInputs / sumOfEulerExpOfAllInputs
10+
})
11+
}
12+
13+
export { Softmax }

Maths/test/Softmax.test.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { Softmax } from '../Softmax'
2+
3+
describe('Softmax', () => {
4+
it('should return equal distribution of 1 for equal input values', () => {
5+
expect(Softmax([1, 1])).toEqual([0.5, 0.5])
6+
expect(Softmax([1, 1, 1, 1])).toEqual([0.25, 0.25, 0.25, 0.25])
7+
})
8+
9+
it('should return values which sum to the value of 1', () => {
10+
expect(Softmax([1, 2, 3, 4]).reduce((a, b) => a + b, 0)).toEqual(1)
11+
})
12+
})

0 commit comments

Comments
 (0)