Sign in

Tanh

Hyperbolic tangent

The hyperbolic tangent: an S-shaped activation that squashes any input into a range centred on zero, from minus the amplitude to plus the amplitude.

Overview

Tanh is the sigmoid's zero-centred sibling. It maps large negative inputs toward −1-1, large positive inputs toward +1+1, and zero to zero. Near the origin it is almost a straight line of slope 1, so small signals pass through nearly unchanged. Because outputs are balanced around zero, the next layer receives inputs with no built-in offset, which helps gradient descent. The template adds two settings: an amplitude that stretches the output range and a slope that scales the input.

A short history

The hyperbolic functions were developed in the 1760s by Vincenzo Riccati and Johann Lambert. In neural networks, tanh became the preferred hidden activation in the 1990s because its output is centred on zero, which Yann LeCun and colleagues argued makes training faster than the logistic sigmoid. The LSTM of Hochreiter and Schmidhuber in 1997 built it into its cell. ReLU replaced it in deep feed-forward networks after 2012 because tanh saturates.

How it works

  1. Take the input xx and multiply it by the slope kk.
  2. Compute tanh⁡(kx)\tanh(kx), a number strictly between −1-1 and 11.
  3. Multiply by the amplitude AA, so the output lies between −A-A and AA.
  4. During training, multiply the incoming gradient by A k (1−tanh⁡2(kx))A\,k\,(1 - \tanh^{2}(kx)).

Watch out for

  • For large inputs of either sign the slope is nearly zero. Units pushed into those flat regions stop learning, and deep stacks of tanh suffer vanishing gradients.
  • The output can never reach ±A\pm A exactly. Targets placed at the limits drive the pre-activations toward infinity.
  • Changing amplitude or slope changes the scale of the gradient by the factor AkA k. Initialisation schemes derived for plain tanh no longer match.

Use cases

When to use it

Recurrent networks such as LSTMs and GRUs, and output layers that must be bounded and symmetric, such as actions scaled to a range or images scaled to [−1,1][-1, 1].

In industry

Sequence models
LSTM and GRU networks use tanh to produce candidate values for their state, keeping them in a bounded range across many time steps.
Robotics and control
Policy networks for continuous control end in a tanh so that actions such as motor torques stay within fixed limits.
Image generation
GAN generators in the DCGAN design end in a tanh so that pixel values fall between minus one and plus one.

Choosing it: what must hold

  • A need for a bounded output that is centred on zero.
  • Inputs and weights scaled so that most values fall in the middle of the curve, not in the flat ends.
  • A network that is shallow, recurrent with gates, or uses tanh only at the output.

When to choose something else

IfUse instead
You need hidden activations for a deep feed-forward or convolutional networkReLU
The output is a probability between 0 and 1Sigmoid
The model is a transformerGELU

Math foundations

  1. The hyperbolic tangent

    tanh⁡(x)=ex−e−xex+e−x\tanh(x) = \frac{e^{x} - e^{-x}}{e^{x} + e^{-x}}

    An odd function, so tanh⁡(−x)=−tanh⁡(x)\tanh(-x) = -\tanh(x), with values strictly between −1-1 and 11.

  2. The template's form

    f(x)=Atanh⁡(kx)f(x) = A \tanh(k x)

    The amplitude AA sets the output range and kk sets how quickly the curve saturates. The defaults A=k=1A = k = 1 give plain tanh.

  3. Its slope

    f′(x)=A k (1−tanh⁡2(kx))f'(x) = A\,k\,\big(1 - \tanh^{2}(k x)\big)

    Written in terms of the tanh value already computed. The slope is largest at x=0x = 0, where it equals AkA k, and falls toward 0 as the unit saturates.

  4. Relation to the sigmoid

    tanh⁡(x)=2 σ(2x)−1\tanh(x) = 2\,\sigma(2x) - 1

    Tanh is a sigmoid stretched to the range −1-1 to 11 and compressed along the input axis. The two differ in centring and in peak slope: 1 for tanh, 0.25 for the sigmoid.

Symbols

