Section 6.3

Activation Functions

The non-linear "kink" that lets neural networks bend, fold and curve through data — without it, a 100-layer network is just one matrix multiplication.

18 min read Intermediate 2 interactive demos

Why Non-Linearity Is Everything

Imagine you stack 100 linear elastic springs end-to-end. The combined response is still a single straight line — just with a different slope. No matter how many you add, you can never reproduce the curved load–deformation behavior of a real bolted connection or a yielding rebar.

The exact same thing happens with neural networks. A linear layer computes $z = Wx + b$. If you stack two linear layers, you get $W_2(W_1 x + b_1) + b_2 = (W_2 W_1)x + (W_2 b_1 + b_2)$ — still linear. Without something nonlinear in between, depth gives you zero extra capacity.

The core insight

An activation function is a small, fixed, nonlinear function applied element-wise after every linear layer. It is what allows a deep network to approximate curves, bends, thresholds, oscillations — anything but a hyperplane.

Civil engineering analogy

An activation function is the load–deformation curve of a structural connector. A linear-elastic spring (no activation) only scales force. A bolt with a yield plateau behaves like ReLU. A rubber bushing with smooth stiffening behaves like tanh. A friction damper with a dead-zone resembles a rectified function. Different connectors suit different load conditions — and different activations suit different problems.

Rule of thumb: every hidden layer in a modern neural network has an activation function. The only layer that often has none is the very last one (for regression).

Sigmoid — The Original

The sigmoid (also called the logistic function) was the dominant activation in the 1980s and 90s. It squashes any real number into the open interval $(0, 1)$, which makes it look like a smoothed step function.

sigmoid
sigma(x) = 1 / (1 + exp(-x))

sigma'(x) = sigma(x) * (1 - sigma(x))     # max value is 0.25 at x=0

What sigmoid is good for

  • The final layer of a binary classifier — the output is naturally a probability.
  • Gates inside LSTM / GRU recurrent cells, where you need a value between 0 and 1.
  • Any place you need a smooth, differentiable on/off switch.

What sigmoid is bad at

  • Vanishing gradients. The maximum slope is $0.25$. Multiply that through 10 layers and you get $0.25^{10} \approx 10^{-6}$. Early layers stop learning.
  • Not zero-centered. All outputs are positive, which biases gradient updates and slows training.
  • Saturates for $|x| > 5$ — gradient is essentially zero there.

Tanh — Sigmoid's Better Sibling

The hyperbolic tangent has the same S-shape as sigmoid but is rescaled to the range $(-1, 1)$ and is symmetric about the origin.

tanh
tanh(x) = (exp(x) - exp(-x)) / (exp(x) + exp(-x))
        = 2 * sigma(2x) - 1

tanh'(x) = 1 - tanh(x)^2     # max value is 1.0 at x=0

Because tanh is zero-centered, gradient flow through it is more balanced — updates can push weights either up or down naturally. Its peak derivative of $1.0$ is also four times larger than sigmoid's, which mitigates (but does not eliminate) the vanishing gradient problem.

Tanh is still the default activation inside recurrent cells (vanilla RNNs, parts of LSTMs and GRUs) because the bounded output keeps the recurrent state from exploding.

ReLU — The Workhorse

The Rectified Linear Unit is almost embarrassingly simple, and yet it is the activation function that made modern deep learning practical.

relu
relu(x) = max(0, x)

relu'(x) = 1  if x > 0
         = 0  if x < 0
         = undefined at x = 0   (use 0 in practice)

Why ReLU dominated 2012–2018

  • No vanishing gradient on the positive side. The derivative is exactly $1$, so signal flows unattenuated through deep stacks.
  • Sparsity. Roughly half the neurons output exactly zero, which is computationally cheap and acts as implicit regularization.
  • Trivially cheap. A single comparison — no exponentials, no divisions.

CE analogy: a one-way damper

ReLU is the activation equivalent of a tension-only brace: in tension it transmits load linearly, in compression it does nothing. Sparse, simple, and effective — exactly the properties you want from a deep-stack building block.

The dying ReLU problem

If a neuron's pre-activation is consistently negative, its gradient is exactly zero, so its weights never update again. The neuron is permanently stuck at zero output — "dead". A bad weight initialization or too high a learning rate can kill 30–40% of neurons in a layer in the first few epochs.

