Skip to content

Commit 1809c2c

Browse files
TMGA-WAYpre-commit-ci[bot]cclauss
authored andcommitted
The tanh activation function is added (TheAlgorithms#8689)
* tanh function been added * tanh function been added * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * tanh function is added * tanh function is added * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * tanh function added * tanh function added * tanh function is added * Apply suggestions from code review --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <[email protected]>
1 parent 3021eda commit 1809c2c

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

maths/tanh.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
This script demonstrates the implementation of the tangent hyperbolic
3+
or tanh function.
4+
5+
The function takes a vector of K real numbers as input and
6+
then (e^x - e^(-x))/(e^x + e^(-x)). After through tanh, the
7+
element of the vector mostly -1 between 1.
8+
9+
Script inspired from its corresponding Wikipedia article
10+
https://en.wikipedia.org/wiki/Activation_function
11+
"""
12+
import numpy as np
13+
14+
15+
def tangent_hyperbolic(vector: np.array) -> np.array:
16+
"""
17+
Implements the tanh function
18+
19+
Parameters:
20+
vector: np.array
21+
22+
Returns:
23+
tanh (np.array): The input numpy array after applying tanh.
24+
25+
mathematically (e^x - e^(-x))/(e^x + e^(-x)) can be written as (2/(1+e^(-2x))-1
26+
27+
Examples:
28+
>>> tangent_hyperbolic(np.array([1,5,6,-0.67]))
29+
array([ 0.76159416, 0.9999092 , 0.99998771, -0.58497988])
30+
31+
>>> tangent_hyperbolic(np.array([8,10,2,-0.98,13]))
32+
array([ 0.99999977, 1. , 0.96402758, -0.7530659 , 1. ])
33+
34+
"""
35+
36+
return (2 / (1 + np.exp(-2 * vector))) - 1
37+
38+
39+
if __name__ == "__main__":
40+
import doctest
41+
42+
doctest.testmod()

0 commit comments

Comments
 (0)