AI Wiki中文/EN

Sigmoid and tanh: saturation and stable computation

Sigmoid 与 tanh

Compare smooth activations, stable tail derivatives and two losses that respond differently to confidently wrong outputs.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Two smooth responses, two different centers

A score may be any real number. A sigmoid squeezes it into(0,1); tanh squeezes it into(−1,1). Near zero, both respond to small changes. Far from zero, both flatten. That flattening is called saturation, and it affects derivatives passed through a network.

The logistic sigmoid is useful for a Bernoulli output or a gate between zero and one. Tanh permits signed responses and is symmetric around zero. Neither range alone proves that its outputs are well calibrated or that a network will train easily. D2L, Sections 5.1.2.2–5.1.2.3 provides the definitions and derivative shapes. Deep Learning, Section 6.2.2.2 explains why the loss paired with a sigmoid changes the consequences of saturation.

Read artificial neurons and the chain rule first. We will compare mathematical values, floating-point values and loss derivatives rather than infer all three from one plot.

The shape and slope fit in two identities

The logistic sigmoid and hyperbolic tangent satisfy:

σ(z)=11+e−z,tanh⁡(z)=2σ(2z)−1,σ(−z)=1−σ(z),tanh⁡(−z)=−tanh⁡(z).\sigma(z)=\frac1{1+e^{-z}},\qquad \tanh(z)=2\sigma(2z)-1,\qquad \sigma(-z)=1-\sigma(z),\quad\tanh(-z)=-\tanh(z).

For finite real z in exact arithmetic, their ranges are open intervals. Their limiting values at infinity are not attained at any finite input. Tanh’s odd symmetry does not guarantee a dataset’s mean activation is zero: that requires a suitable input distribution. For a symmetric distribution of z, bounded odd tanh does have zero expectation.

Differentiating gives:

σ′(z)=σ(z)(1−σ(z))≤14,tanh⁡′(z)=1−tanh⁡2(z)≤1.\sigma'(z)=\sigma(z)(1-\sigma(z))\le\frac14,\qquad \tanh'(z)=1-\tanh^2(z)\le1.

Both derivatives are positive at every finite real input. Their maxima occur at z=0: sigmoid has value 1/2 and slope 1/4, tanh has value 0 and slope 1. The derivatives approach zero in both tails. In a scalar chain of L sigmoid layers whose intervening weight magnitudes are at most 1, the input derivative magnitude is at most 4⁻ᴸ by the chain rule. Without that weight bound, the same conclusion does not follow; matrix weights in larger networks also affect gradient norms.

The output loss changes the gradient

Let p=σ(z) and y be 0 or 1. Compare half squared error with Bernoulli cross-entropy, computed directly from the logit z:

Lsq=12(p−y)2,∂Lsq∂z=(p−y)σ′(z);LBCE=max⁡(z,0)−yz+log⁡(1+e−∣z∣),∂LBCE∂z=p−y.L_{\mathrm{sq}}=\tfrac12(p-y)^2,\quad \frac{\partial L_{\mathrm{sq}}}{\partial z}=(p-y)\sigma'(z);\qquad L_{\mathrm{BCE}}=\max(z,0)-yz+\log(1+e^{-|z|}),\quad \frac{\partial L_{\mathrm{BCE}}}{\partial z}=p-y.

The BCE expression is an algebraically equivalent stable form of the negative Bernoulli log likelihood. Differentiating its usual expression in p and multiplying by dp/dz cancels the sigmoid factor. The final loss is smooth at z=0 even though the stable expression contains max and absolute value.

For y=1 and z=−40, the probability is about 4.25×10⁻¹⁸, a confidently wrong prediction. The squared-error gradient is about−4.25×10⁻¹⁸; the BCE gradient is approximately−1. Saturation therefore does not automatically kill the BCE gradient with respect to this output logit. Hidden sigmoid slopes can still shrink gradients further upstream, and a saturated correct output appropriately has a small loss gradient.

Avoid overflowing an exponential

The direct expression 1/(1+exp(−z)) overflows exp for sufficiently negative floating-point z. Evaluate e=exp(−|z|) instead, returning 1/(1+e) for nonnegative z and e/(1+e) otherwise. Compute the sigmoid slope as e/(1+e)² so it can remain nonzero even when p rounds to 1. A similar exponential form gives the tanh slope.

The complete Python 3.12 program uses only the standard library. Its binary residual for y=1 is−σ(−z), which avoids subtracting a rounded p from 1. That residual is used in both the loss and gradient calculations.

from math import exp, log1p, tanh, isfinite


def responses(z):
    if type(z) not in (int,float) or not isfinite(z) or abs(z)>1000:
        raise ValueError('finite real score in [-1000,1000] required')
    e=exp(-abs(z));p=1/(1+e) if z>=0 else e/(1+e)
    e2=exp(-2*abs(z))
    return p,e/(1+e)**2,tanh(z),4*e2/(1+e2)**2


def binary_losses(z, target):
    p,dp,_,_=responses(z)
    if type(target) is not int or target not in (0,1):
        raise ValueError('binary integer target required')
    residual=p if target==0 else -responses(-z)[0]
    bce=max(z,0)-target*z+log1p(exp(-abs(z)))
    return (residual*residual/2,residual*dp),(bce,residual)


