Neural network formulas: a cheat sheet · Activation functions

Tanh: the hyperbolic tangent

An S-shaped function centred at zero. We take it apart bone by bone: which exponentials it is built from, why it is a “stretched sigmoid”, where the derivative 1 − tanh² comes from, why a neuron wants zero-centred outputs, and what tanh does to the gradient in deep and recurrent networks.

Javharbek Abdulatipov · 35 min read
$$\tanh(x)=\frac{e^{x}-e^{-x}}{e^{x}+e^{-x}}$$

Why we need it

The sigmoid turns a number into a share between 0 and 1. Inside a network, though, we often need not a share but a signed signal: “above normal” or “below normal”, “amplify” or “damp”. The hyperbolic tangent is the same smooth S-curve, but with outputs in $(-1,\,1)$ and its centre at zero.

Where it appears:

  • recurrent networks — in a plain RNN $h_t=\tanh(Wh_{t-1}+Ux_t+b)$; in LSTM and GRU, tanh produces the candidate for the memory, and in LSTM it also bounds the cell’s output;
  • hidden layers of classic networks — before the ReLU era tanh was the standard, and it is still good in small networks and physics-informed models (PINN) where smoothness matters;
  • a generator’s output — if images are normalized to $[-1,\,1]$, the last layer of a GAN generator (DCGAN, for example) uses tanh;
  • bounding actions and logits — in reinforcement learning (SAC) actions are squashed into $(-1,\,1)$ with tanh, and Gemma 2 “soft-caps” its logits: $c\cdot\tanh(z/c)$;
  • inside other activations — the popular approximation of GELU is written through tanh.
The essentials in a minute

$\tanh$ squeezes the whole real line into $(-1,\,1)$, passes through the origin and is odd: $\tanh(-x)=-\tanh x$. It is a stretched sigmoid: $\tanh x=2\sigma(2x)-1$. Its derivative $1-\tanh^2x$ never exceeds 1 — four times the sigmoid’s maximum — but on the tails tanh saturates just the same, and the gradient fades.

Intuition: a sigmoid standing on zero

Picture a volume knob with a sign: zero is silence, turning right makes it louder, turning left makes it louder in antiphase. As long as you stay near zero, the output faithfully follows the input: $\tanh x\approx x$. Further out the knob gets stiffer: the output runs into $\pm1$ and stops growing. This is saturation.

Drag the point. The orange line is the tangent; its slope is the derivative. The grey dashed curve is the sigmoid: the same shape, but shifted up, half as tall and four times flatter.

Figure 1. tanh, its tangent and its derivative (below). Drag the blue point, or use the arrow keys when it has focus. The maximum of the derivative is $1$ at $x=0$; for the sigmoid it is $0.25$. At $x=1$: $\tanh 1=0.7616$, $\tanh' 1=0.4200$.
What to notice

At $x=2$ tanh is already $0.964$, while the derivative is only $0.071$, 14 times smaller than at the centre. For $|x|>2.99$ the derivative drops below $0.01$: the input keeps growing while the output barely moves.

The formula, bone by bone

The formula holds two exponentials: the growing $e^{x}$ and the decaying $e^{-x}$. The numerator is their difference, the denominator their sum. Halves of these expressions have names of their own — the hyperbolic sine and cosine:

$$\begin{aligned}\sinh x&=\frac{e^{x}-e^{-x}}{2}\\[4pt]\cosh x&=\frac{e^{x}+e^{-x}}{2}\\[4pt]\tanh x&=\frac{\sinh x}{\cosh x}\end{aligned}$$
$e^{x}-e^{-x}$
the difference is odd: it changes sign under $x\to-x$; for $x>0$ it is positive;
$e^{x}+e^{-x}$
the sum is always positive and at least 2 — the denominator never vanishes;
$|\sinh x|<\cosh x$
the difference is always smaller in absolute value than the sum, hence $|\tanh x|<1$;
$x\to\pm\infty$
one of the exponentials becomes negligible, and the fraction tends to $\pm1$.

Multiplying the numerator and the denominator by $e^{x}$ or by $e^{-x}$ gives forms convenient for computation, and the last form links tanh to the sigmoid:

