The neural notebook
← All chapters

IV-03 / Part I · Neural Network Foundations

Activations, Derivatives and Saturation

Compare ReLU, stable sigmoid and tanh values and slopes, including the ReLU kink and floating-point saturation.

Review the ideas this chapter uses

A weighted sum can be positive, negative or enormous. What should the next layer receive? An activation function transforms that sum, and its local slope tells us how much a small change can travel through the transformation.

We will give three activations exactly the same input and compare both their outputs and slopes. The initial input is zero, where their behavior differs especially clearly. These are evaluations of functions, not a training run.

Compute it yourself

One input, three activations and their slopes

These controls recompute the actual example. Trace navigation shows saved calculation steps; editing starts a new trace from the displayed inputs.

Complete results from this trace’s starting inputs

Starting inputs for these results
z
0
relu0
sigmoid0.5
tanh0
sigmoidSlope0.25

relu 0. sigmoid 0.5. tanh 0. sigmoidSlope 0.25. ReLU value and selected backward slope. The true ReLU derivative is undefined at zero. The selected backward subgradient is 0.. relu 0. reluSlope 0

ReLU value and selected backward slope

relu=max(0,z); slope=(z>0 ? 1 : 0)

The true ReLU derivative is undefined at zero. The selected backward subgradient is 0.

Inputs

z
0

Outputs

relu
0
reluSlope
0

Current z=0. Selected operation: ReLU value and selected backward slope.

ActivationOutputStored-number slope
ReLU00 (chosen subgradient; true derivative undefined)
Sigmoid0.50.25
Tanh01

A finite-tail computed zero for sigmoid/tanh can reflect rounding. Their true analytic slopes remain positive for every finite z.

Inspect tensor shapes and full precision

All computed outputs

relu
0
sigmoid
0.5
tanh
0
sigmoidSlope
0.25
reluSlope
0
tanhSlope
1
z
0

Values below are stored binary64 numbers, shown without display rounding. Axes specify what each dimension counts; flattened storage is in row-major order.

activation_comparison

activation=3 × quantity=2 · float64 · display precision 8 · Rows ReLU/sigmoid/tanh; columns output/selected or computed slope.

Storage indexValue
00
10
20.5
30.25
40
51

relu.relu

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · relu: relu=max(0,z); slope=(z>0 ? 1 : 0)

Storage indexValue
00

relu.reluSlope

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · relu: relu=max(0,z); slope=(z>0 ? 1 : 0)

Storage indexValue
00

sigmoid.sigmoidArgument

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · sigmoid: sigmoid=1/(1+exp(-z))

Storage indexValue
00

sigmoid.sigmoidExp

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · sigmoid: sigmoid=1/(1+exp(-z))

Storage indexValue
01

sigmoid.sigmoidDenominator

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · sigmoid: sigmoid=1/(1+exp(-z))

Storage indexValue
02

sigmoid.sigmoid

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · sigmoid: sigmoid=1/(1+exp(-z))

Storage indexValue
00.5

sigmoid-slope.sigmoidComplement

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · sigmoid-slope: sigmoidSlope=sigmoid*(1-sigmoid)

Storage indexValue
00.5

sigmoid-slope.sigmoidSlope

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · sigmoid-slope: sigmoidSlope=sigmoid*(1-sigmoid)

Storage indexValue
00.25

tanh.tanh

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · tanh: tanh=tanh(z)

Storage indexValue
00

tanh-slope.tanhSquared

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · tanh-slope: tanhSlope=1-tanh*tanh

Storage indexValue
00

tanh-slope.tanhSlope

scalar_row=1 × scalar_column=1 · float64 · display precision 8 · tanh-slope: tanhSlope=1-tanh*tanh

Storage indexValue
01

Try z=-2, z=0 and z=2, then the finite tails ±40. Inspect the stable sigmoid exponential operands in the trace. All three functions share the same editable preactivation.

Check your understanding

Work from the starting inputs shown above. Each answer includes the reasoning; editing the example resets your answers.

1. At z=0, sigmoid's computed slope is 0.25. What does a local slope describe?
2. At your current z=0, which is ReLU(z)?
3. The sigmoid value is 0.5. Which computed slope matches s*(1-s)?
4. Your tanh value is 0. What should you expect when moving z far into a tail?
5. Current ReLU slope selection=0. What can a central difference across z=0 establish?

Try negative two, zero and positive two before exploring the tails at negative forty and positive forty. The table uses the same preactivation for every function. Select the sigmoid step to inspect its exponential argument and denominator rather than treating the final decimal as an unexplained library answer.

