Skip to content

tanh activation function is added #8684

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 10 commits into from
41 changes: 41 additions & 0 deletions maths/tanh.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""
This script demonstrates the implementation of the tangent hyperbolic
or tanh function.

The function takes a vector of K real numbers as input and
then (e^x - e^(-x))/(e^x + e^(-x)). After through tanh, the
element of the vector mostly -1 between 1.

Script inspired from its corresponding Wikipedia article
https://en.wikipedia.org/wiki/Activation_function
"""
import numpy as np


def tangent_hyperbolic(vector: np.array) -> np.array:
"""
Implements the tanh function

Parameters:
vector: np.array

Returns:
tanh (np.array): The input numpy array after applying
tanh.

mathematically (e^x - e^(-x))/(e^x + e^(-x)) can be written as (2/(1+e^(-2x))-1

Examples:
>>> tangent_hyperbolic(np.array([1,5,6,-0.67]))
array([ 0.76159416, 0.9999092 , 0.99998771, -0.58497988])

"""

exp_vector = np.exp(-2 * vector)
return (2 / (1 + exp_vector)) - 1


if __name__ == "__main__":
import doctest

doctest.testmod()