xx
the input to the activation
AA
output scale, amplitude in the config, default 1
kk
input scale, slope in the config, default 1
σ\sigma
the logistic sigmoid

Worked by hand

Compute plain tanh (A=k=1A = k = 1) and its slope at x=0.5x = 0.5 and x=2x = 2. Use tanh⁡(0.5)=0.4621\tanh(0.5) = 0.4621 and tanh⁡(2)=0.9640\tanh(2) = 0.9640.

f′(0.5)=1−0.46212=1−0.2135=0.7865f'(0.5) = 1 - 0.4621^{2} = 1 - 0.2135 = 0.7865
f′(2)=1−0.96402=1−0.9293=0.0707f'(2) = 1 - 0.9640^{2} = 1 - 0.9293 = 0.0707

At 0.5 the unit still passes 79 percent of the gradient. At 2 it passes 7 percent. Saturation sets in quickly.

Visual example

Loading the example.

Try this

  • Move across the curve and read the output and the slope together.
  • Find where the slope is close to zero: a unit there has stopped learning.

Code sample

import numpy as np
from impl import Tanh
from config import TanhConfig

act = Tanh(TanhConfig())
y = act.forward(np.array([-1.0, 0.0, 1.0]))      # [-0.7616, 0.0, 0.7616]
dy = act.backward(np.array([-1.0, 0.0, 1.0]))    # [0.42, 1.0, 0.42]
Read the implementation (35 lines)
"""Tanh: hyperbolic tangent, f(x) = amplitude * tanh(slope * x).

NumPy only. `forward` computes the activation, `backward` the gradient with respect to the input.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import TanhConfig
except ImportError:  # run from the template's own folder
    from config import TanhConfig

class Tanh:
    """f(x) = amplitude * tanh(slope * x), output in (-amplitude, amplitude)."""

    def __init__(self, config: TanhConfig | None = None) -> None:
        self.config = config or TanhConfig()

    def forward(self, x: np.ndarray) -> np.ndarray:
        """Apply the activation element by element. x: any shape. Returns the same shape."""
        x = np.asarray(x, dtype=float)
        return self.config.amplitude * np.tanh(self.config.slope * x)

    def backward(self, x: np.ndarray, grad_output: np.ndarray | None = None) -> np.ndarray:
        """d f / d x at x, times `grad_output` when given (the chain rule step of backpropagation).

        f'(x) = amplitude * slope * (1 - tanh(slope * x)^2).
        """
        x = np.asarray(x, dtype=float)
        t = np.tanh(self.config.slope * x)
        local = self.config.amplitude * self.config.slope * (1.0 - t**2)
        return local if grad_output is None else local * np.asarray(grad_output, dtype=float)

    __call__ = forward
Repository
gitlab.com/designsbyduhart/solomon-templates/activation-tanh
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Build Tanh(TanhConfig(amplitude=1.0, slope=1.0)) and find the input size beyond which backward is below 0.01. Then use Tanh(TanhConfig(amplitude=1.7159, slope=0.6667)) and report its output and slope at inputs of 1 and 0.

Check on learning

  1. Both sigmoid and tanh saturate. Why did tanh still train noticeably better than sigmoid as a hidden activation?
    A way to think about it

    Compare two things: the peak slope, 1 against 0.25, and the mean of the outputs. Consider what a non-zero mean does to the gradients of the next layer's weights.

  2. An LSTM uses tanh for its candidate values and sigmoid for its gates. Why not the other way round?
    A way to think about it

    A gate answers how much, from none to all. A value needs a sign. Match each role to the range of the function.

  3. Your network's last layer is tanh and the targets are exactly −1-1 and +1+1. What will the pre-activations do during training?
    A way to think about it

    The output only reaches the limits as the input goes to infinity. Think about what the loss gradient keeps asking for, and what that does to the weights.

  4. Doubling slope doubles the peak gradient but also narrows the region where the gradient is large. How would you reason about the net effect?
    A way to think about it

    It depends on the spread of the inputs. If most pre-activations are small, they gain. If they are spread wide, more of them land in the flat tails.