Chapter 8 of 42 · ~28 min read & lab+75 XP
Chapter 8 · Deep Learning

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!

Why ML Engineers & Data Scientists Actually Need This

Choosing the wrong activation function can make a 10-layer neural network completely refuse to learn — even with perfect code and data!

ML / AI Engineer

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!

Data Scientist

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.

Interview & Debug Edge

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!'

Step 0 · Test Your Gut Before Any Math!

What is the MAXIMUM possible value of the Sigmoid derivative σ'(x) anywhere on the entire real number line (−∞, +∞)?

What You Will Master in This Chapter
  • 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
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 4
σ(x)Say aloud:“Sigmoid (Logistic) function”
Plain-English Meaning
Squashes any real number (−∞, +∞) smoothly into probability range (0, 1)
Everyday Example
1 / (1 + e⁻ˣ)
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

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

Everyday Story First (Zero Math Yet!)

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⁻¹⁵!

Sigmoid σ(x) vs. Derivative σ'(x) = σ(x)(1 − σ(x)): Why Deep Sigmoid Nets Vanish!Dead TailDead Tailmax σ'(0) = 0.2510-Layer Chain Rule Collapse0.25¹⁰ = 0.00000095Even at the BEST point (x=0),gradients shrink 4× per layer!Use Sigmoid ONLY for binary output!
Sigmoid's fatal flaw for deep nets: its derivative σ'(x) peaks at just 0.25 and collapses to ~0.00 in the flat saturation tails — starving earlier layers of gradients!

Exact Derivative of Sigmoid (Memorize This 3-Line Derivation!)

σ(x)=11+e−x=(1+e−x)−1\sigma(x) = \frac{1}{1 + e^{-x}} = (1 + e^{-x})^{-1} Differentiating with the chain rule: σ′(x)=−(1+e−x)−2(−e−x)=11+e−x⋅e−x1+e−x=σ(x)(1−σ(x))\sigma'(x) = -(1 + e^{-x})^{-2}(-e^{-x}) = \frac{1}{1+e^{-x}} \cdot \frac{e^{-x}}{1+e^{-x}} = \sigma(x)\big(1 - \sigma(x)\big)

  • Problem #1 (Vanishing Gradients): Since 0<σ(x)<10 < \sigma(x) < 1, the maximum of p(1−p)p(1-p) occurs at p=0.5p = 0.5 (x=0x = 0), giving σ′(0)=0.25\sigma'(0) = \mathbf{0.25}. In the tails (∣x∣>4|x| > 4), σ′(x)<0.018\sigma'(x) < 0.018 — killing gradients!
  • Problem #2 (Not Zero-Centered): Because σ(x)>0\sigma(x) > 0 ALWAYS, every input entering the next layer is strictly positive. That forces the weight gradients ∂L∂wi=∂L∂z⋅ai\frac{\partial L}{\partial w_i} = \frac{\partial L}{\partial z} \cdot a_i for a neuron to be all positive or all negative together, causing inefficient zig-zagging optimization!
Formula Anatomy · Click Any Colored Piece to Decode It
Sigmoid Derivative: σ'(x) = σ(x) · (1 − σ(x))

Click each term to see why high confidence kills learning speed

Neuron Output

Close to 1.0 when x is very positive; close to 0.0 when x is very negative.

In our example: σ(5) = 0.9933
Put it together with real numbers: At x = 0: 0.5 × 0.5 = 0.25 (peak). At x = 6: 0.9975 × 0.0025 = 0.0025 (100× weaker!).
Mini-Lab • Vanishing Derivative Explorer

Drag Input x = 0.0 into the Saturation Tail & Watch Gradient Die

σ'(x) = 0.2500
Output σ(x)
0.5000
Local Slope σ'(x)
0.2500
After 10 Layers
9.5e-7

2. Tanh(x): Zero-Centered Symmetry & 4× Stronger Gradients

Everyday Story First (Zero Math Yet!)

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(x) ∈ (−1, +1) vs. Sigmoid(x) ∈ (0, 1): Zero-Centered & 4× Stronger Slope!— tanh(x) = 2σ(2x) − 1• Zero-centered mean ≈ 0• Peak derivative tanh'(0) = 1.0!-- σ(x): Always positive (>0)Forces all weights to update insame sign → zig-zagging GD!
Tanh is zero-centered (−1 to +1) with a 4× steeper peak slope (1.0 vs. 0.25), avoiding Sigmoid's all-positive output zig-zagging — yet it still saturates at large |x|.

Tanh Formula, Identity & Derivative

tanh⁡(x)=ex−e−xex+e−x=2σ(2x)−1,tanh⁡′(x)=1−tanh⁡2(x)\tanh(x) = \frac{e^x - e^{-x}}{e^x + e^{-x}} = 2\sigma(2x) - 1, \qquad \tanh'(x) = 1 - \tanh^2(x)

  • 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 x=0x = 0, tanh⁡′(0)=1−0=1.0\tanh'(0) = 1 - 0 = \mathbf{1.0} (vs. Sigmoid's 0.25)!
  • Remaining Flaw: Just like Sigmoid, when ∣x∣>3|x| > 3, tanh⁡(x)→±1\tanh(x) \to \pm 1 and tanh⁡′(x)→0\tanh'(x) \to 0 — so deep Tanh networks STILL suffer from vanishing gradients (which ReLU solves in Chapter 4!).
