S30 Logo
S30 AI Labwww.thes30.com
Back
#30

Activation Functions & Initialization

Hard🧠 Deep LearningW7 D1

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.

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

Activation techniques and their benefits

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

Vanishing gradients across depth

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

Exploding gradients across depth

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

ProblemCauseSolution
Exploding gradientsGradients become extremely largeβœ… Gradient clipping
Vanishing gradientsGradients become extremely smallβœ… ReLU, residual connections, good initialization, batch normalization

Initialization techniques and their benefits

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?

Python 3 β€” Notebook
0/5 solvedSubstack Notes
1
Dataset & Setup

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.

Loading editor...
1

Activations

2
Implement ReLU, tanh, and GELU (approx).
1

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 v is very large positive, log(1 + e^v) β‰ˆ v
  • ●if v is very large negative, log(1 + e^v) β‰ˆ 0

So Softplus behaves like max(0, v) but smoothly.

Loading editor...
2

Initialization schemes

3
Implement:
1

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

Loading editor...
3

Forward signal propagation across depth

4
Write `simulate_forward(X0, L, init_fn, act_fn)` returning stats per layer.

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.

Loading editor...
4

Backward gradient propagation (toy)

5
Implement activation derivatives for ReLU and tanh.
1

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.

Loading editor...

Need help? Share feedback