Activation Functions I: Classic Non-Linearities (Sigmoid, Tanh & Softmax)
Master the exact math, derivatives, and geometry of Sigmoid, Tanh, and Softmax — why Sigmoid's 0.25 peak derivative kills deep networks, and when you STILL use them today!
Choosing the wrong activation function can make a 10-layer neural network completely refuse to learn — even with perfect code and data!
Even though ReLU/GELU replaced Sigmoid inside hidden layers, Sigmoid, Tanh, and Softmax are STILL everywhere in modern AI: Sigmoid powers binary heads & LSTM/SwiGLU gates, Tanh powers LSTM cell candidates, and Softmax powers every LLM token distribution & Attention weight!
Understanding why Sigmoid outputs (0, 1) probabilities while Softmax enforces mutually exclusive probabilities summing to 1.0 prevents the #1 multi-label vs. multi-class modeling bug.
Classic Deep Learning interview triad: 'Derive the derivative of Sigmoid on the whiteboard, explain why Sigmoid causes vanishing gradients AND zig-zagging weight updates, and tell me when to use Sigmoid vs. Softmax at the output layer!'
What is the MAXIMUM possible value of the Sigmoid derivative σ'(x) anywhere on the entire real number line (−∞, +∞)?
- Derive σ'(x) = σ(x)(1 − σ(x)) and tanh'(x) = 1 − tanh²(x) cleanly from scratch
- Prove why Sigmoid causes Vanishing Gradients in deep hidden layers (0.25^10 ≈ 10⁻⁶) and non-zero-centered zig-zag updates
- Explain why Tanh beats Sigmoid in hidden layers & RNN gates (zero-centered, 4× steeper peak slope = 1.0) yet still saturates
- Use Softmax with Temperature T for multi-class output probabilities and understand the Max-Shift numerical stability trick
Think of an activation function as a dimmer switch on each neuron. Early researchers loved Sigmoid because it smoothly squashed wild numbers into a cozy 0 to 1 percentage. The catch? Once a neuron gets even slightly confident (x = +5 or x = −5), the dimmer switch hits its mechanical stop (saturation), its slope goes completely flat (0.006), and backpropagation can no longer nudge the neuron to fix its mistakes!
1. Sigmoid σ(x): Derivative Derivation & The Saturation Death Zone
Sigmoid is famous for two things: its gorgeous probability output (0, 1) and its catastrophic saturation tails. Drag x into the tails in the mini-lab below to watch a 10-layer gradient collapse to 10⁻¹⁵!
Exact Derivative of Sigmoid (Memorize This 3-Line Derivation!)
Differentiating with the chain rule:
- Problem #1 (Vanishing Gradients): Since , the maximum of occurs at (), giving . In the tails (), — killing gradients!
- Problem #2 (Not Zero-Centered): Because ALWAYS, every input entering the next layer is strictly positive. That forces the weight gradients for a neuron to be all positive or all negative together, causing inefficient zig-zagging optimization!
Click each term to see why high confidence kills learning speed
Close to 1.0 when x is very positive; close to 0.0 when x is very negative.
Drag Input x = 0.0 into the Saturation Tail & Watch Gradient Die
2. Tanh(x): Zero-Centered Symmetry & 4× Stronger Gradients
How do we fix Sigmoid's all-positive zig-zagging AND double its steepness? Stretch and shift Sigmoid down to live cleanly between −1 and +1: that gives the Hyperbolic Tangent tanh(x)!
Tanh Formula, Identity & Derivative
- Zero-Centered: Outputs average around
0, allowing next-layer weights to update smoothly in both positive and negative directions without zig-zagging! - 4× Steeper Peak: At , (vs. Sigmoid's
0.25)! - Remaining Flaw: Just like Sigmoid, when , and — so deep Tanh networks STILL suffer from vanishing gradients (which ReLU solves in Chapter 4!).
Why is tanh strictly preferred over sigmoid inside LSTM/RNN candidate states?
3. Softmax & Temperature Scaling: Multi-Class Output Probabilities
When classifying an image into 10 mutually exclusive classes (Cat vs. Dog vs. Fox...) or predicting the next token out of 128,000 vocabulary words, you need outputs that are all positive and sum to exactly 1.000! That's Softmax.
Softmax Formula + Temperature + Stability Trick
- Shift-Invariance: Subtracting leaves the math 100% identical while preventing
exp(1000) = inf → NaNoverflow! - Temperature : makes the distribution sharper (more confident/greedy); softens probabilities (more creative/diverse LLM sampling!).
- Multi-Class vs. Multi-Label Rule: Use Softmax when classes are mutually exclusive (exactly 1 winner). Use independent Sigmoids when multiple tags can be true simultaneously (e.g., a photo is BOTH "Outdoor" AND "Dog"!).
Hand-Compute Softmax With Max-Shift Stability
Compute Softmax for raw logits z = [1002, 1000, 1000] without overflowing float32!
Shifted logits: z − m = [0, −2, −2]. Zero risk of exp(1002) = inf!
exp(0) = 1.0.You are building a movie tagger where a single movie can be BOTH 'Action' AND 'Comedy' AND 'Sci-Fi' at the same time. Should the output layer use Softmax or independent Sigmoids?
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Because Sigmoid is STILL used every day for: (1) binary classification probabilities, (2) multi-label classification, (3) gating mechanisms (0 = block, 1 = let through) inside LSTMs, GRUs, Squeeze-and-Excitation CNNs, and modern SiLU/SwiGLU (x·σ(x))!
Synchronized Activation Curve f(x) & Live Tangent Derivative f'(x)
Watch the glowing gold tangent flatten out in the saturation tails — starving gradients!
LLM Next-Token Sampling
Every ChatGPT/Claude/Gemini word is sampled from Softmax(logits / Temperature) over 100k+ vocabulary tokens.
Multi-Label Medical & Content Tagging
Independent Sigmoid outputs predict 14 simultaneous chest X-ray conditions without forcing probabilities to sum to 1.
Gating in LSTMs & Attention
Sigmoid acts as a learned 0-to-1 valve controlling how much memory to forget or keep.
RL Policy Actions
Tanh bounds continuous robot torques cleanly into [−1, +1] action limits.
import torch
import torch.nn.functional as F
# 1. Numerically Stable Softmax from Scratch (Max-Shift Trick)
def stable_softmax(logits: torch.Tensor, temp: float = 1.0) -> torch.Tensor:
scaled = logits / temp
shifted = scaled - scaled.max(dim=-1, keepdim=True).values
exps = torch.exp(shifted)
return exps / exps.sum(dim=-1, keepdim=True)
# 2. Compare Sigmoid vs Tanh derivatives on PyTorch autograd
x = torch.tensor([-4.0, 0.0, 4.0], requires_grad=True)
y_sig = torch.sigmoid(x)
y_sig.sum().backward()
print("Sigmoid grads at [-4, 0, 4]:", x.grad) # [0.0177, 0.2500, 0.0177]
# Softmax with Temperature
logits = torch.tensor([[3.0, 1.5, 0.5]])
print("T=1.0:", stable_softmax(logits, temp=1.0).round(decimals=3))
print("T=0.5:", stable_softmax(logits, temp=0.5).round(decimals=3))
nn.Softmax(dim=-1) before nn.CrossEntropyLoss() in PyTorch.CrossEntropyLoss (and BCEWithLogitsLoss); only apply Softmax/Sigmoid at inference time when displaying probabilities!BCEWithLogitsLoss for multi-label!torch.exp(z) / torch.exp(z).sum() without subtracting z.max().z > 88 in float32) overflow exp(z) to inf, producing inf/inf = NaN.exp(z) overflow inside Softmax without changing the output?