$$\begin{aligned}\tanh x&=\frac{e^{2x}-1}{e^{2x}+1}=\frac{1-e^{-2x}}{1+e^{-2x}}\\[4pt]&=2\sigma(2x)-1\end{aligned}$$
Figure 2. Left: $\sinh$ and $\cosh$ are the half-difference and the half-sum of the exponentials; tanh is their ratio. At $x_0=1$: $\sinh 1=1.175$, $\cosh 1=1.543$, the ratio is $0.7616=\tanh 1$. Right: press “Play” — the sigmoid turns into tanh in three steps: squeeze it horizontally by 2, stretch it vertically by 2, lower it by 1.
$x$$\tanh x$$\tanh' x$$\sigma(x)$
−3−0.99510.00990.0474
−2−0.96400.07070.1192
−1−0.76160.42000.2689
−0.5−0.46210.78640.3775
00.00001.00000.5000
0.50.46210.78640.6225
10.76160.42000.7311
20.96400.07070.8808
30.99510.00990.9526

The table shows the oddness, $\tanh(-x)=-\tanh x$, while the derivative is an even function. The sigmoid is listed for comparison: its values are symmetric not about zero but about $0.5$.

Properties and shape

  • Domain: all real numbers; range: the open interval $(-1,\,1)$ — the values $\pm1$ are never reached.
  • Oddness: $\tanh(-x)=-\tanh x$; the graph is symmetric about the origin, $\tanh 0=0$.
  • Monotonicity: strictly increasing, since $\tanh' x=1-\tanh^2x>0$ for every $x$.
  • Asymptotes: $\lim_{x\to\pm\infty}\tanh x=\pm1$.
  • Inflection point: a single one, at $x=0$; the function is convex for $x<0$ and concave for $x>0$.
  • Lipschitz with constant 1: $|\tanh a-\tanh b|\le|a-b|$; in particular $|\tanh x|\le|x|$, with equality only at $x=0$.
  • Almost the identity near zero: $\tanh x=x-\tfrac{x^3}{3}+\dots$ — with small weights a tanh network behaves almost linearly.
Why tanh x = 2σ(2x) − 1

Substitute the definition of the sigmoid $\sigma(u)=1/(1+e^{-u})$ with $u=2x$:

$$2\sigma(2x)-1=\frac{2}{1+e^{-2x}}-\frac{1+e^{-2x}}{1+e^{-2x}}=\frac{1-e^{-2x}}{1+e^{-2x}}=\frac{e^{x}-e^{-x}}{e^{x}+e^{-x}}=\tanh x$$

In the second-to-last step the numerator and the denominator are multiplied by $e^{x}$. Conversely, $\sigma(x)=\tfrac12\bigl(1+\tanh\tfrac x2\bigr)$. So a network with tanh hidden units can be rewritten as one with sigmoid hidden units of the same expressive power — only the weight scales and biases change. The difference lies in how training goes (see the section on centring).

The inverse function and the addition formula

Solve $y=\tanh x$ for $x$: from $y=\frac{e^{2x}-1}{e^{2x}+1}$ we get $e^{2x}=\frac{1+y}{1-y}$, hence

$$\operatorname{artanh}y=\frac12\ln\frac{1+y}{1-y},\qquad -1<y<1$$

For example, $\operatorname{artanh}0.5\approx0.549$. Another useful identity is the addition formula:

$$\tanh(a+b)=\frac{\tanh a+\tanh b}{1+\tanh a\,\tanh b}$$

This is exactly the relativistic addition of velocities (as fractions of the speed of light): $0.5c$ and $0.5c$ give not $c$ but $\frac{0.5+0.5}{1+0.25}c=0.8c$. In the “world of tanh” the sum of two numbers from $(-1,\,1)$ never leaves it.

A soft limiter: c · tanh(x / c)

Near zero the function $c\tanh(x/c)$ barely changes its input ($\approx x$), while large values are smoothly pressed towards $\pm c$. Unlike the hard cut $\operatorname{clip}(x,-c,c)$, it has no kinks, and its derivative never drops to zero abruptly. Gemma 2 bounds its attention logits ($c=50$) and final logits ($c=30$) this way, so that they do not blow up during training.

The derivative: tanh′ = 1 − tanh²

The key formula of the page. Let us derive it in three ways — each one is useful somewhere else.

Method 1. The quotient rule

Let $u=e^{x}-e^{-x}$ and $v=e^{x}+e^{-x}$. Then $u'=v$ and $v'=u$, and by the quotient rule:

