Skip to content

Module 05

Anurag Prasad edited this page Nov 9, 2026 · 10 revisions

Module 05 — Activation Functions, Neural Network Units and Expressivity

⬅️ Module 04 · 🗺️ Curriculum · 🏠 Home · Module 06 ➡️

Level: Beginner–Intermediate · Prerequisites: Module 02, Module 04 · Time: about 6–7 hours

On this page: Overview and learning goals · Beginner: the big picture · Core concepts and derivations · Worked example · Implementation · Advanced topics · Pitfalls and best practices · Conceptual questions and answers · Sources and further reading


Overview and learning goals

Stacking linear layers gives another linear layer. The activation function inserts the nonlinearity that makes depth worthwhile, shapes how gradients flow, and (at the output) defines what the network predicts. This module surveys the main activations, softmax, and the theory of what networks can represent: the universal approximation theorem and the benefits of depth.

After this module you should be able to:

  • compute activations and derivatives and identify saturation;
  • choose hidden and output activations for a task;
  • explain why composing linear maps is useless without nonlinearity;
  • state the universal approximation theorem, its intuition and limits;
  • explain why depth can be exponentially more efficient than width.

Beginner: the big picture

A neuron computes a pre-activation $z=\mathbf{w}^\top\mathbf{x}+b$ and then a post-activation $a=\phi(z)$. If $\phi$ were the identity, a 100-layer network would equal one matrix $W_{100}\cdots W_1$. A nonlinearity lets the network bend decision boundaries and build complex functions from simple pieces.

Common activation functions and their derivatives

Figure 5.1 — Activations (solid) and derivatives (dashed). Sigmoid/tanh saturate (derivative → 0 at both ends); ReLU does not saturate for $z>0$. Original figure (figures/make_figs_1.py).

flowchart LR
    X["Input x"] --> Z1["z1 = W1 x + b1 (pre-activation)"] --> A1["a1 = phi(z1) (post-activation)"]
    A1 --> Z2["z2 = W2 a1 + b2"] --> A2["a2 = softmax(z2)"] --> P["Probabilities"]
Loading

Core concepts and derivations

Linear, step and sigmoid units

Linear: $\phi(z)=z$ (regression outputs). Step: $\mathbf{1}[z\ge0]$, not differentiable (Module 04). Sigmoid $\sigma(z)=\frac1{1+e^{-z}}\in(0,1)$ with $\sigma'=\sigma(1-\sigma)\le\frac14$.

Tanh, ReLU and modern variants

$\tanh(z)=2\sigma(2z)-1\in(-1,1)$, zero-centred, $\tanh'=1-\tanh^2\le1$. ReLU $\max(0,z)$ is cheap, non-saturating for $z>0$ and induces sparse activations, but units with $z<0$ for all inputs get zero gradient ("dying ReLU"). Variants:

Name Formula Note
Leaky ReLU / PReLU $z$ if $z>0$ else $\alpha z$ $\alpha$ fixed / learned
ELU $z$ if $z>0$ else $\alpha(e^z-1)$ smooth negative side
GELU $z\,\Phi(z)$ $\Phi$ = Gaussian CDF; used in BERT/GPT-style models
SiLU/Swish $z\,\sigma(z)$ smooth, non-monotonic
Mish $z\tanh(\ln(1+e^z))$ smooth, self-gated

GELU and SiLU weight the input by a soft gate in $[0,1]$ depending on its own value, giving smooth gradients near 0.

Softmax and probabilistic outputs

$\mathrm{softmax}(\mathbf{z})_k=e^{z_k}/\sum_je^{z_j}$ maps logits to a probability vector; adding a constant to all logits changes nothing, so subtract $\max_kz_k$ for stability. Its Jacobian is $\mathrm{diag}(\mathbf{p})-\mathbf{p}\mathbf{p}^\top$. Sigmoid is softmax with two classes ($z_1-z_2$). Output pairing: regression → linear (+MSE); binary → sigmoid (+BCE); multiclass → softmax (+CE); multilabel → independent sigmoids.

Derivatives and saturation