Pause & Check · Quick Intuition Pulse

Why is tanh strictly preferred over sigmoid inside LSTM/RNN candidate states?

3. Softmax & Temperature Scaling: Multi-Class Output Probabilities

Everyday Story First (Zero Math Yet!)

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(z / T): Converting Raw Logits [3.0, 1.5, 0.5] into ProbabilitiesSharp (T = 0.5)95%Cat5%Dog0.5%FoxStandard (T = 1.0)77%Cat17%Dog6%FoxFlat (T = 3.0)49%Cat30%Dog21%Fox
Softmax turns raw scores (logits) into a clean probability distribution summing to 1.0; Temperature T < 1 sharpens winners while T > 1 flattens probabilities.

Softmax Formula + Temperature TT + Stability Trick

Softmax(z)i=ezi/T∑j=1Kezj/T=e(zi−m)/T∑j=1Ke(zj−m)/T,m=max⁡jzj\text{Softmax}(\mathbf{z})_i = \frac{e^{z_i / T}}{\sum_{j=1}^K e^{z_j / T}} = \frac{e^{(z_i - m)/T}}{\sum_{j=1}^K e^{(z_j - m)/T}}, \qquad m = \max_j z_j

  • Shift-Invariance: Subtracting m=max⁡(z)m = \max(\mathbf{z}) leaves the math 100% identical while preventing exp(1000) = inf → NaN overflow!
  • Temperature TT: T<1T < 1 makes the distribution sharper (more confident/greedy); T>1T > 1 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"!).
Walk Through With Me · Interactive Worked Example

Hand-Compute Softmax With Max-Shift Stability

Compute Softmax for raw logits z = [1002, 1000, 1000] without overflowing float32!

1Step 1 — Subtract m = max(z) = 1002Step 1 / 3

Shifted logits: z − m = [0, −2, −2]. Zero risk of exp(1002) = inf!

Teacher's Note: The largest shifted logit is ALWAYS 0, so exp(0) = 1.0.
Try It YourselfWarm-Up

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?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

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))!

Interactive Visual Lab
Lab Challenge: In the dual-panel activation animation below, switch between Sigmoid and Tanh and watch the glowing gold tangent flatten out in the saturation tails while the derivative bell curve drops to 0!
Interactive Animation • Classic Activations

Synchronized Activation Curve f(x) & Live Tangent Derivative f'(x)

Watch the glowing gold tangent flatten out in the saturation tails — starving gradients!

f(x) = σ(x)Derivative f'(x) (Gradient Multiplier)
0%
x = -5.0 | slope = 0.007
At x = -5.00: output f(x) = 0.007, tangent slope f'(x) = 0.0066 — SATURATED! Gradient is nearly dead!
Intuition Takeaway: Sigmoid (0, 1) and Tanh (−1, +1) both saturate in the tails and starve deep hidden layers of gradients — keep Sigmoid/Softmax for output probabilities & gates, and unlock deep hidden layers with ReLU/GELU/SwiGLU in Chapter 4!
Where This Powers Real ML, Deep Learning & Generative AI

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.

Production NumPy & PyTorch Code Patterns
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))
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Putting nn.Softmax(dim=-1) before nn.CrossEntropyLoss() in PyTorch.
Best Practice: Pass raw logits directly to CrossEntropyLoss (and BCEWithLogitsLoss); only apply Softmax/Sigmoid at inference time when displaying probabilities!
Trap #2: Using Softmax for multi-label classification where multiple classes can be active simultaneously.
Best Practice: Softmax forces probabilities to sum to 1 (mutually exclusive); use independent Sigmoids + BCEWithLogitsLoss for multi-label!
Trap #3: Forgetting Sigmoid's non-zero-centered zig-zag gradient issue (only mentioning vanishing gradients).
Best Practice: Mention BOTH: (1) peak derivative 0.25 + flat tails → vanishing gradients, AND (2) strictly positive outputs → zig-zagging weight updates!
Trap #4: Computing naive torch.exp(z) / torch.exp(z).sum() without subtracting z.max().
Best Practice: Large logits (z > 88 in float32) overflow exp(z) to inf, producing inf/inf = NaN.
Chapter Mastery Check (+75 XP)
Score: 0 / 5
1Which mathematical trick prevents exp(z) overflow inside Softmax without changing the output?
2When should you use Softmax instead of independent Sigmoids at the output layer?
3What happens to Softmax probabilities when you lower Temperature T from 1.0 to 0.2?
4Why do all-positive Sigmoid outputs cause zig-zagging weight updates in the next layer?
5What is the exact derivative of tanh(x)?

Apply What You Learned — Solve Matching Coding Problems