Skip to content
E
Educatum

Pros and Cons of Tanh Activation Function

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

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 (tanh⁡\tanh) activation function is a smooth, S-shaped non-linearity defined as a rescaled and shifted sigmoid:

tanh⁡(x)=ex−e−xex+e−x=2σ(2x)−1,ddxtanh⁡(x)=1−tanh⁡2(x)∈(0,1]\tanh(x) = \frac{e^x - e^{-x}}{e^x + e^{-x}} = 2\sigma(2x) - 1, \qquad \frac{d}{dx}\tanh(x) = 1 - \tanh^2(x) \in (0, 1]

Pros:

  • Zero-Centered Outputs: Maps inputs into (−1,1)(-1, 1) 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 1.01.0 at x=0x=0 (four times larger than sigmoid’s 0.250.25), 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 (−1,1)(-1, 1) help stabilize recurrent state updates.

Cons:

  • Vanishing Gradients on Saturation: As ∣x∣|x| grows large, tanh⁡(x)→±1\tanh(x) \to \pm 1 and 1−tanh⁡2(x)→01 - \tanh^2(x) \to 0, 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 (∣x∣≫1|x| \gg 1) where outputs approach ±1\pm 1 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 tanh⁡\tanh. Near zero (x=0.5x = 0.5), tanh⁡(0.5)≈0.462\tanh(0.5) \approx 0.462 and its derivative is 1−0.4622≈0.7861 - 0.462^2 \approx 0.786, letting gradients flow cleanly. For large pre-activations (x=10x = 10 or x=−10x = -10), tanh⁡(x)\tanh(x) saturates near ±1\pm 1 and its derivative collapses to 8.24×10−98.24 \times 10^{-9}, 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}")
  • Sigmoid Activation: Maps inputs to (0,1)(0, 1) with max derivative 0.250.25; typically reserved for binary classification output probabilities or gating coefficients, whereas tanh⁡\tanh is preferred over sigmoid in hidden layers.
  • ReLU / GELU Activations: Eliminate positive-side saturation (ReLU′(x)=1\text{ReLU}'(x)=1 for x>0x>0), making them standard defaults in deep MLPs, CNNs, and Transformers.
  • Xavier / Glorot Initialization: Balances forward activation variance and backward gradient variance specifically around linear/tanh⁡\tanh activations near zero.
  • Recurrent Gating (LSTM / GRU): Uses sigmoid for multiplicative gates in (0,1)(0, 1) alongside tanh⁡\tanh for zero-centered candidate states in (−1,1)(-1, 1).
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.