Before You Start
- Required knowledge
- Neural-network forward/backward passes, variance, and NumPy matrix operations.
- Libraries used
- NumPy
- Dataset and source
- Generated Gaussian inputs and weight matrices; no external training dataset.
- Expected output
- Activation and initialization comparisons measuring signal and gradient propagation.
Lesson Videos
Activation Functions & Initialization β Theory & Concepts
Read this before attempting the exercises. Choosing the right activation and initialization is crucial for training deep networks successfully.
1. Why Activations Matter
Without nonlinear activations, a deep network collapses to a single linear layer:
Layer 1: hβ = Wβx + bβ
Layer 2: hβ = Wβhβ + bβ = Wβ(Wβx + bβ) + bβ = (WβWβ)x + (Wβbβ + bβ)
> Just another linear function! No benefit from depth.
2. Activation Function Zoo

ReLU (Rectified Linear Unit)
f(x) = max(0, x)
f'(x) = 1 if x > 0, 0 if x < 0
- βPros: Fast, no vanishing gradient for positive inputs, sparse activations
- βCons: Dead neurons (if input always negative, gradient is always 0)
Leaky ReLU
f(x) = max(Ξ±x, x) where Ξ± = 0.01
- βFixes dead neuron problem β small gradient for negative inputs
GELU (Gaussian Error Linear Unit)
f(x) = x Β· Ξ¦(x) where Ξ¦ is the standard normal CDF
- βUsed in Transformers (BERT, GPT)
- βSmooth approximation of ReLU with better gradient flow
Swish / SiLU
f(x) = x Β· Ο(x)
- βSelf-gated, smooth, used in EfficientNet and modern architectures
3. Weight Initialization
The Problem
Too small init: activations > 0 in deep layers (vanishing)
Too large init: activations > β in deep layers (exploding)
Even if forward activations look reasonable at first, bad initialization can still break training by causing gradients to shrink toward zero or blow up across depth.
Vanishing Gradients

When the local Jacobian factors are usually smaller than 1, the chain-rule product shrinks toward 0 as depth increases. Early layers then receive almost no learning signal.
Exploding Gradients

When the local Jacobian factors are usually larger than 1, the chain-rule product grows rapidly with depth. This makes optimization unstable and can lead to divergence or NaNs.
Summary
| Problem | Cause | Solution |
|---|---|---|
| Exploding gradients | Gradients become extremely large | β Gradient clipping |
| Vanishing gradients | Gradients become extremely small | β ReLU, residual connections, good initialization, batch normalization |

Xavier/Glorot Initialization (for sigmoid/tanh)
# Variance = 2 / (fan_in + fan_out)
W = np.random.randn(fan_in, fan_out) * np.sqrt(2.0 / (fan_in + fan_out))
He/Kaiming Initialization (for ReLU)
# Variance = 2 / fan_in
W = np.random.randn(fan_in, fan_out) * np.sqrt(2.0 / fan_in)
Rule of thumb: Use He init with ReLU, Xavier init with tanh/sigmoid.
4. Batch Normalization
Normalize activations within each mini-batch:
# During training:
mu = x.mean(axis=0) # batch mean
sigma = x.std(axis=0) # batch std
x_norm = (x - mu) / (sigma + eps)
out = gamma * x_norm + beta # learnable scale and shift
Benefits:
- βStabilizes training (less sensitive to initialization and learning rate)
- βActs as mild regularization
- βAllows higher learning rates
FAANG Interview Tip: BatchNorm has different behavior at train vs test time. At test time, it uses running statistics, not batch statistics.
5. Layer Normalization
Normalize across features (not across batch):
# LayerNorm: normalize each sample independently
mu = x.mean(axis=-1, keepdims=True)
sigma = x.std(axis=-1, keepdims=True)
x_norm = (x - mu) / (sigma + eps)
Used in: Transformers (BERT, GPT). Preferred over BatchNorm because it doesn't depend on batch size.
6. Practical Initialization in PyTorch
import torch.nn as nn
# He initialization (default for Conv2d and Linear with ReLU)
nn.init.kaiming_normal_(layer.weight, mode='fan_in', nonlinearity='relu')
# Xavier initialization
nn.init.xavier_uniform_(layer.weight)
# Zero bias
nn.init.zeros_(layer.bias)
Now you're ready to attempt the exercises. Switch to the Exercise tab and start coding!
Ready to practice?
Activation Functions & Initialization β Student Lab
Focus: implement activations + init schemes and empirically verify signal/gradient propagation across depth.
Section 0 β Setup
Weβll work with synthetic Gaussian inputs so we can isolate activation/init effects.
Activations
Section 1 β Activations
Task 1.1
Implement ReLU, tanh, and GELU (approx).
Task 1.2
Compare output mean/std on standard normal input.
Optional concept β Softplus
softplus(v) = log(1 + e^v)
Why it is used:
- βsmooth approximation of ReLU
- βavoids numerical instability with a stable implementation
- βuseful in logistic-loss derivations
Behavior:
- βif
vis very large positive,log(1 + e^v) β v - βif
vis very large negative,log(1 + e^v) β 0
So Softplus behaves like max(0, v) but smoothly.
Initialization schemes
Section 2 β Initialization schemes
Weβll initialize weight matrices for a linear layer: Y = X W (no bias).
Task 2.1
Implement:
- βnaive normal init with std=1
- βXavier normal init
- βHe normal init
Return a weight matrix of shape (fan_in, fan_out).
Forward signal propagation across depth
Section 3 β Forward signal propagation across depth
We simulate an L-layer network: X_{l+1} = act(X_l W_l)
Task 3.1
Write simulate_forward(X0, L, init_fn, act_fn) returning stats per layer.
We care about:
- βmean/std of activations
- βfor ReLU: fraction of zeros
- βfor tanh: saturation (
|a| > 0.95) and average local derivative
Task 3.2
Compare naive vs Xavier/He for depth L=50 using both ReLU and tanh.
Backward gradient propagation (toy)
Section 4 β Backward gradient propagation (toy)
We estimate gradient flow using a simple scalar loss:
- βForward: X_{l+1} = act(X_l W_l)
- βLoss: mean(X_L)
- βBackward (approx): propagate gradients using local Jacobians
This is not a full autodiff engine; itβs a controlled experiment to see gradient norms explode/vanish.
Task 4.1
Implement activation derivatives for ReLU and tanh.
Task 4.2
Simulate gradient norms across depth for different init schemes.