Backprop multiplies by $\phi'(z)$ at every layer. For sigmoid, $\phi'\le0.25$, so a depth-$L$ chain can shrink gradients by $0.25^L$ — vanishing gradients. Saturation (large $\lvert z\rvert$) makes $\phi'\approx0$. ReLU's derivative is exactly 1 on the active side, which is a main reason deep nets became trainable (with good initialisation, Module 09).

Composition and decision regions

A one-hidden-layer ReLU network partitions input space into polyhedral regions on which it is linear. Each hidden unit contributes a hyperplane "fold"; more units and layers create more regions.

Universal approximation theorem

Statement (Cybenko 1989; Hornik 1991; Leshno et al. 1993). For any continuous $f$ on a compact set $K\subset\mathbb{R}^n$, any $\varepsilon>0$, and any non-polynomial continuous activation $\phi$, there exist $N$, weights $\mathbf{w}_i,\,b_i$ and $c_i$ with

$$\sup_{\mathbf{x}\in K}\Bigl\lvert f(\mathbf{x})-\sum_{i=1}^Nc_i\,\phi(\mathbf{w}_i^\top\mathbf{x}+b_i)\Bigr\rvert<\varepsilon .$$

Intuition (1-D, sigmoid): a steep sigmoid is a step; the difference of two steps is a "bump"; a weighted sum of bumps approximates any continuous curve. For ReLU, sums of "hinges" build piecewise-linear interpolants.

Limitations. The theorem is about existence: $N$ may be astronomically large; it says nothing about whether gradient descent finds the weights, how much data is needed, or how well the model generalises.

Depth versus width

Deep ReLU networks can represent functions with exponentially many linear regions using polynomially many units (Montúfar et al. 2014); Telgarsky (2016) constructs a "sawtooth" function a depth-$L$ network computes with $O(L)$ units that shallow networks need exponentially many units to match. Depth composes features hierarchically (edges → parts → objects), a better inductive bias for natural signals.

Worked example

$|x|$ with two ReLU units: $|x|=\mathrm{ReLU}(x)+\mathrm{ReLU}(-x)$.