From a weighted sum to an activation

A preactivation, written zz, is the value before an activation function. In the previous chapter it was a weighted sum plus bias. Here we edit zz directly so that changes in the activation are not mixed with changes in weights or input shape. An activation is the resulting value a=f(z)a=f(z).

A local slope, or derivative f′(z)f'(z), measures the nearby output change per unit input change. It is not the output itself. If an input perturbation is small enough and the function is differentiable there, an approximate relation is Δa≈f′(z)Δz\Delta a\approx f'(z)\Delta z. This is a local statement: doubling a large input change need not double the activation’s change.

Every entry here is scalar. The comparison tensor has three activation rows, in order ReLU, sigmoid and tanh, and two quantity columns: output and selected or computed slope. Those rows are different functions, not different samples in a batch. Distinguishing those meanings matters even though the storage mechanism is the same tensor record.

If all layers only applied affine transformations, composing them would still produce an affine transformation. A nonlinear activation can make the relationship between inputs and outputs more expressive. It does not independently choose useful parameters or guarantee that an optimization procedure will succeed.

ReLU: two simple branches and a real kink

The rectified linear unit, ReLU, is defined by

f(z)=max⁡(0,z).f(z)=\max(0,z).

For z=−2z=-2, the output is zero. For z=2z=2, the output is two. On the strictly negative branch, changing zz slightly still gives zero, so the derivative is zero. On the strictly positive branch, the output equals its input, so the derivative is one.

At exactly zero, the forward value remains perfectly well defined: f(0)=0f(0)=0. The derivative is another question. Approaching zero from the left gives slope zero; approaching from the right gives slope one. Since those disagree, there is no unique derivative at the kink.

Our backward convention selects subgradient zero at that point. The table labels it explicitly, rather than claiming ReLU has a true derivative of zero everywhere that its output is zero. A central difference straddling the kink can average the two sides, but it cannot create differentiability. Later numerical gradient checks must exclude perturbations that cross this boundary.

An inactive ReLU is also not necessarily permanently inactive. Another input or another parameter state can place the preactivation on the positive branch. The zero local slope describes the current negative region, not an irreversible property of a neuron.

Sigmoid: a bounded output and stable evaluation

The sigmoid function maps real numbers into the interval between zero and one:

s(z)=11+exp⁡(−z).s(z)=\frac{1}{1+\exp(-z)}.

Here exp⁡(t)=et\exp(t)=e^t is the exponential function. Its positive outputs grow rapidly when tt grows. Directly evaluating exp⁡(−z)\exp(-z) for an extremely negative zz can therefore be numerically awkward. An equivalent negative-input formula avoids that problem:

s(z)=exp⁡(z)1+exp⁡(z)when z<0.s(z)=\frac{\exp(z)}{1+\exp(z)}\quad\text{when }z<0.

The implementation chooses the first expression for nonnegative inputs and the second for negative inputs. In either case the exponential argument is nonpositive. The trace exposes sigmoidArgument, sigmoidExp and sigmoidDenominator, so you can inspect the actual stable evaluation. Equivalent mathematics does not require identical intermediate magnitudes.

The local sigmoid derivative is

s′(z)=s(z)(1−s(z)).s'(z)=s(z)\bigl(1-s(z)\bigr).

At the origin, exp⁡(0)=1\exp(0)=1, giving s(0)=1/(1+1)=1/2s(0)=1/(1+1)=1/2. Its slope is (1/2)(1−1/2)=1/4(1/2)(1-1/2)=1/4. A value of one half and a slope of one quarter describe different properties of the same function at the same point.

As the output approaches either endpoint, one of the two derivative factors becomes small. The resulting small slope is called saturation: nearby input changes make relatively little difference to the output. A sigmoid-like output is sometimes used as a probability, but interpreting it that way requires a declared task and objective; a bounded number alone is not evidence of calibrated prediction.

Tanh: centered outputs

The hyperbolic tangent, written tanh⁡\tanh, maps real inputs between negative one and positive one. One mathematical identity is

tanh⁡(z)=exp⁡(z)−exp⁡(−z)exp⁡(z)+exp⁡(−z).\tanh(z)=\frac{\exp(z)-\exp(-z)}{\exp(z)+\exp(-z)}.

The code uses the platform’s native tanh evaluation rather than rebuilding that ratio. Native implementations can handle rounding and cancellation more carefully than a naive literal expression. The identity explains the function, while the stored result remains a binary64 approximation.

Its derivative can be written using its own output:

