📜  Python中的 numpy.tanh()(1)

📅  最后修改于: 2023-12-03 14:46:36.702000             🧑  作者: Mango

numpy.tanh()

The numpy.tanh() function is a mathematical function in Python's NumPy library that calculates the hyperbolic tangent of an input array. It is an element-wise function, meaning it operates on each element of the array individually.

Syntax
numpy.tanh(x)
Parameters
  • x: An array-like object. Input values for which hyperbolic tangent has to be calculated.
Return Value

The numpy.tanh() function returns an array with the same shape as the input array, containing the hyperbolic tangent values of the corresponding elements.

Example
import numpy as np

# Input array
arr = np.array([-1, 0, 1])

# Calculate hyperbolic tangent
result = np.tanh(arr)

print(result)

Output:

[-0.76159416  0.          0.76159416]
Mathematical Explanation

The hyperbolic tangent function tanh(x) is defined as:

tanh(x) = (e^(2x) - 1) / (e^(2x) + 1)

In the numpy.tanh() implementation, the numpy.exp() function is used to calculate the exponential value e^x for each element of the input array. Using these values, the hyperbolic tangent is calculated using the formula mentioned above.

Usage

The numpy.tanh() function is commonly used in various scientific and mathematical applications, particularly in machine learning and neural networks. It is used to introduce non-linearity into the network and to normalize values within a range of -1 to 1.

Here are a few common use cases:

  1. Activation function in neural networks:

    import numpy as np
    
    def sigmoid(x):
        return 1 / (1 + np.exp(-x))
    
    def feedforward(inputs, weights):
        hidden_layer = np.dot(inputs, weights)
        outputs = np.tanh(hidden_layer)
        return outputs
    
    inputs = np.array([0.5, -0.3, 0.2])
    weights = np.array([[0.7, 0.2, -0.6],
                        [0.3, -0.1, 0.5],
                        [-0.4, 0.9, 0.1]])
    output = feedforward(inputs, weights)
    
  2. Data normalization:

    import numpy as np
    
    def normalize_data(data):
        data_mean = np.mean(data)
        data_std = np.std(data)
        normalized_data = (data - data_mean) / data_std
        return normalized_data
    
    data = np.array([10, 20, 30, 40, 50])
    normalized_data = np.tanh(data)
    
Conclusion

The numpy.tanh() function is a useful tool for calculating the hyperbolic tangent of an array. It can be used in various mathematical and scientific applications, particularly in machine learning and neural networks. This function provides a simple yet efficient way to introduce non-linearity and normalize data within a specific range.