$$\tanh' x=\frac{u'v-uv'}{v^{2}}=\frac{v^{2}-u^{2}}{v^{2}}=1-\Bigl(\frac{u}{v}\Bigr)^{2}=1-\tanh^{2}x$$
Method 2. Through the fundamental hyperbolic identity

For hyperbolic functions $\cosh^2x-\sinh^2x=1$ (check it by substituting the exponentials), $\sinh' x=\cosh x$ and $\cosh' x=\sinh x$. Then

$$\tanh' x=\frac{\cosh x\cdot\cosh x-\sinh x\cdot\sinh x}{\cosh^{2}x}=\frac{1}{\cosh^{2}x}=\operatorname{sech}^{2}x$$

Dividing the identity by $\cosh^2x$ gives $1-\tanh^2x=\operatorname{sech}^2x$ — the same formula in another notation. The $\operatorname{sech}^2$ form is useful in code for large $|x|$.

Method 3. Through the sigmoid

From $\tanh x=2\sigma(2x)-1$ by the chain rule:

$$\tanh' x=2\cdot\sigma'(2x)\cdot2=4\sigma(2x)\bigl(1-\sigma(2x)\bigr)$$

This shows at once why the maximum of the derivative is $4\cdot\tfrac14=1$ rather than $\tfrac14$ as for the sigmoid: twice the output range and a twice-compressed input scale give a factor of 4.

$$\tanh' x=1-\tanh^{2}x$$

In practice: on the forward pass the network has already computed $t=\tanh z$. On the backward pass the derivative costs a single multiplication $1-t^2$ — no new exponentials. That is why frameworks keep the output of tanh, not its input, for the backward pass.

The second derivative and the sharpest bends

Differentiating once more: $\tanh'' x=-2\tanh x\,(1-\tanh^2x)$. It vanishes only at $x=0$ (the inflection point), and its extrema are at $\tanh^2x=\tfrac13$, i.e. $x=\pm\operatorname{artanh}\tfrac{1}{\sqrt3}\approx\pm0.658$, with values $\mp\tfrac{4}{3\sqrt3}\approx\mp0.770$. At these points the slope is already $1-\tfrac13=\tfrac23$ and falls fastest: here the line $y\approx x$ gives way to the bend towards saturation.

The Taylor series around zero

$$\tanh x=x-\frac{x^{3}}{3}+\frac{2x^{5}}{15}-\frac{17x^{7}}{315}+\frac{62x^{9}}{2835}-\dots,\qquad |x|<\frac{\pi}{2}$$

The series converges only for $|x|<\pi/2\approx1.571$: the denominator $\cosh x$ vanishes at the complex points $x=\pm i\pi/2$, and the radius of convergence equals the distance to the nearest one. That is half the sigmoid’s radius ($\pi$), since tanh is squeezed horizontally by a factor of 2.

Figure 3. Taylor polynomials of orders 1–9 and the convergence band $|x|<\pi/2$. At $x=1$ the third-order approximation gives $0.6667$ instead of $0.7616$, and the ninth-order one gives $0.7679$. At $x=2$, outside the band, the polynomials diverge: order 3 gives $-0.667$, order 9 already $7.889$.

Zero-centring: why tanh trains better than the sigmoid

Consider a neuron of the next layer: $z=\sum_i w_ia_i+b$, where $a_i$ are the outputs of the previous layer. The gradient of the loss with respect to a weight is

$$\frac{\partial L}{\partial w_i}=\delta\cdot a_i,\qquad \delta=\frac{\partial L}{\partial z}$$

If all $a_i>0$ (sigmoid outputs), then on a single example all components of the gradient share one sign — the sign of $\delta$. An SGD step moves all the neuron’s weights either up or down. If reaching the optimum requires raising some weights and lowering others, the only way is to zigzag.

A second view is through the shape of the loss surface. For a linear neuron with the squared loss $\tfrac12(w^\top a-y)^2$ the Hessian is $\mathbb E[aa^\top]=\operatorname{Cov}(a)+\mu\mu^\top$, where $\mu$ is the mean input. A non-zero mean adds one large eigenvalue along $\mu$, and the “valley” stretches. For the inputs $\sigma(z)$ below the eigenvalues are $0.034$ and $0.530$ (condition number 15.5); for $\tanh(z)$ they are $0.340$ and $0.415$ (1.22).

