Pros and Cons of Tanh Activation Function
The hyperbolic tangent (tanh) activation function maps inputs smoothly to (-1, 1), offering zero-centered outputs and a steeper maximum gradient of 1.0 compared to sigmoid's 0.25. While zero-centering improves optimization dynamics, tanh still saturates for large magnitude inputs, causing vanishing gradients that make ReLU-family activations preferable in deep feedforward networks.
Study Card: Pros and Cons of Tanh Activation Function
Direct Answer
The hyperbolic tangent () activation function is a smooth, S-shaped non-linearity defined as a rescaled and shifted sigmoid:
Pros:
- Zero-Centered Outputs: Maps inputs into around zero, avoiding the all-positive output bias of sigmoid that causes zig-zag weight updates in subsequent layers.
- Steeper Gradient Near Zero: Maximum derivative is at (four times larger than sigmoid’s ), providing stronger gradient flow in the active regime.
- Smooth & Bounded: Continuously differentiable everywhere and useful in gated recurrent units (LSTM/GRU) where bounded candidate states in help stabilize recurrent state updates.
Cons:
- Vanishing Gradients on Saturation: As grows large, and , starving earlier layers of gradients in deep networks.
- Higher Compute Cost: Exponential evaluations are more expensive than piecewise-linear activations like ReLU.
Key Terms
- Vanishing Gradient: Exponential shrinkage of backpropagated gradients when activation derivatives are strictly less than 1 across many layers or steps.
- Zero-Centered: Outputs distributed symmetrically around zero, allowing gradients wrt downstream weights to take balanced positive and negative signs.
- Saturation: Operating in flat tail regions () where outputs approach and local derivatives vanish toward zero.
- Activation Function: Non-linear mapping applied to pre-activations so multi-layer networks can learn non-linear functions.
Example
Consider hidden units using . Near zero (), and its derivative is , letting gradients flow cleanly. For large pre-activations ( or ), saturates near and its derivative collapses to , effectively halting learning for weights feeding that saturated unit—justifying Xavier/Glorot initialization to keep pre-activations in the linear regime at startup.
Code Implementation
import numpy as np
import matplotlib.pyplot as plt
def tanh(x):
return np.tanh(x)
def tanh_derivative(x):
return 1.0 - np.tanh(x) ** 2
x = np.linspace(-10, 10, 100)
y_tanh = tanh(x)
y_tanh_derivative = tanh_derivative(x)
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.plot(x, y_tanh)
plt.title('Tanh Activation Function')
plt.xlabel('Input')
plt.ylabel('Output')
plt.grid(True)
plt.subplot(1, 2, 2)
plt.plot(x, y_tanh_derivative)
plt.title('Tanh Derivative')
plt.xlabel('Input')
plt.ylabel('Derivative')
plt.grid(True)
plt.tight_layout()
plt.show()
# Illustrate active vs. saturated derivatives
for val in [10, -10, 0.5]:
print(f"tanh({val}) = {tanh(val):.6f}, derivative = {tanh_derivative(val):.6e}")
Related Concepts
- Sigmoid Activation: Maps inputs to with max derivative ; typically reserved for binary classification output probabilities or gating coefficients, whereas is preferred over sigmoid in hidden layers.
- ReLU / GELU Activations: Eliminate positive-side saturation ( for ), making them standard defaults in deep MLPs, CNNs, and Transformers.
- Xavier / Glorot Initialization: Balances forward activation variance and backward gradient variance specifically around linear/ activations near zero.
- Recurrent Gating (LSTM / GRU): Uses sigmoid for multiplicative gates in alongside for zero-centered candidate states in .