Deep Learning Slides 📂 Introduction · 5 of 18 44 min read

Activation Functions in Deep Learning: Sigmoid to GELU

Without activation functions, a hundred-layer network collapses into a single straight line. This visual guide walks the whole family — sigmoid, tanh, ReLU, Leaky ReLU, ELU, GELU, and softmax — with animated curves, the vanishing-gradient and dying-ReLU traps, and a clear map of which to use when.

Activation Functions in Deep Learning

Strip the activations out of a neural network and a hundred layers collapse into one straight line. These little non-linear curves are what let networks bend, twist, and actually learn. Meet the whole family.
Why Non-Linearity Vanishing Gradients ReLU & GELU Softmax

Press Next → or use ← → arrow keys

Section 01

Why Neurons Must Be Non-Linear

Stack a hundred panes of clear glass and light still travels straight through — the stack does nothing a single pane couldn't. Linear layers are the same: a linear function of a linear function is still linear. Without a non-linear activation between them, a 100-layer network is mathematically just one layer.
Linear — one straight cut Non-linear — curved boundary
🔑
Two jobs, one function

A good activation must (1) be non-linear so depth adds power, and (2) be differentiable almost everywhere so gradients can flow backward during training.

Section 02

Sigmoid — The Classic Squash

The sigmoid squeezes any input into a smooth (0, 1) range — perfect for probabilities. It ruled early neural nets, but it hides a costly flaw.

Sigmoid σ(z)=1/(1+e⁻ᶻ) z
Formulaσ(z) = 1 / (1 + e⁻ᶻ)
Range(0, 1)
Max gradientσ′(z) ≤ 0.25
Zero-centred?No
⚠️
Two problems baked in

Its output is always positive, so gradient updates zig-zag. And its slope never exceeds 0.25 — so in a deep stack, gradients shrink fast. Today sigmoid survives only on binary output neurons.

Section 02

tanh — Sigmoid, Recentred

Tanh has the same S-shape but spans (−1, +1), so its outputs are zero-centred — gradients flow more cleanly than sigmoid. Its slope can reach 1.0, four times sigmoid's.

tanh(z) z
Formula(eᶻ − e⁻ᶻ)/(eᶻ + e⁻ᶻ)
Range(−1, +1)
Max gradienttanh′(z) ≤ 1.0
Zero-centred?Yes
🔎
Better, but not cured

Tanh still saturates: push |z| large and the curve flattens, so the gradient still dies at the extremes. The saturation trap is next.

Section 02

The Saturation Trap

At the flat ends of a sigmoid or tanh curve, a big change in input barely nudges the output — like a volume knob jammed at the top. The gradient there is nearly zero. In a 50-layer network that silence echoes backward and nothing moves.
gradient × 0.25 at every layer — vanishing backward ← grad 1.00.250.060.016≈0
🧮
The math is brutal

Each layer can multiply the gradient by ≤ 0.25. After 10 layers that's 0.25¹⁰ ≈ 0.000001 — the early layers effectively stop learning. This single problem is why ReLU took over.

Section 03

ReLU — The Revolution

ReLU is almost embarrassingly simple: keep positives, zero the rest. Yet it trains up to 6× faster than sigmoid and sparked the 2010s deep-learning boom.

ReLU(z)=max(0,z) z
FormulaReLU(z) = max(0, z)
Range[0, ∞)
Gradient (z > 0)exactly 1 — no vanishing
Gradient (z < 0)0 — dead zone
🚀
Why it's fast

For positive inputs the gradient is exactly 1, so it passes backward untouched — no saturation, no shrinkage. It's also just a comparison, so it's cheap to compute at scale.

Section 03

ReLU's Fatal Flaw — Dying Neurons

ReLU outputs 0 for any negative input — and its gradient there is also 0. If a neuron's weights drift so it always receives negatives, it outputs 0 forever and never updates again. It's dead: no signal, no learning, no coming back.
0Gradient in the negative zone — no recovery
40–50%Neurons can die with a high learning rate
>20%Dead rate = red flag; switch activation
💀
Watch the dead-neuron rate

Aggressive learning rates or poor initialisation can kill nearly half a layer. The fixes all share one idea: let a little signal leak through on the negative side.

Section 04

Leaky ReLU & ELU — Reviving the Dead

Both keep ReLU's positive side but replace the flat zero with a gentle negative slope, so neurons keep a pulse.

Leaky ReLU max(αz, z) z
ELU z
💧
Leaky ReLU · max(αz, z)

A tiny slope (α ≈ 0.01) on the negatives means gradients never fully vanish. Cheap and effective — a favourite for CNNs and GANs.

🌊
ELU · α(eᶻ − 1) for z < 0

A smooth exponential curve gives near-zero-centred outputs and a clean gradient everywhere — great for deep MLPs, at a small compute cost.

Section 04

GELU — The Transformer's Choice