Figure 4. We train the two weights $w=(w_1,\,w_2)$ of a linear neuron on 100 examples; the inputs are $\sigma(z)$ on the left and $\tanh(z)$ on the right, for the same random $z$. SGD with step $0.5$ starts at $(-1,\,1)$ and heads for $w^*=(1,\,-1)$. On the left every step points “up-right” or “down-left” (the teal quadrants), and the path saws across the elongated valley; on the right the path is noisy too (SGD takes one example at a time), but it heads for the optimum without the systematic sawing. After 50 steps the distance to the optimum is $1.252$ versus $0.000$; an accuracy of $0.1$ takes 194 steps versus 21.
Takeaway

Zero-centred activations make the next layer’s loss surface “rounder”, and gradient descent heads for the minimum more directly. This is one reason tanh in hidden layers trains faster than the sigmoid (LeCun et al., “Efficient BackProp”, 1998). The same idea underlies input normalization and BatchNorm.

Tanh on the plane: folds, ridges and hills

A neuron with two inputs computes $\tanh(w_1x_1+w_2x_2+b)$. On the plane this is a fold: the surface goes from $-1$ to $+1$ across the line $w^\top x+b=0$ and stays constant along it. The sum of two opposite folds gives a ridge, and four folds plus one more tanh at the output give a hill that differs from $-1$ only inside a square.

Figure 5. A small tanh network. “1 neuron” is $\tanh(k(0.8x_1+0.6x_2))$; “2 neurons” is $\tanh(k(x_1+1))-\tanh(k(x_1-1))-1$; “4 + output” is the sum $s$ of four such folds along $x_1$ and $x_2$, followed by $\tanh(2(s-3))$. At $k=2$ the top of the hill is $f(0,\,0)=0.937$, and far away $f=-1.000$. The dashed lines are where the input of each hidden neuron is zero.

This is how the universal approximation theorem works (Cybenko, 1989; Hornik, 1991): a network with one hidden layer of sufficiently many tanh neurons approximates any continuous function on a closed bounded set to any accuracy. Hills are made of folds, and any landscape can be made of hills. Our hill uses a second tanh at the output for clarity, but the theorem needs only one hidden layer with a linear output. It says such weights exist, but not how many neurons are needed or whether training will find them.

Tanh in training: activations through layers and curve fitting

What happens to the signal in a deep network

Let the weights of each layer be random with variance $g^2/n$, where $n$ is the number of inputs of a neuron. If $g$ is small, the signal fades from layer to layer and tanh acts almost linearly. If $g$ is large, the neurons’ inputs are large and tanh goes into saturation: outputs stick to $\pm1$ and the derivatives are almost zero.

Figure 6. A random network of 10 layers of 100 neurons with inputs $N(0,1)$; each layer shows a histogram of 2000 activations (20 examples × 100 neurons), the orange point is the mean. tanh with $g=1$: the mean of the last layer is $0.013$, and the spread gradually shrinks to $0.225$; with $g=0.5$ the signal fades: the spread drops to $0.001$; with $g=3$ almost half the neurons are saturated ($48\%$ of values with $|a|>0.95$). With $g=5/3$ the spread stays around $0.65$, with $10\%$ saturated. For the sigmoid the mean on every layer is about $0.5$ ($0.516$ on the last one) — the outputs are not centred.

Hence tanh layers use Glorot (Xavier) initialization, $\operatorname{Var}w=\frac{2}{n_\text{in}+n_\text{out}}$, and PyTorch recommends multiplying it by the gain $g=5/3$ (calculate_gain('tanh')): the factor compensates for tanh squeezing the signal. For a square layer this is exactly the case $g=5/3$ in Figure 6.

A tanh network fits a curve

A hidden layer of $H$ neurons and a linear output: $\hat y(x)=\sum_{k=1}^{H}v_k\tanh(w_kx+b_k)+c$. Each term is a “step” with smooth edges; training moves, stretches and scales the steps until their sum lies on the data.

Figure 7. 40 points of $y=0.8\sin(2.2x)+0.3x$ with noise ($\sigma=0.08$), full-batch gradients and Adam with step $0.05$. The teal curves are the contributions of individual neurons, the blue one is their sum. With 5 neurons the MSE drops from $1.059$ to a plateau of about $0.05$ (steps 200–380); then one neuron “finds its role”: by step 500 the error is $0.006$, by step 800 $0.0041$, at the noise level ($0.08^2=0.0064$). With 3 neurons the network gets stuck at about $0.11$ ($0.106$ by step 2000); with 8 it reaches $0.0039$ by step 400.
A plateau means saturation