XOR with one hidden layer (solving Module 04's impossibility): $h_1=\mathrm{ReLU}(x_1+x_2)$, $h_2=\mathrm{ReLU}(x_1+x_2-1)$, $y=h_1-2h_2$.

$(x_1,x_2)$ $h_1$ $h_2$ $y$
(0,0) 0 0 0
(0,1) 1 0 1
(1,0) 1 0 1
(1,1) 2 1 0

The hidden layer re-represents the inputs so that XOR becomes linearly separable.

Implementation

import numpy as np
from math import erf

relu = lambda z: np.maximum(0, z)
sigmoid = lambda z: 1 / (1 + np.exp(-z))
gelu = lambda z: 0.5 * z * (1 + np.vectorize(erf)(z / np.sqrt(2)))
silu = lambda z: z * sigmoid(z)

def softmax(z):
    z = z - z.max(-1, keepdims=True); e = np.exp(z); return e / e.sum(-1, keepdims=True)

x = np.array([[0,0],[0,1],[1,0],[1,1]], float)
h = relu(x @ np.array([[1,1],[1,1]], float) + np.array([0,-1.]))
print(h @ np.array([1., -2.]))              # [0, 1, 1, 0]

Advanced topics

  • Gated linear units (GLU, SwiGLU) $\phi(W_1x)\odot(W_2x)$ are standard in modern Transformer feed-forward layers.
  • Self-normalising activations (SELU) keep activations near zero mean/unit variance under suitable initialisation.
  • Smoothness vs. sparsity trade-offs; the neural tangent kernel view depends on activation choice.
  • Approximation rates: Barron (1993) shows rates independent of dimension for functions with bounded Fourier moment; Lipschitz constants of $\phi$ control robustness.
  • Number of linear regions is a measure of expressivity but is rarely reached by trained networks.
  • Quantisation and hardware favour piecewise-linear activations.

Pitfalls and best practices

  • Applying softmax and then a loss that already includes softmax.
  • Using sigmoid/tanh in deep plain stacks without normalisation or residuals.
  • Ignoring dead ReLUs (watch the fraction of zero activations; use a smaller learning rate or Leaky ReLU).
  • Reading the universal approximation theorem as a guarantee of trainability.
  • Sigmoid outputs for mutually exclusive classes (use softmax).

Conceptual questions and answers

Q1. Why can't a deep network of purely linear layers do better than one layer?

Show answer

Composition of linear maps is a linear map: $W_L\cdots W_1=W_{\text{eff}}$. Nonlinearities are what let depth add expressive power.

Q2. Why did ReLU help train deep networks?

Show answer

Its derivative is 1 for positive inputs, so gradients are not repeatedly shrunk by factors $\le\frac14$ as with sigmoid; it is also cheap and induces sparse activations.

Q3. What is the dying-ReLU problem and how do you mitigate it?

Show answer

A unit whose pre-activation is negative for all inputs outputs 0 and receives zero gradient, so it never recovers. Use Leaky ReLU/ELU/GELU, careful initialisation and smaller learning rates.

Q4. Why subtract the max logit in softmax?

Show answer

Softmax is invariant to adding a constant; subtracting $\max_kz_k$ prevents overflow in $e^{z}$ without changing the result.

Q5. State the universal approximation theorem and one thing it does not say.

Show answer

One hidden layer with a non-polynomial activation can approximate any continuous function on a compact set arbitrarily well. It does not bound the width, nor guarantee that training finds the approximator or that it generalises.

Q6. Why is depth often better than width?

Show answer

Some function families need exponentially many units in a shallow network but polynomially many in a deep one, and depth encodes compositional structure.

Q7. Which output activation and loss for multilabel classification?

Show answer

Independent sigmoids with binary cross-entropy per label, since labels are not mutually exclusive.

Q8. How does GELU differ from ReLU conceptually?

Show answer

ReLU gates by the sign of $z$; GELU weights $z$ by the Gaussian CDF $\Phi(z)$ — a smooth, probabilistic gate with non-zero gradient for small negative $z$.

Q9. Why is tanh usually preferred to sigmoid for hidden units in old-style networks?

Show answer

Zero-centred outputs and a larger maximum derivative (1 versus 0.25) lead to better-conditioned updates; both still saturate.

Sources and further reading

  • Cybenko, G. (1989). Approximation by superpositions of a sigmoidal function. Math. Control Signals Systems, 2, 303–314.
  • Hornik, K. (1991). Approximation capabilities of multilayer feedforward networks. Neural Networks, 4(2), 251–257.
  • Leshno, M., Lin, V. Y., Pinkus, A., & Schocken, S. (1993). Multilayer feedforward networks with a nonpolynomial activation function can approximate any function. Neural Networks, 6(6).
  • Glorot, X., Bordes, A., & Bengio, Y. (2011). Deep sparse rectifier neural networks. AISTATS.
  • Hendrycks, D., & Gimpel, K. (2016). Gaussian error linear units (GELUs). arXiv:1606.08415.
  • Ramachandran, P., Zoph, B., & Le, Q. V. (2017). Searching for activation functions. arXiv:1710.05941.
  • Montúfar, G., et al. (2014). On the number of linear regions of deep neural networks. NeurIPS.
  • Telgarsky, M. (2016). Benefits of depth in neural networks. COLT.
  • Barron, A. R. (1993). Universal approximation bounds for superpositions of a sigmoidal function. IEEE Trans. Inf. Theory, 39(3).

⬅️ Module 04 · 🗺️ Curriculum · 🏠 Home · Module 06 ➡️

🎓 Deep Learning Hub

🏠 Home · 🗺️ Curriculum · 🧭 Learning paths

❓ Question bank · 📖 Glossary · 📚 References

Jump to module:

01 02 03 04 05 06 07 08 09 10 11 12

13 14 15 16 17 18 19 20 21 22 23 24

Part 1 · Mathematical foundations
Part 2 · Neural network fundamentals
Part 3 · Training deep networks
Part 4 · Core architectures
Part 5 · Representation and generative learning
Part 6 · Specialised, modern and responsible deep learning
Reference and meta

Clone this wiki locally