ddztanh⁡(z)=1−tanh⁡2(z).\frac{d}{dz}\tanh(z)=1-\tanh^2(z).

At zero, the numerator in the identity is 1−1=01-1=0 and the denominator is 1+1=21+1=2. Therefore tanh⁡(0)=0\tanh(0)=0, and its derivative is 1−02=11-0^2=1. The complete default comparison is now explicit:

FunctionOutput at zeroLocal backward slope shown
ReLU00selected 00, true derivative undefined
Sigmoid1/21/21/41/4
Tanh0011

Tanh is centered around zero, unlike sigmoid. This can change how numerical signals enter another layer, but it is not a universal guarantee of easier learning. Its tails also saturate.

Why these slopes work

For sigmoid, write s=(1+e−z)−1s=(1+e^{-z})^{-1}. The exponential’s derivative is d(e−z)/dz=−e−zd(e^{-z})/dz=-e^{-z}. Applying the power rule to the reciprocal and then the chain rule gives

s′=−(1+e−z)−2(−e−z)=e−z(1+e−z)2.s'=-(1+e^{-z})^{-2}(-e^{-z}) =\frac{e^{-z}}{(1+e^{-z})^2}.

Now split the fraction into two factors. The first is ss, and the second equals 1−s1-s:

11+e−z⋅e−z1+e−z=s(1−11+e−z)=s(1−s).\frac1{1+e^{-z}}\cdot\frac{e^{-z}}{1+e^{-z}} =s\left(1-\frac1{1+e^{-z}}\right)=s(1-s).

For tanh, let u=ezu=e^z and v=e−zv=e^{-z}, so u′=uu'=u and v′=−vv'=-v. A prime denotes a derivative with respect to zz. Write the output as t=(u−v)/(u+v)t=(u-v)/(u+v). The numerator derivative is u+vu+v, and the denominator derivative is u−vu-v. The quotient rule therefore gives

t′=(u+v)(u+v)−(u−v)(u−v)(u+v)2=(u+v)2−(u−v)2(u+v)2=1−(u−vu+v)2=1−t2.t'=\frac{(u+v)(u+v)-(u-v)(u-v)}{(u+v)^2} =\frac{(u+v)^2-(u-v)^2}{(u+v)^2} =1-\left(\frac{u-v}{u+v}\right)^2=1-t^2.

The denominator is positive because exponentials are positive. These are real-arithmetic identities. The code substitutes stored sigmoid/tanh outputs into the final expressions, so the floating-point caveats below still apply.

Stored endpoints are not analytic endpoints

Binary64 arithmetic has finite precision. A sufficiently positive sigmoid input can produce a stored output exactly equal to one, because the tiny difference from one is no longer representable at that scale. Computing s(1−s)s(1-s) from that stored value gives zero. Similarly, native tanh can round a finite tail to positive or negative one, making the computed 1−t21-t^2 zero.

Mathematically, sigmoid and tanh have positive derivatives at every finite real input. The displayed zero in these cases is a numerical saturation result, not a newly discovered exact flat interval. ReLU’s negative branch is different: it really is constant there and has an exactly zero derivative away from the kink.

At our bounded range [−40,40][-40,40], the sigmoid exponential tail is still representable; endpoint rounding is the important limitation. The negative sigmoid branch may preserve a tiny positive value even when the positive branch has rounded to one. Do not infer an exact numerical symmetry merely from the analytic identity s(−z)=1−s(z)s(-z)=1-s(z).

When slopes multiply along a longer chain, several small factors can greatly shrink a propagated sensitivity. This helps motivate later backpropagation chapters. The current comparison does not execute that chain or show a training curve; it isolates the local ingredients you will need.

Connect the source to the table

The Python reference uses an explicit stable sigmoid branch, native NumPy tanh, and the same slope formulas. Each product, subtraction and denominator is finite-checked before reuse. The ReLU zero convention appears directly in source.

Read the complete executable Python / NumPy source

This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.

"""IV-03: compare activation values and their stored-number slopes."""
import numpy as np
from reference import validate, finite, guarded, tensor, step, result, run

DEFAULT_IV03 = {"z": 0}


