liveBook · Manning

Tanh

As explained in Inside Deep Learning: Math, Algorithms, Models

A nonlinear activation function that maps real-valued inputs into the interval [-1,1].

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

How Inside Deep Learning: Math, Algorithms, Models covers it

How deep it goes
Defines the output range, explains nonlinear placement and saturation, and demonstrates PyTorch usage without deriving tanh internals.
Examples
Demonstrates activation curves, a two-layer PyTorch network, LSTM gates, and an additive-attention replacement exercise.
What it assumes
Assumes familiarity with linear layers and introduces activation functions before comparing tanh with sigmoid.
What you can do after
Apply it via PyTorch's nn.Tanh in hidden layers and recognize saturation-related gradient risks.
How it connects
Connects tanh with activation functions, sigmoid, vanishing gradients, LSTM, and gating mechanisms.

Also explained in

Compare how 4 books explain tanh →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Inside Deep Learning: Math, Algorithms, Models. The section links point to the parts of the book it draws on.