if __name__=='__main__':
    for z in (0,20,40,-40,1000,-1000):
        p,dp,t,dt=responses(z)
        print('z:',z,'sigmoid/slope/tanh/slope:',*[f'{v:.9g}' for v in (p,dp,t,dt)])
    for z in (-40,40):
        squared,bce=binary_losses(z,1)
        print('target1, z:',z,'half-MSE loss/gradient:',*[f'{v:.9g}' for v in squared],
              'BCE loss/gradient:',*[f'{v:.9g}' for v in bce])

Actual output:

z: 0 sigmoid/slope/tanh/slope: 0.5 0.25 0 1
z: 20 sigmoid/slope/tanh/slope: 0.999999998 2.06115361e-09 1 1.6993417e-17
z: 40 sigmoid/slope/tanh/slope: 1 4.24835426e-18 1 7.21940555e-35
z: -40 sigmoid/slope/tanh/slope: 4.24835426e-18 4.24835426e-18 -1 7.21940555e-35
z: 1000 sigmoid/slope/tanh/slope: 1 0 1 0
z: -1000 sigmoid/slope/tanh/slope: 0 0 -1 0
target1, z: -40 half-MSE loss/gradient: 0.5 -4.24835426e-18 BCE loss/gradient: 40 -1
target1, z: 40 half-MSE loss/gradient: 9.02425694e-36 -1.80485139e-35 BCE loss/gradient: 4.24835426e-18 -4.24835426e-18

At z=40, floating-point sigmoid may print or round to 1 while the directly evaluated slope remains about 4.25×10⁻¹⁸. At z=20, tanh can round to 1 while its slope formula retains about 1.70×10⁻¹⁷. These are representations of smooth mathematical functions, not newly defined discontinuities. At much larger magnitudes, even the exponential underflows and a numerical slope becomes zero.

Every scalar evaluation takes constant time and space. The explicit score bound keeps this demonstration within a finite tested range. In model code, use the framework’s loss-from-logits operation instead of independently applying sigmoid, clipping probabilities and taking logarithms. Our tests compare exact central values, finite differences at moderate scores, symmetry, tail behavior and invalid inputs; no deep network is trained here.

A centered output is not a cure for training

Tanh’s zero-centered range can be convenient, but it also saturates. Input scaling, initialization, normalization, depth and weight matrices all influence whether activations reach flat regions. Replacing an activation is one intervention, not a complete explanation of a training outcome.

Sigmoid outputs are bounded, yet the BCE for a confidently wrong logit is unbounded. Clipping p changes the objective or its derivatives and can hide severe errors. Stable logit evaluation avoids the need for such clipping in this example. Class weighting, label smoothing and different targets change the stated loss and require their own derivative derivations.

This chapter distinguishes output-logit gradients from hidden-layer gradients. It does not claim BCE prevents all vanishing gradients or that tanh always outperforms sigmoid. See activation functions and the planned ReLU chapter for different response shapes.

Which quantity has saturated?

  1. What are the two function values and derivatives at zero?

Answer 1: Sigmoid is 1/2 with derivative 1/4; tanh is 0 with derivative 1.

  1. For y=1 and a very negative logit, which loss has an output-logit gradient approaching−1?

Answer 2: Bernoulli cross-entropy. The half-squared-error gradient approaches zero instead.

  1. If floating-point tanh(20) is 1, does the exact derivative at 20 equal zero?

Answer 3: No. It is positive, about 1.70×10⁻¹⁷. Computing 1 minus the squared rounded value loses that small quantity.

  1. Does the 4⁻ᴸ scalar sigmoid derivative bound hold for arbitrary intervening weights?

Answer 4: No. The stated bound assumes every intervening weight has magnitude at most 1; larger factors can change the product.

Check the objective alongside the activation

The sources establish the response definitions and the Bernoulli output-loss argument. The branch-stable implementation, tail comparison and tests are original teaching material. The important experimental question is not just whether a unit’s curve looks flat, but which derivative is measured under which objective and numerical representation.

Continue to gradient checking to compare analytic and numerical derivatives, and backpropagation to see how local derivatives combine. A finite-difference check near complete numerical saturation can itself be unreliable because the perturbed function values may round to the same number.

Make a prediction, then check

For y=1 and z=−40, which output-logit gradient is near−1?

Choose one answer

Learning objectives

  • Derive response slopes and state saturation assumptions.
  • Compute stable losses from logits and distinguish output gradients.

Prerequisites & connections

Explore related knowledge →

References

  1. Dive into Deep Learning — 5.1 Multilayer Perceptrons
    Aston Zhang; Zachary C. Lipton; Mu Li; Alexander J. Smola · 2023
  2. Deep Learning — Chapter 6: Deep Feedforward Networks
    Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.

  • Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
  • Four focused CPython3.12.4 tests passed per chapter. Neuron gradients, exact XOR/affine composition, sharp interpolation errors and stable activation/loss derivatives are checked against literal references, analytic identities and finite differences. No external runtime dependencies.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
  • Final copy review restored the proper name D2L after prose spacing; no equations, examples or exercises changed. Final English article SHA rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.