Long plateaus on the loss curve often mean that some neurons work on the flat tails of tanh: their derivative is small, and the gradient barely moves their parameters. Input normalization, careful initialization and adaptive optimizers such as Adam help.

Tanh in recurrent networks and LSTM

A plain recurrent network updates its state with the same formula at every step: $h_t=\tanh(Wh_{t-1}+Ux_t+b)$. Here tanh works as a fuse: however long the text, the state stays in $(-1,\,1)$ and does not “explode”. But boundedness is paid for with the gradient (the factors are multiplied from $s=T$ on the left to $s=t+1$ on the right):

$$\frac{\partial h_T}{\partial h_t}=\prod_{s=t+1}^{T}\operatorname{diag}\bigl(1-h_s^{2}\bigr)\,W$$

Every factor contains $1-h_s^2\le1$. If the weights are small, the product decays exponentially. If the weights are large, the states are pressed against $\pm1$, $1-h_s^2\to0$ — and the gradient fades too. It survives only in a narrow window between these regimes. In a multidimensional RNN near the edge of this window the gradient can also explode (Pascanu et al., 2013), which is why tanh RNNs are trained with gradient-norm clipping.

Figure 8. A scalar RNN $h_t=\tanh(wh_{t-1}+x_t)$, 30 steps, inputs $x_t\sim N(0,\,0.2^2)$ (grey bars). Below: $|\partial h_{30}/\partial h_t|$ on a log scale. With $w=1$ the gradient from the first step to the last shrinks to $3.1\cdot10^{-4}$; with $w=0.5$ to $5.7\cdot10^{-11}$; with $w=1.2$ to $1.3\cdot10^{-3}$; and with $w=2$ and $w=3$, when the state is saturated, to $7.2\cdot10^{-18}$ and $1.6\cdot10^{-38}$.

LSTM solves this with a separate “highway” — the cell state $c_t$, which is updated by addition rather than through tanh:

$$\begin{aligned}g_t&=\tanh\bigl(W_g[h_{t-1},x_t]+b_g\bigr)\\c_t&=f_t\odot c_{t-1}+i_t\odot g_t\\h_t&=o_t\odot\tanh(c_t)\end{aligned}$$

Here $f_t,i_t,o_t\in(0,\,1)$ are gates built on sigmoids, and tanh plays two roles: the candidate $g_t\in(-1,\,1)$ can both increase and decrease the memory (a sigmoid could only add), and $\tanh(c_t)$ bounds the output. Along the chain $c_{t-1}\to c_t$ the gradient is multiplied by $f_t$ (ignoring the dependence of the gates on $h_{t-1}$), with no $\tanh'$ factor, so with $f_t\approx1$ it reaches distant steps.

A bit of history

In 1998 Yann LeCun recommended the scaled tangent $1.7159\tanh(2x/3)$: it gives $f(\pm1)=\pm1$ and an output variance close to one. LSTM (Hochreiter and Schmidhuber, 1997) made tanh the standard of recurrent networks for two decades. In convolutional networks it was displaced by ReLU: in the AlexNet paper (2012) a four-layer convolutional network with ReLU reached 25% training error on CIFAR-10 six times faster than the same network with tanh.

In code: stable and without surprises

The naive formula through exponentials computes $e^{1000}=\infty$ at $x=1000$, and the result is $\infty/\infty=\text{nan}$. The built-in np.tanh and torch.tanh are stable: for $x\gtrsim19$ they return exactly $1.0$ in float64. But then $1-\tanh^2 x$ gives exactly 0, although the true value at $x=20$ is about $1.7\cdot10^{-17}$. If you need the derivative on the far tails, compute it through $\operatorname{sech}^2$ in a stable form.

pythonimport numpy as np

def tanh_grad_from_output(t):
    """The derivative from the already computed output t = tanh(x): one multiplication."""
    return 1.0 - t * t

def tanh_grad(x):
    """sech²x = 4e^(−2|x|) / (1 + e^(−2|x|))²:
    no overflow and no loss of precision."""
    e = np.exp(-2.0 * np.abs(x))
    return 4.0 * e / (1.0 + e) ** 2

def naive_tanh(x):
    return (np.exp(x) - np.exp(-x)) / (np.exp(x) + np.exp(-x))