@guarded
def derive_iv03(state):
    """ReLU at zero uses selected backward 0, not a unique true derivative."""
    z = validate(state, DEFAULT_IV03, {"z": (-40, 40)})["z"]
    relu = finite(np.float64(z if z > 0 else 0), "relu")
    reluSlope = np.float64(1 if z > 0 else 0)
    # The exponential argument is never positive in this stable evaluation.
    sigmoidArgument = finite(-z if z >= 0 else z, "sigmoid argument")
    sigmoidExp = finite(np.exp(sigmoidArgument), "sigmoid exponential")
    sigmoidDenominator = finite(np.float64(1) + sigmoidExp, "sigmoid denominator")
    sigmoidValue = finite(np.float64(1) / sigmoidDenominator if z >= 0 else sigmoidExp / sigmoidDenominator, "sigmoid")
    sigmoidComplement = finite(np.float64(1) - sigmoidValue, "sigmoid complement")
    sigmoidSlope = finite(sigmoidValue * sigmoidComplement, "sigmoid slope")
    tanh = finite(np.tanh(z), "tanh")
    tanhSquared = finite(tanh * tanh, "tanh squared")
    tanhSlope = finite(np.float64(1) - tanhSquared, "tanh slope")
    steps = [
        step("relu", "ReLU value and selected backward slope", "relu=max(0,z); slope=(z>0 ? 1 : 0)", "Undefined derivative at zero; selected subgradient 0." if z == 0 else "Slope 1 for positive z, 0 for negative z.", {"z": z}, {"relu": relu, "reluSlope": reluSlope}),
        step("sigmoid", "Stable sigmoid value", "sigmoid=1/(1+exp(-z))" if z >= 0 else "e=exp(z); sigmoid=e/(1+e)", "Avoid exponentiating a positive argument.", {"z": z}, {"sigmoidArgument": sigmoidArgument, "sigmoidExp": sigmoidExp, "sigmoidDenominator": sigmoidDenominator, "sigmoid": sigmoidValue}),
        step("sigmoid-slope", "Sigmoid local slope", "sigmoidSlope=sigmoid*(1-sigmoid)", "Finite-tail zero may be floating-point saturation.", {"sigmoid": sigmoidValue}, {"sigmoidComplement": sigmoidComplement, "sigmoidSlope": sigmoidSlope}),
        step("tanh", "Hyperbolic tangent value", "tanh=tanh(z)", "Finite tails may round to endpoints.", {"z": z}, {"tanh": tanh}),
        step("tanh-slope", "Tanh local slope", "tanhSlope=1-tanh*tanh", "Use the stored activation, with its rounding limits.", {"tanh": tanh}, {"tanhSquared": tanhSquared, "tanhSlope": tanhSlope}),
    ]
    tensors = [tensor("activation_comparison", [3, 2], ["activation", "quantity"], [relu, reluSlope, sigmoidValue, sigmoidSlope, tanh, tanhSlope], "Rows ReLU/sigmoid/tanh; columns output/slope.")]
    return result(tensors, steps, {"relu": relu, "sigmoid": sigmoidValue, "tanh": tanh, "sigmoidSlope": sigmoidSlope, "reluSlope": reluSlope, "tanhSlope": tanhSlope, "z": z})


if __name__ == "__main__":
    run(derive_iv03, DEFAULT_IV03)
Read the validation and JSON helpers
Read the complete executable Python / NumPy source

This is the actual reference file, imported directly from the repository. Comments explain each operation. It is provided for later execution; no validation run is claimed.

"""Small serialization/validation helpers for the five standalone references.

Run each ivNN.py from its path; this sibling module is then on Python's import
path. This module supplies no neuron, matrix multiplication or loss algorithm.
"""
import argparse
from functools import wraps
import json
import sys
import numpy as np


class ParseFault(ValueError):
    """Owned JSON syntax/profile failure, separate from numerical validation."""


_JSON_INT = int


def _members(pairs):
    value = {}
    for key, member in pairs:
        if key in value:
            raise ParseFault("Duplicate JSON object members are not allowed.")
        value[key] = member
    return value


def _constant(token):
    raise ParseFault(f"Nonstandard JSON constant {token} is not allowed.")


def _integer(token):
    if token == "-0":
        return -0.0
    try:
        return _JSON_INT(token)
    except ValueError as error:
        if type(error) is not ValueError:
            raise
        raise ParseFault("JSON integer exceeds the interpreter's conversion capacity.") from error


class NumericalFault(ValueError):
    def __init__(self, code, reason):
        super().__init__(reason)
        self.code = code


def finite(value, label):
    if isinstance(value, bool) or not isinstance(value, (int, float, np.integer, np.floating)):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    try:
        value = np.float64(value)
    except (ValueError, OverflowError) as error:
        raise NumericalFault("NONFINITE", f"{label} must be finite.") from error
    if not np.isfinite(value):
        raise NumericalFault("NONFINITE", f"{label} must be finite.")
    return value