Leaky ReLU & Friends

The fix for dying ReLU is obvious: don't let the negative side be exactly flat.

leaky_relu
leaky_relu(x) = x        if x >= 0
              = 0.01 * x if x < 0

# Parametric ReLU (PReLU): the slope alpha is learned
# Randomized ReLU (RReLU):  alpha sampled randomly during training

With a small negative slope (typically $0.01$), gradients can still flow when the input is negative, so neurons can recover from bad initializations.

The modern smooth family

  • ELU (Exponential Linear Unit): $x$ for $x \ge 0$, $\alpha(e^x - 1)$ for $x < 0$. Smooth, mean-centered.
  • SELU: a self-normalizing variant that keeps activations zero-mean and unit-variance.
  • Swish / SiLU: $x \cdot \sigma(x)$. Smooth, non-monotonic, used in EfficientNet and many modern CNNs.
  • GELU: $x \cdot \Phi(x)$ where $\Phi$ is the Gaussian CDF. A "soft" ReLU that lets small negative values through probabilistically.
  • Mish: $x \cdot \tanh(\text{softplus}(x))$. Empirically strong on vision tasks.
GELU dominates Transformers. Every major large language model — GPT, BERT, T5, LLaMA — uses GELU (or its smooth cousin SwiGLU) as the feed-forward activation.

Softmax — The Output for Many Choices

Softmax is special: it acts on a vector, not on individual scalars. It is used as the final activation of a multi-class classifier to convert raw scores ("logits") into a proper probability distribution.

softmax
softmax(z)_i = exp(z_i) / sum_j exp(z_j)

# Properties:
#   - every output is in (0, 1)
#   - all outputs sum to exactly 1
#   - the largest logit gets the largest probability
#   - "soft" because it's a smooth approximation of argmax

For example, for a soil classifier outputting logits $z = [2.0,\; 1.0,\; 0.1]$ for {clay, silt, sand}, softmax gives roughly $[0.66,\; 0.24,\; 0.10]$ — a 66% probability the sample is clay.

Numerical stability: always subtract $\max(z)$ from every logit before exponentiating. Mathematically identical, but prevents $e^{1000}$ overflow.

Demo 1 — Activation Function Explorer

Toggle activation functions on and off and overlay them on a single set of axes. Hover the canvas to read off exact $f(x)$ and $f'(x)$ values at any point. Toggle the dashed derivative overlay to see why some activations vanish in deep networks.

Hover the plot to read values…

The Vanishing Gradient Problem

Backpropagation works by multiplying derivatives along the chain rule. If every layer's local gradient is less than $1$, the product shrinks exponentially with depth.

Sigmoid's maximum derivative is $0.25$. Through 10 layers: $0.25^{10} \approx 9.5 \times 10^{-7}$. The first layer receives a gradient signal a million times weaker than the last layer. It barely learns.

ReLU's derivative is exactly $1$ on the positive side. Through 10 layers: $1^{10} = 1$. The first layer learns at the same rate as the last. This is, in a single sentence, why deep learning works.

See it for yourself

The demo below pushes a unit gradient backward through 10 layers and shows the surviving magnitude per layer. Switch the activation and watch the bars collapse (sigmoid) or stay healthy (ReLU).

Demo 2 — Vanishing Gradient Through 10 Layers

Each bar is the gradient magnitude reaching that layer during backprop, starting from a unit gradient at the output. Press Run backprop to animate the signal collapsing (or surviving) through the depth of the network.

Pick an activation and press Run backprop.

Selection Guide

After all the math, the practical decision is usually one of four options.

Hidden layers

Default to ReLU for CNNs and most MLPs. Use GELU for Transformers and modern language models. Try Leaky ReLU if you suspect dying neurons.

Output layer — binary classification

Use sigmoid with a single output unit. Combine with binary cross-entropy loss. Output is interpreted as $P(\text{class} = 1)$.

Output layer — multi-class classification

Use softmax with one unit per class. Combine with categorical cross-entropy loss. Output is a full probability distribution.

Output layer — regression

Use no activation (i.e. linear output). The network must be able to predict any real number — a positive bound from sigmoid or a floor from ReLU would distort the prediction.