GELU multiplies each input by the probability it's positive under a Gaussian: f(z) = z · Φ(z). The result is a smooth curve that dips slightly below zero before rising — a soft, probabilistic gate.

GELU z·Φ(z) z
Formulaz · Φ(z)
Min value≈ −0.17 near z = −0.75
Smooth?Yes — everywhere
Used inBERT, GPT-2/3/4
🤖
Why transformers love it

Its smooth, near-zero-centred shape produces cleaner gradient flow through residual connections and attention than ReLU's hard kink — which is why every major LLM uses it by default.

Section 04

The ReLU Family — Side by Side

ActivationDying neuronsZero-centredSmoothCostBest for
ReLUYes — commonNoNo (kink)Very lowCNNs, fast baseline
Leaky ReLUNoNoNoVery lowCNNs, GANs
ELUNoYes (≈)YesMediumDeep MLPs, regression
GELUNoYes (≈)YesMediumTransformers, LLMs
🧭
The trend is clear

As you move down the table you trade a little compute for smoother, zero-centred, always-alive neurons. For anything deeper than a few layers, that trade is almost always worth it.

Section 05

Softmax — Turning Scores into Probabilities

Softmax takes a vector of raw scores (logits) and turns them into probabilities that sum to 1 — the standard final layer for multi-class classification.

logits [3.2, 1.8, 0.5] → softmax 70.6%17.6%11.8% class Aclass Bclass C
Raw votes (400, 300, 300) become shares (40%, 30%, 30%). The leader takes the most probability mass, but the losers are never fully silenced — every class keeps a sliver.
🚫
Never in hidden layers

softmax(z)ᵢ = eᶻⁱ / Σⱼ eᶻʲ forces neurons into a zero-sum competition. In hidden layers that destroys the independent signal each neuron carries — so it belongs only in the output.

Section 06

All Activations From Scratch

Every activation is a one-liner in NumPy:

import numpy as np

def sigmoid(z):   return 1 / (1 + np.exp(-z))
def tanh(z):      return np.tanh(z)
def relu(z):      return np.maximum(0, z)
def leaky_relu(z, alpha=0.01): return np.where(z > 0, z, alpha * z)
def elu(z, alpha=1.0):       return np.where(z > 0, z, alpha * (np.exp(z) - 1))
def gelu(z):
    return 0.5 * z * (1 + np.tanh(np.sqrt(2/np.pi) * (z + 0.044715 * z**3)))
def softmax(z):
    e = np.exp(z - np.max(z))     # subtract max for stability
    return e / e.sum()

print(softmax(np.array([3.2, 1.8, 0.5])))   # [0.706 0.176 0.118]
🛡️
The softmax stability trick

Subtracting max(z) before exponentiating prevents overflow on large logits without changing the result — always do it.

Section 07

Activations in a Real Network

A modern deep MLP: GELU in the hidden layers, LayerNorm between them, and raw logits at the output.

import torch.nn as nn

class DeepMLP(nn.Module):
    def __init__(self, in_dim, hidden, out_dim):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(in_dim, hidden),
            nn.GELU(),                  # ← modern choice
            nn.LayerNorm(hidden),
            nn.Linear(hidden, hidden),
            nn.GELU(),
            nn.LayerNorm(hidden),
            nn.Linear(hidden, out_dim), # raw logits — no softmax here
        )
    def forward(self, x): return self.net(x)
🛑
Never put Softmax before CrossEntropyLoss

nn.CrossEntropyLoss already applies log-softmax internally. Adding your own nn.Softmax() applies it twice — corrupting gradients and causing numerical instability.

Section 08

How to Choose — The Decision Map

SituationUse this
Output layer — multi-classSoftmax
Output layer — binarySigmoid
Transformers / LLMsGELU
CNNs / visionReLU → Leaky ReLU if >10% die
Deep MLP / tabularELU or GELU
GAN discriminatorLeaky ReLU (α = 0.2)
When in doubt

Use GELU in hidden layers and nn.CrossEntropyLoss (which handles softmax) for classification. It's the setup behind every major transformer and almost always beats ReLU beyond four layers.

Section 09

6 Golden Rules

  Activation cheat-sheet
1No sigmoid/tanh in deep hidden layers. They saturate — reserve sigmoid for binary outputs.
2Monitor the dead-neuron rate. Above 20% zero activations, switch to Leaky ReLU or lower the learning rate.
3Softmax only at the output. In hidden layers its zero-sum competition destroys independent signals.
4In PyTorch, output raw logits. CrossEntropyLoss handles log-softmax; don't add softmax yourself.
5GELU is the modern default for deep networks — smooth, zero-centred, great gradient flow.
6Match the initialisation. ReLU → He (Kaiming); sigmoid/tanh → Glorot (Xavier).
🚀
The bend that makes learning possible

From sigmoid to GELU, the whole story is about keeping gradients alive as networks grow deep. Choose the curve well and everything downstream trains faster and further.