print(naive_tanh(1000.0))       # nan: inf / inf (plus an overflow warning)
print(np.tanh(1000.0))          # 1.0 — the built-in function is stable
print(1 - np.tanh(20.0) ** 2)   # 0.0: tanh(20) rounds to 1 in float64
print(tanh_grad(20.0))          # 1.6993417021166355e-17 — the correct value
pythonimport torch
import torch.nn as nn

x = torch.tensor([-2.0, 0.0, 2.0], requires_grad=True)
y = torch.tanh(x)               # tensor([-0.9640,  0.0000,  0.9640])
y.sum().backward()
print(x.grad)                   # tensor([0.0707, 1.0000, 0.0707]) = 1 − tanh²

# Initialization for tanh: gain 5/3
layer = nn.Linear(256, 256)
nn.init.xavier_uniform_(layer.weight, gain=nn.init.calculate_gain("tanh"))

# A recurrent network with tanh and gradient clipping against explosions
rnn = nn.RNN(input_size=32, hidden_size=64, nonlinearity="tanh", batch_first=True)
out, h = rnn(torch.randn(8, 100, 32))   # 8 sequences of length 100
out.pow(2).mean().backward()
nn.utils.clip_grad_norm_(rnn.parameters(), max_norm=1.0)
The rule

Use the built-in tanh and automatic differentiation; on the backward pass, the formula $1-t^2$ from the stored output. For tanh networks, Glorot (Xavier) initialization with gain $5/3$; for RNNs, gradient-norm clipping.

Common mistakes

  1. tanh at the output instead of the sigmoid for a probability. The output of tanh lies in $(-1,\,1)$ and is not a probability. Binary classification needs the sigmoid and BCE; tanh at the output is appropriate when the targets are scaled to $[-1,\,1]$.
  2. The derivative of the input instead of the output. The formula $1-t^2$ applies to the output $t=\tanh x$. A common slip is $1-x^2$ of the input: at $x=2$ it gives $-3$ instead of $0.071$.
  3. Unnormalized inputs and large weights. If the features are in the hundreds or the weights are too large, tanh is saturated from the first steps and hardly learns. Standardize the data and use an initialization meant for tanh.
  4. “tanh solves vanishing gradients”. It is better than the sigmoid (a derivative up to 1 and centring), but it saturates too. For deep networks use the ReLU family, normalization and residual connections; for sequences, LSTM/GRU.
  5. A home-made tanh through exp. It returns nan for large $|x|$. Use np.tanh or torch.tanh.
  • Sigmoid: $\tanh x=2\sigma(2x)-1$ and $\sigma(x)=\tfrac12(1+\tanh\tfrac x2)$; the derivatives are related by $\tanh' x=4\sigma'(2x)$.
  • ReLU: does not saturate for $x>0$ and displaced tanh from deep convolutional networks.
  • GELU: the popular approximation $0.5x\bigl(1+\tanh\bigl(\sqrt{2/\pi}\,(x+0.044715x^3)\bigr)\bigr)$.
  • SiLU: $x\sigma(x)=\tfrac x2\bigl(1+\tanh\tfrac x2\bigr)$ — the same S-curve acting as a “soft gate”.
  • MSE: the natural partner for a tanh output when the targets lie in $[-1,\,1]$.
  • Adam: the optimizer of Figure 7; its adaptive step helps it get through plateaus caused by saturation.

Summary

1) $\tanh x=\frac{e^x-e^{-x}}{e^x+e^{-x}}=\frac{\sinh x}{\cosh x}=2\sigma(2x)-1$ maps $\mathbb R$ onto $(-1,\,1)$, is odd and passes through zero. 2) $\tanh'=1-\tanh^2\le1$, with the maximum at zero and saturation on the tails. 3) The Taylor series $x-\frac{x^3}{3}+\dots$ converges for $|x|<\pi/2$. 4) Zero-centred outputs make the next layer train faster than with the sigmoid. 5) Sums of tanh folds approximate any continuous function on a compact set; initialize with Glorot (Xavier) and gain $5/3$. 6) In an RNN tanh keeps the state bounded, but the gradient through time fades — hence LSTM.

Check yourself

1. We know that $\tanh 0.5\approx0.462$. What is $\tanh(-0.5)$?
2. A neuron output $t=\tanh z=0.8$. What is the derivative $\tanh' z$?
3. Which identity is correct?
4. Why does tanh in hidden layers usually train faster than the sigmoid?
5. In a tanh RNN the recurrent weight was made very large. What happens to the gradient over many steps?