The hyperbolic tangent squashes its input into (−1, 1). It is the sigmoid rescaled and centred, tanh(z) = 2σ(2z) − 1, so it is zero-centred with slope 1 at the origin, four times the sigmoid's, which made it the preferred hidden activation before ReLU and keeps it central in recurrent networks, where its bounded output keeps the state from blowing up. Like the sigmoid it saturates: for large |z| its slope vanishes and units stop learning. This page covers its definition and properties, a stable implementation, its relation to the sigmoid, LeCun's scaled tanh, Xavier initialisation, saturation, and its roles in RNN cells and as a bounded output layer. In the exercises you implement tanh and check its identities, then measure how the weight scale controls saturation and trainability in an eight-layer tanh network.
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.
A balanced squash
Tanh is the sigmoid’s balanced sibling: it squashes any input into the range from −1 to +1 instead of 0 to 1, so 0 maps to 0. Balanced outputs and a steeper middle made it the go-to hidden activation of the 1990s and 2000s. Its bounded output still makes it the standard choice inside recurrent cells.
Activation lab: the curve, its slope, and what a network learns with it
tanh: training accuracy after 300 steps 0.993
Compare activations at the same number of steps. Smooth, non-saturating units usually fit the spirals fastest. Sigmoid and the hard-threshold units learn slowly or need surrogate gradients. Gated and maxout units use twice as many hidden pre-activations. Learning rates are fixed per activation and not tuned, so treat small differences as noise (press "new data and weights").
Why engineers care
Tanh appears in LSTM and GRU cells for telemetry and trajectory models, in policy networks that output bounded actions (a steering angle or thrust command scaled to ±1), and in physics-informed networks that need smooth derivatives. Knowing when it saturates, and how to scale weights to avoid it, keeps these models trainable.
📝 Quick check (Level 0)
0/3 answered
1. tanh outputs lie in…
2. tanh(0) =
3. A common modern use of tanh is…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.
Properties by hand
Definition: tanh z = (e^z − e^(−z))/(e^z + e^(−z)).
Stable form: sign(z)(1 − e^(−2|z|))/(1 + e^(−2|z|)), which handles z = ±10⁴.
Odd and bounded: tanh(−z) = −tanh z, with |tanh z| < 1.
Derivative: 1 − tanh² z, equal to 1 at 0. At an output of 0.5 the slope is 0.75; at 0.99 it is 0.0199 (saturated).
Relation to the sigmoid: tanh z = 2σ(2z) − 1.
Saturation: for |z| > 2.5 the slope is below 0.027. Such units barely pass gradient.
LeCun’s scaled tanh: f(z) = 1.7159 tanh(2z/3), chosen so that f(±1) = ±1. Its slope at 0 is 1.14. For unit-normal inputs it keeps a mean square of about 0.75, against 0.39 for plain tanh.
Xavier initialisation (E0-7) was derived for tanh: it keeps activations in the near-linear region at the start.
📝 Quick check (Level 1)
0/3 answered
1. tanh′ at output 0.5?
2. tanh(z) equals…
3. LeCun's scaled tanh maps 1 to…
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.
Where tanh is used
Exercise 1.
The stable implementation matched np.tanh and handled ±10⁴.
The identities tanh(−z) = −tanh z and tanh z = 2σ(2z) − 1 held to machine precision.
LeCun’s scaled tanh gave f(1) = 1.0000, and a mean square of 0.751 on unit-normal inputs against 0.395 for plain tanh. It is not exactly unit variance, a detail sometimes misremembered.
Recurrent cells. An LSTM computes a candidate state tanh(W[h, x]) and outputs h = o ⊙ tanh(c). The bounds keep the hidden state from growing without limit over thousands of steps, which a ReLU would not guarantee.
Bounded outputs. Actor networks in continuous control end in tanh, rescaled to the actuator range, so commands can never exceed physical limits. (SAC adds a log-determinant correction for this squashing.)
torch.tanh(z); nn.Tanh()action = max_thrust * torch.tanh(policy_net(state)) # always within ±max_thrust
🐍 Exercise 1: tanh and its relatives
Implement a stable tanh and its derivative, check that it is odd and that tanh z = 2σ(2z) − 1, and examine LeCun's scaled tanh and the saturated fraction of units.
📝 Quick check (Level 2)
0/3 answered
1. Why use tanh for an actor network's output?
2. The LSTM hidden state uses tanh because…
3. Plain tanh's mean square output for unit-normal input is about…
Level 3: Advanced
★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.
Theory
Zero-centring and conditioning. A layer fed zero-mean inputs has a better-conditioned Hessian for its weights than one fed all-positive inputs (LeCun et al., 1991, 1998). With tanh the outputs are centred near initialisation, so the next layer sees roughly zero-mean inputs.
Signal propagation. For zero-bias tanh networks, mean-field theory gives a critical (edge-of-chaos) weight variance σ_w² = 1, matching Xavier.
Below it, activations shrink toward 0, gradually at the critical point itself.
Above it, the network becomes chaotic and pre-activations grow until units saturate.
Exercise 2 maps this trade-off in a finite network.
Saturation dynamics. Once |z| is large, tanh′ ≈ 4e^(−2|z|). The unit’s incoming gradient is tiny and it can stay stuck for many steps. Normalisation layers keep z in range by construction.
Interview questions.
Tanh or ReLU for a deep feedforward network? Usually ReLU-family activations: they do not saturate on the positive side and are cheaper. Tanh remains common in RNN cells, bounded outputs and smooth physics models.
How do you detect saturation? Log the fraction of units with |z| above about 2.5, or histograms of activations piling up at ±1.
📝 Quick check (Level 3)
0/3 answered
1. For large |z|, tanh′ behaves like…
2. The critical weight variance for zero-bias tanh is…
3. Zero-centred inputs help because…
Level 4: Expert
★★★★★ Expert⏱ 25 minResearchers: original papers and open problems.
How much saturation can training tolerate?
History.
Tanh networks were standard in the 1990s (LeCun et al., 1989, 1998).
S. Hochreiter and J. Schmidhuber (1997) used tanh in LSTM cells.
X. Glorot and Y. Bengio (2010) derived Xavier initialisation for tanh.
B. Poole et al. (2016) mapped the order–chaos transition of tanh networks.
After 2012, ReLU replaced tanh in most feedforward vision models.
Exercise 2. An 8-layer tanh network (width 32) on spirals, with weights of std gain/√fan-in, trained by full-batch gradient descent at learning rate 0.1 for 200 steps.
weight gain
saturated units at start (size of z above 2.5)
final loss per seed
0.5
0.000
0.880, 1.011
1
0.002
0.011, 0.008
2
0.103
0.005, 0.006
4
0.471
0.007, 0.013
8
0.730
0.342, 1.136
Too-small weights left the network unable to learn in 200 steps. The signal faded through 8 layers, and the loss stayed at 0.88–1.01, near ln 3 = 1.10.
Gains from 1 to 4 all trained well, even with nearly half the units starting saturated at gain 4. Training pulled most of them back into range.
At gain 8, 73% of units started saturated, and training stalled (0.34 and 1.14): most units passed almost no gradient.
Tanh tolerates a fairly wide range of scales around the critical value, with failure at both extremes. This window narrows as depth grows.
🐍 Exercise 2 (research): saturation and trainability
Train eight-layer tanh networks with weight gains from 0.5 to 8, measuring the initial fraction of saturated units and the final training loss.
Tanh in AI, robotics and aerospace
Bounded control outputs: policy networks for drones and manipulators end in tanh, scaled to actuator limits.
Recurrent state estimation: LSTM- and GRU-based models of telemetry and sensor sequences.
Physics-informed networks: smooth tanh activations give the higher derivatives that PDE residual losses need (J-section topics).
References
Y. LeCun, L. Bottou, G. Orr, K.-R. Müller (1998). “Efficient BackProp.” In Neural Networks: Tricks of the Trade.
X. Glorot, Y. Bengio (2010). “Understanding the difficulty of training deep feedforward neural networks.” Proc. AISTATS.
S. Hochreiter, J. Schmidhuber (1997). “Long short-term memory.” Neural Computation 9(8).
B. Poole, S. Lahiri, M. Raghu, J. Sohl-Dickstein, S. Ganguli (2016). “Exponential expressivity in deep neural networks through transient chaos.” Advances in NeurIPS 29.
Explain why gain 8 stalled training while gain 4 did not.
At gain 4, about half the units started with |z| > 2.5. The rest still passed gradient, and their updates, plus bias changes, pulled saturated units back into the sensitive region. At gain 8, about three quarters started saturated, and the pre-activations were much larger, so slopes of order e^(−2|z|) were tiny for most units in every layer. The backpropagated signal through 8 layers was multiplied by many near-zero factors, so the early layers barely changed and training stalled. ∎
Problem 16Level 3
Explain why an LSTM uses tanh rather than ReLU for its candidate and output nonlinearities.
The cell state is updated additively over many steps (c ← f ⊙ c + i ⊙ g). With a bounded candidate g = tanh(·) ∈ (−1, 1), each step adds a bounded amount, and the output h = o ⊙ tanh(c) is bounded too, so the recurrent dynamics stay stable over long sequences. An unbounded ReLU could let the state and hidden activations grow without limit through the recurrent loop, causing explosions. ∎
Problem 17Level 3
Design the output layer of a policy network commanding a gimbal angle within ±30°.
End the network with a linear layer followed by tanh and scale it by 30°, so commands are always within limits. Initialise the last layer with small weights, so the initial commands sit near 0 in tanh’s linear region. Penalise large pre-tanh values (or use a small action regulariser), to avoid saturation, which would stop the policy from learning to back off the limit. For stochastic policies with a squashed Gaussian, include the tanh log-Jacobian correction in the log-probability (as in SAC). ∎
Level 4
Problem 18Level 4
Saturated fraction at gain 2?
0.103.
Problem 19Level 4
Worst final loss at gain 8?
1.136.
Problem 20Level 4
Final loss at gain 1, seed 1?
0.008.
Coding practice
🐍 Code 1 (Level 1): stable tanh
sign(z)(1 − e^(−2|z|))/(1 + e^(−2|z|)).
🐍 Code 2 (Level 0): derivative from the output
1 − t².
🐍 Code 3 (Level 0): tanh via the sigmoid
2σ(2z) − 1.
🐍 Code 4 (Level 0): saturated fraction
Share of |z| above a threshold.
🐍 Code 5 (Level 0): LeCun's scaled tanh
1.7159 tanh(2z/3).
Topic test
A timed test drawn at random from this topic's question bank. Each attempt gets new questions. For a longer test across the whole chapter, see the chapter test, or mix topics in the question bag.
Tanh: topic test
10 questions, drawn at random from a bank of 21. Every attempt is different.
⏱ Time limit: 15 minutes. The test submits itself when time runs out.
Levels covered: 0, 1, 2, 3, 4. No hints or solutions until you submit.