Neural networks — the forward pass with matrices
Be able to write a multi-layer neural network's forward pass as matrix operations, count the parameters, and implement it in plain Python/NumPy.
Prerequisites
Formal
A network with input x (d numbers), one hidden layer of h neurons and k outputs:
z₁ = W₁x + b₁ (W₁ is h×d, b₁ is h) a₁ = ReLU(z₁) z₂ = W₂a₁ + b₂ (W₂ is k×h, b₂ is k) ŷ = softmax(z₂) (for classification: probabilities that sum to 1)
Parameters: h·d + h + k·h + k. For d = 784, h = 128, k = 10: 100 480 + 1 290 = 101 770.
ReLU(z) = max(0, z). Softmax(z)ᵢ = e^{zᵢ} / Σⱼ e^{zⱼ}.
Code
import numpy as np
def relu(z): return np.maximum(0, z)
def softmax(z):
e = np.exp(z - z.max())
return e / e.sum()
rng = np.random.default_rng(0)
W1, b1 = rng.normal(0, 0.1, (128, 784)), np.zeros(128)
W2, b2 = rng.normal(0, 0.1, (10, 128)), np.zeros(10)
def forward(x):
a1 = relu(W1 @ x + b1)
return softmax(W2 @ a1 + b2)
x = rng.random(784)
print(forward(x).sum()) # 1.0
@ is matrix multiplication. With a batch of N examples as an N×784 matrix it becomes
X @ W1.T + b1 — the same thing, all the examples at once.
Mastery means
- Writes the forward pass for a two-layer network as formulas
- Calculates the parameter count from the layer sizes
Sign in to do the exercises and build your mastery up.
Sources
Leads to
- DActivation functions
- DAttention
- DBackpropagation
- DEmbeddings — words as vectors
- DWhat does the network see? Images through the layers
- EAutoencoders
- EConvolutional networks (CNNs)
- EGenerative models — an overview
- EWeight initialisation
- ESequence models before transformers
- FDeep Q-Networks
- FGraph neural networks (GNNs)
- FQuantisation
Part of the goals (30)
- Image classification with convolutional networks
- Run models more cheaply: quantisation
- Training neural networks for real
- Understand how generative AI works
- Classical ML for real
- Language models in practice
- Deep reinforcement learning
- Interpreting a language model
- Fine-tune and run your own models
- Generative models in depth
- Build a transformer from scratch
- AI safety in practice
- Build a voice interface
- Seeing and hearing with AI
- Frontier Lab — an independent research project
- Build a RAG system you can trust
- Multimodal systems
- Responsible AI in practice
- Fine-tune a model with LoRA
- Train your first neural network
- Evals in practice
- Reproduce a paper
- Build a memory system for an agent
- Build an AI service that survives production
- AI in production
- Statistics for experiments
- Build an agent you can trust
- Build an NLP system end to end
- An AI service in operation
- AI, ethics and society