def validate(state, defaults, bounds=None):
    if type(state) is not dict:
        raise NumericalFault("INVALID_INPUT", "State must be a scalar-field object.")
    values = {}
    for key in defaults:
        minimum, maximum = (bounds or {}).get(key, (-100, 100))
        value = finite(state.get(key), key)
        if value < minimum or value > maximum:
            raise NumericalFault("INVALID_INPUT", f"{key} must be between {minimum} and {maximum}.")
        values[key] = value
    if any(key not in defaults for key in state):
        raise NumericalFault("INVALID_INPUT", "Only the declared scalar fields are supported.")
    return values


def choice(value, allowed, label):
    if not float(value).is_integer() or value not in allowed:
        raise NumericalFault("INVALID_INPUT", f"{label} must be one of {allowed}.")


def guarded(derive):
    @wraps(derive)
    def call(state):
        try:
            return derive(state)
        except NumericalFault as error:
            return {"status": "unavailable", "code": error.code, "reason": str(error)}
        except (OverflowError, FloatingPointError) as error:
            return {"status": "unavailable", "code": "NONFINITE", "reason": str(error)}
        except (TypeError, AttributeError) as error:
            return {"status": "unavailable", "code": "UNAVAILABLE", "reason": str(error)}
    return call


def tensor(identifier, shape, axes, values, provenance):
    if not 1 <= len(shape) <= 4 or len(shape) != len(axes) or any(not isinstance(axis, str) or not axis for axis in axes) or len(set(axes)) != len(axes):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: name each axis uniquely.")
    count = 1
    for dimension in shape:
        if isinstance(dimension, bool) or not isinstance(dimension, int) or not 1 <= dimension <= 64:
            raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier}: invalid dimension.")
        count *= dimension
    if count > 4096:
        raise NumericalFault("UNSUPPORTED_SIZE", f"{identifier}: at most 4096 elements are supported.")
    if count != len(values):
        raise NumericalFault("SHAPE_MISMATCH", f"{identifier}: storage does not match shape.")
    return {"id": identifier, "shape": list(shape), "axes": list(axes), "dtype": "float64",
            "values": [float(finite(value, identifier)) for value in values],
            "provenance": provenance, "precision": 8}


def step(identifier, label, equation, explanation, inputs, outputs, state=None):
    record = {"id": identifier, "label": label, "equation": equation, "explanation": explanation,
              "inputs": {key: float(value) for key, value in inputs.items()},
              "outputs": {key: float(finite(value, key)) for key, value in outputs.items()}}
    if state is not None:
        record["state"] = {key: float(value) for key, value in state.items()}
    return record


def result(tensors, steps, outputs):
    for operation in steps:
        for key, value in operation["outputs"].items():
            tensors.append(tensor(f'{operation["id"]}.{key}', [1, 1], ["scalar_row", "scalar_column"],
                                  [value], f'{operation["id"]}: {operation["equation"]}'))
    return {"status": "defined", "tensors": tensors, "steps": steps,
            "outputs": {key: float(value) for key, value in outputs.items()}}


def run(derive, defaults):
    """Later owner CLI: ivNN.py [complete JSON state | - for stdin]."""
    parser = argparse.ArgumentParser(description=derive.__doc__)
    parser.add_argument("state", nargs="?")
    args = parser.parse_args()
    if args.state is not None:
        source = sys.stdin.read() if args.state == "-" else args.state
        try:
            state = json.loads(source, object_pairs_hook=_members, parse_constant=_constant, parse_int=_integer)
        except (json.JSONDecodeError, ParseFault) as error:
            output = {"status": "unavailable", "code": "INVALID_INPUT", "reason": str(error)}
        else:
            output = derive(state)
    else:
        state = dict(defaults)
        output = derive(state)
    print(json.dumps(output, allow_nan=False, separators=(",", ":")))

Different JavaScript and NumPy implementations of transcendental functions may differ in low floating-point bits. Parity validation needs justified tolerances, not a claim that every decimal representation must be identical. The exact origin values above remain independent hand-derived expectations.

Use the lab questions to identify what a slope means, calculate ReLU’s output and sigmoid’s derivative, predict tail behavior, and reject a false derivative claim at the kink. For background, revisit the chain rule and the artificial neuron.

  • Activation outputs and derivatives answer different questions.
  • ReLU has two smooth branches and no unique derivative at zero.
  • Stable sigmoid evaluation avoids unnecessarily large exponential intermediates.
  • Floating-point endpoint saturation must be distinguished from analytic behavior.

Next, we combine two hidden activations with an output layer and trace a complete multilayer forward pass, keeping every parameter and tensor shape visible.