Civil example. Predicting concrete compressive strength (regression) → linear output. Classifying soil into clay/silt/sand (multi-class) → softmax. Detecting whether a beam will fail under load (binary) → sigmoid. All hidden layers in between → ReLU.

Civil Engineering Application

Soil Stress-Strain Nonlinearity

Soil doesn't follow Hooke's law — its stress-strain curve is highly nonlinear. ReLU and its variants let neural networks model this elasto-plastic behavior naturally. Without activation functions, the network could only learn linear responses, missing the critical yield and hardening regions.

Flow Regime Detection

Sigmoid activation is perfect for detecting laminar vs turbulent flow transitions — the output smoothly transitions from 0 to 1 around the critical Reynolds number, just like real flow regime changes happen gradually rather than as a sharp switch.

Knowledge Check

1. Why do neural networks need a non-linear activation function?

  • To make computation faster.
  • Without it, stacking many linear layers collapses to a single linear transformation.
  • To convert outputs into probabilities.
  • To reduce overfitting.

2. Why does sigmoid cause vanishing gradients in deep networks?

  • Its output is bounded between 0 and 1.
  • It is not differentiable at zero.
  • Its maximum derivative is 0.25, so the gradient shrinks geometrically through layers.
  • It uses an exponential, which is computationally expensive.

3. What is the "dying ReLU" problem?

  • ReLU produces NaN values during training.
  • A neuron stuck with negative pre-activations has zero gradient and never updates again.
  • ReLU saturates for large positive inputs.
  • ReLU outputs are not zero-centered.

4. You are building a network to classify a soil sample as clay, silt, or sand. Which activation should the output layer use?

  • ReLU
  • Sigmoid
  • Linear (no activation)
  • Softmax

Summary

  • An activation function injects non-linearity. Without it, depth is meaningless.
  • Sigmoid and tanh saturate and cause vanishing gradients in deep stacks.
  • ReLU's derivative of $1$ on the positive side is what unlocked deep learning.
  • Leaky ReLU, ELU, GELU, Swish, Mish are smoother modern variants — GELU dominates Transformers.
  • Softmax produces a probability distribution and is the standard multi-class output.
  • Hidden → ReLU/GELU. Binary out → sigmoid. Multi-class out → softmax. Regression out → linear.
Mini case study

Picking an activation: NVIDIA Modulus PINNs for subsurface Darcy flow

Physics-informed neural networks (PINNs) replace expensive finite-element solvers for groundwater and contaminant-transport problems. NVIDIA Modulus (used by Sandia, NETL and BP for reservoir and CO₂ storage simulations) embeds a small MLP as the trial solution to Darcy’s equation. The choice of activation function turns out to dominate convergence — SiLU/swish trains, ReLU silently fails because its second derivative vanishes everywhere.

0Hidden layers
0Neurons per layer
0Speed-up vs FEM at inference
0Mean PDE residual (SiLU)

A PINN trains by minimising the residual of the PDE itself — for Darcy, that means second derivatives of the network output with respect to the input coordinates. ReLU’s second derivative is zero almost everywhere, so the residual gradient is zero and training stalls. The fix is choosing a smooth activation; the question is which.

“The activation isn’t a hyperparameter — it’s a constraint on what the network can represent.”

  • 5-layer 128-wide MLP mapping (x, y) → pressure head h(x,y).
  • Composite loss = PDE residual + boundary loss + data-misfit (sparse well measurements).
  • Activation sweep — ReLU, tanh, Sigmoid, SiLU/swish, GELU, sin (SIREN) — all other hyperparameters fixed.
Final PDE residual on a 2-D Darcy benchmark (lower is better)

ReLU stalls (zero second derivative); tanh works but saturates; SiLU and sin activations dominate — both have smooth, non-vanishing higher-order derivatives.

  • SiLU + GELU drove residuals below 3% — usable for CO₂ plume migration forecasts.
  • SIREN (sin) wins on high-frequency permeability fields where SiLU still smears the front.
  • 1000× inference speed-up vs the FEM baseline once trained — the reason Modulus is in production.
  • Match activation to derivative order. If your loss touches second derivatives, ReLU is mathematically unable to learn.
  • SiLU is the safe default for most modern MLPs — smooth, non-saturating, free GELU-like benefits.
  • SIREN unlocks high-frequency signals — useful for fracture-network and contaminant-front problems.