tanh is a nonlinear activation function that maps every real-valued input into [-1, 1]. In a neural network, placing it between linear layers lets the model represent functions that a stack of linear operations cannot. Around zero, tanh is approximately linear; for larger positive or negative inputs, it approaches its range limits. section 2.2.3 section 6.1
Use tanh when a bounded, historically common nonlinearity fits the model:
- Insert one activation between adjacent linear layers rather than after the final output layer. section 2.2.3
- Use nn.Tanh() in PyTorch; a two-linear-layer network therefore needs one intermediate activation. section 2.2.3
- Account for saturation: tanh and sigmoid can produce vanishing gradients, although bounded outputs are useful for LSTM gating. section 6.1 section 6.6.2
A tanh hidden layer in PyTorch
model = nn.Sequential( nn.Linear(1, 10), nn.Tanh(), nn.Linear(10, 1), ) section 2.2.3
activation_input = np.linspace(-2, 2, num=200)
tanh_activation = np.tanh(activation_input)
sigmoid_activation = np.exp(activation_input)/(np.exp(activation_input)+1)
sns.lineplot(x=activation_input, y=activation_input,
color=’black’, label="linear")
sns.lineplot(x=activation_input, y=tanh_activation,
color=’red’, label="tanh(x)")
ax = sns.lineplot(x=activation_input, y=sigmoid_activation,
color=’blue’, label="$\sigma(x)$)")
ax.set_xlabel(’Input value x’)
ax.set_ylabel(’Activation’)
[13]: Text(0, 0.5, 'Activation')
Compare tanh with a linear function and sigmoid by plotting their activation values across inputs from -2 to 2. section 2.2.3



