Module 3 of 127 lessons

Build a Neural Network from Scratch

No frameworks: we write every neuron, every derivative and every update by hand, then watch the network learn.

Course contents · Module 3 of 12
← Build Claude from scratch
98 lessons · 12 modules
  1. 1Understanding Claude and modern AI6
    1. 1.1What is Claude?
    2. 1.2What is an LLM?
    3. 1.3How ChatGPT, Claude, Gemini and other AI assistants work
    4. 1.4AI, machine learning, deep learning, transformers and LLMs
    5. 1.5What happens when you send a message to an AI?
    6. 1.6Tokens, context windows and embeddings
  2. 2Mathematics and foundations6
    1. 2.1Essential linear algebra
    2. 2.2Vectors, matrices and matrix multiplication
    3. 2.3Probability and statistics
    4. 2.4Softmax, gradients and loss functions
    5. 2.5Neural networks and backpropagation
    6. 2.6Practical Python demonstrations
  3. 3Neural network from scratch7
    1. 3.1Set up Python and NumPy
    2. 3.2Build neurons and layers
    3. 3.3Implement forward propagation
    4. 3.4Implement backpropagation
    5. 3.5Implement gradient descent
    6. 3.6Train a small neural network without PyTorch or TensorFlow
    7. 3.7Visualize training and loss
  4. 4Understanding transformers9
    1. 4.1Why traditional RNNs have limitations
    2. 4.2The transformer architecture
    3. 4.3Tokenization and embeddings
    4. 4.4Positional encoding
    5. 4.5Self-attention and multi-head attention
    6. 4.6Query, Key and Value explained visually
    7. 4.7Feed-forward networks
    8. 4.8Layer normalization and residual connections
    9. 4.9Implement a simplified transformer in NumPy
  5. 5Build a GPT-like model9
    1. 5.1Tokenizer implementation
    2. 5.2Vocabulary creation
    3. 5.3Dataset preparation
    4. 5.4Next-token prediction
    5. 5.5Building a decoder-only transformer
    6. 5.6Training a tiny language model
    7. 5.7Text generation and temperature
    8. 5.8Top-k and top-p sampling
    9. 5.9Understanding hallucinations and limitations
  6. 6How Claude is different9
    1. 6.1Claude's architecture at a conceptual level
    2. 6.2Constitutional AI
    3. 6.3Supervised fine-tuning
    4. 6.4Reinforcement learning from human feedback
    5. 6.5Preference optimization
    6. 6.6Safety training and alignment
    7. 6.7System prompts and instruction following
    8. 6.8Long-context processing
    9. 6.9Tool use and agentic behavior
  7. 7Build your own AI assistant10
    1. 7.1Design a Claude-like chat interface
    2. 7.2Conversation management
    3. 7.3System instructions
    4. 7.4Chat history and context management
    5. 7.5Streaming responses
    6. 7.6Markdown and code rendering
    7. 7.7Syntax highlighting
    8. 7.8Error handling
    9. 7.9File upload and document understanding concepts
    10. 7.10Building a frontend chatbot
  8. 8Memory and RAG8
    1. 8.1What is AI memory?
    2. 8.2Short-term vs long-term memory
    3. 8.3Embeddings and vector databases
    4. 8.4Semantic search
    5. 8.5Retrieval-Augmented Generation (RAG)
    6. 8.6Chunking and document retrieval
    7. 8.7Build a basic document Q&A system
    8. 8.8Context injection and source citations
  9. 9Function calling and agents9
    1. 9.1What is function calling?
    2. 9.2Tool definitions and JSON schemas
    3. 9.3Calling external tools
    4. 9.4Tool execution loops
    5. 9.5Search, calculator and other tools
    6. 9.6Multi-step reasoning and planning
    7. 9.7Agent architecture
    8. 9.8Safety restrictions and tool permissions
    9. 9.9Build a basic tool-using AI agent
  10. 10Fine-tuning and training8
    1. 10.1Pretraining vs fine-tuning
    2. 10.2Dataset collection and cleaning
    3. 10.3Instruction datasets
    4. 10.4Fine-tuning concepts
    5. 10.5LoRA and QLoRA
    6. 10.6GPU and VRAM requirements
    7. 10.7Training costs and realistic hardware requirements
    8. 10.8Model evaluation and benchmarking
  11. 11Deployment and production9
    1. 11.1Model inference
    2. 11.2Quantization
    3. 11.3CPU vs GPU inference
    4. 11.4Running open-source LLMs locally
    5. 11.5Ollama and Hugging Face concepts
    6. 11.6API design
    7. 11.7Docker deployment
    8. 11.8Monitoring and logging
    9. 11.9Security, rate limiting and cost optimization
  12. 12Capstone project8
    1. 12.1Capstone overview and architecture
    2. 12.2The conversational UI
    3. 12.3Conversation history and system prompts
    4. 12.4Streaming output with Markdown and code
    5. 12.5Configurable model providers and error handling
    6. 12.6Document Q&A and memory
    7. 12.7Tool calling
    8. 12.8Testing, deployment and the capstone challenge

Lesson 3.1Module 3: Neural network from scratch

Set up Python and NumPy

  • ⏱ 17 min read
  • Beginner

Learning objectives

  • Create an isolated Python environment and install NumPy in it.
  • Run a setup check and understand every line it prints.
  • Read and predict array shapes for matrix multiplication, broadcasting and reductions.
  • Explain why we write X @ W once instead of nested loops, and why seeded random generators matter.

In this module you build a neural network with nothing but Python and NumPy: no PyTorch, no TensorFlow, no automatic differentiation. Every weight, every derivative and every update will be a line of code you wrote and can print. That is slower to write than calling a framework, but it removes all the magic. When you reach transformers in module 4 and a tiny GPT in module 5, you will recognise every piece, because a large language model is built from exactly the parts in this module: layers that multiply matrices, non-linear functions, a loss, gradients and an optimiser, repeated at a vastly larger scale.

This first lesson is short on theory and long on tools. You set up a clean environment, check that NumPy works, and learn the handful of array habits that the rest of the module relies on. If you already use NumPy daily, skim the code and jump to the exercise.

Analogy: a workbench and a power saw

Plain Python is a well-organised workbench: you can build anything, one plank at a time. NumPy is the power saw bolted to it. Instead of cutting 10,000 planks one by one in a Python loop, you clamp the whole stack together (an array) and cut it in one pass. The saw is written in fast compiled code, so one pass over a million numbers takes milliseconds. Neural networks are almost nothing but "do the same arithmetic to a big stack of numbers", which is exactly the job the saw was built for.

Why NumPy, and why not a framework yet?

A neural network is a function with many adjustable numbers called parameters (or weights). Running it means multiplying an input by matrices of weights and applying simple functions in between. Training it means computing, for every weight, how the error would change if that weight moved a little (the gradient), and nudging all weights in the direction that lowers the error. All of that is arithmetic on arrays.

NumPy gives Python a fast n-dimensional array type, ndarray, plus matrix multiplication, element-wise maths and random numbers. Frameworks such as PyTorch and JAX add three things on top: they run the same array maths on GPUs, they compute gradients automatically (autograd), and they ship ready-made layers. In this module we deliberately give up all three so that you write the gradients yourself in lesson 3.4. Once you have done that once, autograd stops being a black box, and debugging a real model becomes far less mysterious.

Simplified implementation

Everything in this module runs on a CPU with networks of a few hundred to a few thousand parameters. Frontier language models have billions to trillions of parameters (exact figures for Claude are Not public) and are trained on large clusters of accelerators. The ideas are the same; the scale is not remotely comparable.

Install Python and NumPy in a virtual environment

You need Python 3.10 or newer. A virtual environment is a private folder of packages for one project, so installing NumPy here never breaks another project on your machine. Create one, activate it, and install NumPy (and, optionally, matplotlib for the charts in lesson 3.7):

python3 --version                 # should print 3.10 or newer
python3 -m venv .venv             # create the environment in a folder called .venv
source .venv/bin/activate         # activate it (your prompt now starts with (.venv))
python -m pip install numpy       # the only package the runnable code needs
python -m pip install matplotlib  # optional: real charts in lesson 3.7
py --version                      # should print 3.10 or newer
py -m venv .venv
.venv\Scripts\Activate.ps1        # if blocked: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned
python -m pip install numpy
python -m pip install matplotlib  # optional

Using python -m pip rather than a bare pip guarantees that the package goes into the same Python you will run, which avoids the most common setup problem of all. Every runnable file in this module also has a ▶ Run button that executes it in your browser with Pyodide (Python compiled to WebAssembly), so you can follow along without installing anything; a local install is still better for experiments.

Check your setup

Save this file as check_setup.py and run python check_setup.py. It tests the four things the module depends on: the Python version, matrix multiplication, reproducible random numbers, and floating-point precision.

# @run
# Lesson 3.1: check that Python and NumPy are ready for module 3.
# Run it with:  python check_setup.py
import sys

import numpy as np

# 1. Python version: the course is tested on Python 3.10 and newer.
ok_python = sys.version_info >= (3, 10)
print("Python 3.10 or newer:", "yes" if ok_python else "NO, please upgrade")

# 2. NumPy imports and does matrix maths correctly.
A = np.array([[1.0, 2.0], [3.0, 4.0]])
B = np.array([[5.0, 6.0], [7.0, 8.0]])
C = A @ B                                   # matrix multiplication
expected = np.array([[19.0, 22.0], [43.0, 50.0]])
print("Matrix multiply works:", "yes" if np.allclose(C, expected) else "NO")

# 3. Reproducible randomness: same seed, same numbers.
rng1 = np.random.default_rng(42)
rng2 = np.random.default_rng(42)
same = np.array_equal(rng1.normal(size=5), rng2.normal(size=5))
print("Same seed gives same numbers:", "yes" if same else "NO")
rng = np.random.default_rng(0)
print("First three draws with seed 0:", np.round(rng.normal(size=3), 4))

# 4. float32 vs float64: how many digits survive?
third64 = np.float64(1.0) / 3.0
third32 = np.float32(1.0) / np.float32(3.0)
print(f"1/3 as float64: {float(third64):.12f}")
print(f"1/3 as float32: {float(third32):.12f}")
print("Bytes per number: float64 =", np.dtype(np.float64).itemsize,
      "| float32 =", np.dtype(np.float32).itemsize)

# 5. A vectorised operation on a million numbers (the reason we use NumPy).
x = np.arange(1_000_000, dtype=np.float64)
print("Sum of 0..999999:", int(x.sum()))

print("Setup looks good. You are ready for lesson 3.2." if ok_python else "Fix the problems above first.")
  1. import numpy as np: the universal convention. Every NumPy example you will ever read calls it np.
  2. sys.version_info >= (3, 10): compares the running version as a tuple, so 3.12 passes and 3.9 fails.
  3. C = A @ B: the @ operator is matrix multiplication. Row 1 of A times column 1 of B is 1·5 + 2·7 = 19, which is why the expected top-left entry is 19.
  4. np.allclose(C, expected): compares floats with a small tolerance. Never compare floating-point results with ==.
  5. np.random.default_rng(42): creates a random generator with a fixed seed. Two generators with the same seed produce the same sequence, which makes every experiment repeatable.
  6. np.float32(1.0) / np.float32(3.0): the same division in 32-bit precision. It agrees with 64-bit to about 7 digits, then drifts.
  7. np.dtype(np.float64).itemsize: bytes per number. Half the bytes means half the memory, which is why large models are stored in 16-bit or even smaller formats (lesson 11.2).
  8. x = np.arange(1_000_000) and x.sum(): one call adds a million numbers in compiled code. A Python for loop doing the same thing is many times slower.
Python 3.10 or newer: yes
Matrix multiply works: yes
Same seed gives same numbers: yes
First three draws with seed 0: [ 0.1257 -0.1321  0.6404]
1/3 as float64: 0.333333333333
1/3 as float32: 0.333333343267
Bytes per number: float64 = 8 | float32 = 4
Sum of 0..999999: 499999500000
Setup looks good. You are ready for lesson 3.2.

If any line says NO, fix it before going on: a failed matrix check usually means a broken NumPy install (reinstall it inside the virtual environment), and an old Python means installing a newer one from python.org. The two "1/3" lines are the first hint of a theme you will meet again: computers store approximations of real numbers, and the precision you choose is a trade-off between accuracy, memory and speed.

Think in shapes

The single most useful habit for neural-network code is to know the shape of every array. By convention in this module, a batch of data is a matrix with one row per example and one column per feature. Four examples with three features each is shape (4, 3). A layer's weights map n_in features to n_out features, so they have shape (n_in, n_out), and the matrix product of the batch with the weights has shape (batch, n_out). The rule is that the inner sizes must match and disappear:

X(4×3)·W(3×2)=Y(4×2),Yij=∑k=13XikWkj

In words: entry (i, j) of the result is row i of X multiplied element by element with column j of W, then summed. The shared size 3 is consumed; the outer sizes 4 and 2 survive.

Two more ideas complete the toolkit. Broadcasting lets NumPy combine arrays of different shapes by virtually repeating the smaller one: adding a bias vector of shape (2,) to a (4, 2) matrix adds the same two numbers to every row, without copying anything. Reductions such as sum, mean and max collapse one axis: axis=0 runs down the rows (one result per column), axis=1 runs across the columns (one result per row).

X @ W, shape (4, 2) 33 1212 2121 3030 + b, shape (2,) 10-10 10-1010-1010-10 = result, shape (4, 2) 13-7 222 3111 4020 dashed = repeated by broadcasting, never actually copied
Broadcasting a bias. The same (2,) vector is added to every row of the (4, 2) matrix. This is exactly how every layer adds its bias to a whole batch at once. (The left matrix is X @ W from the tour below.)

A ten-minute NumPy tour

This file contains every NumPy operation the module uses. Read it once now; you will see each line again inside the network code.

# @run
# Lesson 3.1: the NumPy you need for this module, in one short tour.
import numpy as np

rng = np.random.default_rng(0)

# Shapes: a batch of 4 examples, each with 3 features -> (4, 3)
X = np.arange(12, dtype=np.float64).reshape(4, 3)
print("X shape:", X.shape)
print(X)

# Matrix multiply: (4, 3) @ (3, 2) -> (4, 2)
W = np.ones((3, 2))
print("X @ W shape:", (X @ W).shape)

# Broadcasting: a (2,) bias is added to every row of a (4, 2) matrix
b = np.array([10.0, -10.0])
print("(X @ W + b) first row:", X[0] @ W + b)

# Reductions along an axis: axis=0 goes down the rows, axis=1 across the columns
print("column sums (axis=0):", X.sum(axis=0))
print("row sums (axis=1):   ", X.sum(axis=1))
print("row max, keepdims:   ", X.max(axis=1, keepdims=True).shape)

# Element-wise maths and boolean masks
Z = np.array([[-2.0, 0.5], [3.0, -0.1]])
print("ReLU via np.maximum:", np.maximum(0.0, Z).tolist())
print("mask Z > 0:         ", (Z > 0).tolist())

# Fancy indexing: pick one column per row (used by cross-entropy)
P = np.array([[0.7, 0.2, 0.1], [0.1, 0.1, 0.8]])
labels = np.array([0, 2])
print("P[rows, labels]:", P[np.arange(2), labels])
print("argmax per row: ", P.argmax(axis=1))

# Random numbers from a seeded generator
print("uniform:", np.round(rng.uniform(-1, 1, size=3), 3))
print("permutation of 0..5:", rng.permutation(6))
  1. np.arange(12, dtype=np.float64).reshape(4, 3): twelve numbers laid out as 4 rows of 3. reshape only changes how the same memory is viewed.
  2. X @ W with W = np.ones((3, 2)): (4, 3) times (3, 2) gives (4, 2). Each output is just the row sum here, because every weight is 1.
  3. X[0] @ W + b: the first row (0, 1, 2) gives 3 in both columns; adding the bias (10, -10) gives 13 and -7, as in the figure above.
  4. X.sum(axis=0) and X.sum(axis=1): column sums (18, 22, 26) and row sums (3, 12, 21, 30). Remember: the axis you name is the one that disappears.
  5. keepdims=True: keeps the reduced axis with size 1, giving shape (4, 1) instead of (4,). That makes the result broadcast correctly back against the (4, 3) matrix, which softmax needs in lesson 3.2.
  6. np.maximum(0.0, Z): element-wise maximum, which is the ReLU activation in one call. Z > 0 produces a boolean mask, which backpropagation through ReLU uses.
  7. P[np.arange(2), labels]: fancy indexing picks one entry per row: row 0, column 0 and row 1, column 2. Cross-entropy uses this to pick the probability of the correct class.
  8. P.argmax(axis=1): the index of the largest value in each row, which is how a classifier turns probabilities into a predicted class.
  9. rng.uniform, rng.permutation: random numbers from the seeded generator. permutation is how we will shuffle training data every epoch.
X shape: (4, 3)
[[ 0.  1.  2.]
 [ 3.  4.  5.]
 [ 6.  7.  8.]
 [ 9. 10. 11.]]
X @ W shape: (4, 2)
(X @ W + b) first row: [13. -7.]
column sums (axis=0): [18. 22. 26.]
row sums (axis=1):    [ 3. 12. 21. 30.]
row max, keepdims:    (4, 1)
ReLU via np.maximum: [[0.0, 0.5], [3.0, 0.0]]
mask Z > 0:          [[False, True], [True, False]]
P[rows, labels]: [0.7 0.8]
argmax per row:  [0 2]
uniform: [ 0.274 -0.46  -0.918]
permutation of 0..5: [4 1 2 0 3 5]

Why vectorise?

Here is the same layer computation written with loops and with one matrix product. Both give identical numbers; the vectorised one is shorter, harder to get wrong and, on a typical laptop, one to two orders of magnitude faster for arrays of this size (the exact factor depends on your CPU and NumPy build, so measure it yourself with time.perf_counter()).

import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(size=(256, 64))      # 256 examples, 64 features
W = rng.normal(size=(64, 32))       # a layer with 32 outputs

# Loops: 256 * 32 * 64 = 524,288 Python-level multiplications
Y_loop = np.zeros((256, 32))
for i in range(256):
    for j in range(32):
        for k in range(64):
            Y_loop[i, j] += X[i, k] * W[k, j]

Y_vec = X @ W                         # one call into optimised compiled code
print(np.allclose(Y_loop, Y_vec))     # True

The speed difference is not only "C is faster than Python". Libraries like NumPy hand matrix products to BLAS routines that use the CPU's vector instructions and caches carefully, and often several cores. GPUs push the same idea much further, with thousands of simple cores doing multiply-adds in parallel. That is the fundamental reason deep learning took off when it did: the core operation is a matrix multiplication, and hardware got very good at it.

Views, copies, dtypes and in-place updates

Three details that bite people who write neural networks by hand:

  • Views versus copies. Slicing (X[:10]), reshape and .T usually return a view that shares memory with the original. Fancy indexing (X[[3, 1, 2]]) and boolean masks return a copy. Writing into a view changes the original; writing into a copy does not. Use np.shares_memory(a, b) when in doubt.
  • In-place operators matter for parameters. W -= 0.1 * dW modifies the array that the layer holds. W = W - 0.1 * dW builds a new array and rebinds a local name, leaving the layer's weights untouched. Our optimisers in lesson 3.5 depend on the in-place form.
  • Integer arrays truncate. np.arange(5) is an integer array; assigning 0.7 into it silently stores 0. Create floating arrays explicitly with dtype=np.float64 or by writing 1.0.
  • Precision. We use float64 for clarity and for gradient checking (lesson 3.4), which needs many digits. Real training uses float32 or 16-bit formats such as bfloat16, usually with some float32 "master" copies; that is Industry practice for large models and is covered with quantisation in module 11.
  • Random generators. np.random.default_rng(seed) returns an independent Generator object. The older global np.random.seed() API still works, but a global state is shared by every library you import, so results can change when an unrelated import draws a random number. Passing a generator around, as this module does, keeps experiments reproducible.

Common mistakes and debugging tips

pip install numpy worked, but import numpy fails

Your shell's pip belongs to a different Python than the one running your script (common with several Pythons, conda and system packages side by side).

Fix: activate the virtual environment, then always use python -m pip install …. Check with python -c "import sys; print(sys.executable)".

Confusing shape (n,) with (n, 1)

A 1-D array of 5 labels and a (5, 1) column of predictions look similar, but subtracting them broadcasts to a (5, 5) matrix with no error at all. Losses then come out silently wrong.

Fix: print .shape often, use reshape(-1, 1) or .ravel() deliberately, and add assert pred.shape == y.shape before computing a loss.

Results change on every run

Unseeded randomness (initial weights, shuffling, data) makes it impossible to tell whether a change helped or you got lucky.

Fix: create one rng = np.random.default_rng(0) at the top and pass it to everything that needs randomness. Change the seed on purpose to check that a result is robust.

Comparing floats with ==

0.1 + 0.2 == 0.3 is False in every language that uses binary floating point.

Fix: use np.allclose or np.isclose, or compare with an explicit tolerance.

Key takeaways

  • A virtual environment plus python -m pip install numpy is all the setup this module needs.
  • Rows are examples, columns are features: (batch, n_in) @ (n_in, n_out) = (batch, n_out).
  • Broadcasting adds a bias to every row; reductions collapse the axis you name; keepdims keeps shapes compatible.
  • Seeded generators make experiments repeatable; vectorised code is shorter and much faster than loops.

Exercise: standardise features without a loop

Neural networks train best when each input feature has mean 0 and standard deviation 1. Write standardise(X) that takes any matrix of shape (n, d) and returns a matrix of the same shape in which every column has mean 0 and standard deviation 1, using no Python loops. Test it on X = rng.normal(5.0, 3.0, size=(1000, 4)) and print the column means and standard deviations, rounded to 3 decimals. Then explain why you must reuse the training mean and standard deviation when you later standardise validation data.

Hint

"Per column" means reduce over the rows: axis=0. The mean then has shape (d,), which broadcasts against (n, d) automatically. Guard against a column whose standard deviation is 0.

Show a solution
import numpy as np

def standardise(X, eps=1e-8):
    mean = X.mean(axis=0)                 # shape (d,)
    std = X.std(axis=0)                   # shape (d,)
    return (X - mean) / (std + eps), mean, std

rng = np.random.default_rng(0)
X = rng.normal(5.0, 3.0, size=(1000, 4))
Xs, mean, std = standardise(X)
print(np.round(Xs.mean(axis=0), 3))       # [ 0. -0. -0. -0.]  ("-0." is a tiny negative number rounded)
print(np.round(Xs.std(axis=0), 3))        # [1. 1. 1. 1.]

The function returns the mean and standard deviation so you can apply the same transformation to validation and test data: (X_val - mean) / (std + eps). Computing new statistics on the validation set would leak information about it into your pipeline and make validation scores slightly optimistic; at prediction time you might only have one example, whose "standard deviation" is meaningless.

Check your understanding

A batch X has shape (32, 10) and weights W have shape (10, 4). What is the shape of X @ W + b if b has shape (4,)?

  1. (10, 4)
  2. (32, 10)
  3. (32, 4)
  4. An error: b has the wrong shape
The inner size 10 is consumed by the matrix product, leaving (32, 4); the (4,) bias broadcasts across all 32 rows. (10, 4) is the weight shape, (32, 10) is the input shape, and the bias shape is exactly right.

Why does this module pass a seeded generator rng to every function instead of calling np.random.normal directly?

  1. So that every experiment is reproducible and independent of random numbers drawn by other code
  2. Because the global functions are deprecated and no longer work
  3. Because seeded numbers are more random
A generator object with a fixed seed gives the same sequence every run and isn't disturbed by other code drawing from a global state. The global API still works (it is legacy, not removed), and a seed makes numbers repeatable, not "more random".

X has shape (4, 3). What does X.max(axis=1, keepdims=True) return?

  1. Shape (3,): the largest value in each column
  2. Shape (4, 1): the largest value in each row, kept as a column
  3. Shape (1, 3): the largest value in each row
axis=1 reduces across the columns, giving one value per row (4 values), and keepdims keeps that axis with size 1, so (4, 1). Per-column maxima would be axis=0.

Lesson 3.2Module 3: Neural network from scratch

Build neurons and layers

  • ⏱ 15 min read
  • Intermediate

Learning objectives

  • Compute a single neuron's output by hand: weighted sum, bias, activation.
  • Write a Dense layer that processes a whole batch with one matrix product, and count its parameters.
  • Compare ReLU, sigmoid, tanh and softmax, and explain why a network needs non-linear activations at all.
  • Explain why weights must start random, and why the size of that randomness (He or Xavier initialisation) matters.

Every neural network, from the four-neuron toy you will build today to the transformer layers inside a large language model, is assembled from the same small part: a unit that takes some numbers in, multiplies each by a weight, adds them up with a bias, and passes the result through a simple non-linear function. This lesson builds that unit, then stacks many of them side by side into a layer, which is where matrices come in.

Analogy: a judge weighing evidence

Picture a judge deciding whether a loan application looks risky. Each piece of evidence (income, debt, years at the job) gets a weight: some push towards "risky", some away, some barely matter. The judge adds up the weighted evidence, adds a personal leaning (the bias: some judges are stricter than others), and then makes a call. A neuron is that judge. A layer is a panel of judges who all see the same evidence but each weigh it differently, so each notices something different. Training, later in this module, is the process of teaching every judge which evidence to trust.

One neuron

A neuron with two inputs x1 and x2 has two weights, one bias and an activation function f. It first computes the pre-activation z, a plain weighted sum, and then the output a:

z=w1x1+w2x2+b=w·x+b,a=f(z)

In words: multiply each input by its weight, add them up, add the bias, then pass the total through the activation function.

With weights (0.5, -1.0), bias 0.1 and input (2, 1): z = 0.5·2 + (-1.0)·1 + 0.1 = 0.1. With the ReLU activation, which keeps positive numbers and turns negatives into zero, the output is 0.1. That is the whole computation. The name "neuron" comes from a loose analogy with brain cells, which also combine many inputs and "fire" past a threshold; real neurons are far more complicated, and modern deep learning owes much more to linear algebra and optimisation than to biology.

Geometrically, the set of inputs where z = 0 is a straight line (a plane in 3-D, a hyperplane in more dimensions). The weights set the line's direction, the bias shifts it, and the neuron answers "how far, and on which side of this line, is the input?" Try it below: the shading shows the neuron's output over the whole input plane, and the dashed line is where z = 0.

One neuron over the input planeInteractive

Notice that whatever you do, the boundary stays a straight line. A single neuron can only separate things that a straight line can separate. That limitation, famously pointed out for the perceptron in the late 1960s, is why we need many neurons in layers, and why the activation function must be non-linear.

Activation functions

The activation function is the only non-linear step in a neuron. Four are worth knowing now:

01-12-303z ReLUsigmoidtanh
Three activations on the same axis. ReLU is zero for negative z and the identity for positive z. Sigmoid squashes everything into (0, 1); tanh into (-1, 1). Both flatten out at the ends, which is where their slope, and therefore their gradient, nearly vanishes.
FunctionFormulaOutput rangeSlope (used in lesson 3.4)Typical use
ReLUmax(0, z)[0, ∞)1 if z > 0, else 0Hidden layers: cheap, and the gradient doesn't shrink for positive inputs
Sigmoid1 / (1 + e−z)(0, 1)s(1 − s), at most 0.25Output of a yes/no classifier (a probability)
Tanh(ez − e−z) / (ez + e−z)(−1, 1)1 − t², at most 1Hidden layers in older and recurrent networks
Softmaxezi / Σ ezj (over a row)(0, 1), row sums to 1Combined with cross-entropy (lesson 3.4)Output of a multi-class classifier, and of every language model's next-token prediction

Transformers mostly use smooth relatives of ReLU such as GELU or SwiGLU in their feed-forward layers (lesson 4.7); the reasoning is the same.

Why the non-linearity is essential

Suppose you skipped the activation and stacked two layers anyway. The first computes W1x+b1, the second multiplies that by W2:

W2(W1x+b1)+b2=(W2W1)x+(W2b1+b2)=W′x+b′

In words: two linear layers in a row are exactly one linear layer with different numbers. A hundred of them still are. Without activations, depth buys nothing.

A non-linear function between the layers breaks this collapse. With ReLU, each hidden neuron contributes a "hinge": a straight piece that switches on along its own line. Adding many hinges lets the network bend its decision boundary into curves, which you will see happen in lesson 3.6.

From neurons to a Dense layer

A dense (or fully connected) layer is several neurons that all read the same inputs. Put each neuron's weights in a column and you get a weight matrix W of shape (n_in, n_out); put the biases in a vector b of length n_out. A whole batch of inputs, one example per row, then goes through the layer in a single line:

Z(batch,nout)=X(batch,nin)W(nin,nout)+b

In words: each row of Z holds the pre-activations of all neurons for one example; the bias is broadcast to every row.

The layer has nin×nout+nout parameters. A layer from 2 inputs to 4 neurons has 2·4 + 4 = 12. This simple formula is how parameter counts of real models are added up; the feed-forward block of a transformer, for example, is two dense layers, and in typical published designs it holds most of each block's parameters.

x₁x₂h₁h₂h₃h₄ W shape (2, 4): column j = weights of neuron h_j b shape (4,) params = 2·4 + 4 = 12
A Dense(2, 4) layer. Each of the 8 lines is one weight; each hidden neuron also has a bias. The whole picture is the single line X @ W + b.

The code

Here are the building blocks as small classes. Each has a forward method; in lesson 3.4 each will gain a backward method too. The bottom part runs five experiments.

# @run
# Lesson 3.2: neurons, Dense layers, weight initialisation and activation functions.
import numpy as np


class Neuron:
    """One neuron: a weighted sum of its inputs plus a bias, then an activation."""

    def __init__(self, weights, bias):
        self.w = np.asarray(weights, dtype=np.float64)
        self.b = float(bias)

    def forward(self, x):
        z = np.dot(self.w, x) + self.b          # pre-activation (a single number)
        return max(0.0, float(z))               # ReLU activation


class Dense:
    """A fully connected layer: n_in inputs -> n_out neurons, for a whole batch at once."""

    def __init__(self, n_in, n_out, rng, init="he"):
        if init == "he":                         # for ReLU layers
            std = np.sqrt(2.0 / n_in)
        elif init == "xavier":                   # for tanh / sigmoid layers
            std = np.sqrt(2.0 / (n_in + n_out))
        elif init == "zeros":                    # a bad idea, kept for the experiment
            std = 0.0
        else:                                    # a fixed small number, e.g. 0.01
            std = float(init)
        self.W = rng.normal(0.0, std, size=(n_in, n_out))   # one column per neuron
        self.b = np.zeros(n_out)                            # biases can start at zero

    def forward(self, X):
        return X @ self.W + self.b               # (batch, n_in) @ (n_in, n_out) + (n_out,)


class ReLU:
    def forward(self, Z):
        return np.maximum(0.0, Z)


class Sigmoid:
    def forward(self, Z):
        return 1.0 / (1.0 + np.exp(-Z))


class Tanh:
    def forward(self, Z):
        return np.tanh(Z)


class Softmax:
    def forward(self, Z):
        Z = Z - Z.max(axis=1, keepdims=True)     # subtract the row max: same result, no overflow
        E = np.exp(Z)
        return E / E.sum(axis=1, keepdims=True)


if __name__ == "__main__":
    rng = np.random.default_rng(0)

    # 1. A single neuron by hand: 0.5*2 + (-1.0)*1 + 0.1 = 0.1, ReLU keeps it.
    n = Neuron([0.5, -1.0], 0.1)
    print(f"neuron output: {n.forward(np.array([2.0, 1.0])):.2f}")

    # 2. A Dense layer is many neurons sharing the same input.
    layer = Dense(2, 4, rng)
    X = np.array([[2.0, 1.0], [0.0, -1.0], [1.0, 1.0]])   # batch of 3 examples
    Z = layer.forward(X)
    print("W shape:", layer.W.shape, "| b shape:", layer.b.shape, "| output shape:", Z.shape)

    # 3. The activations on the same numbers.
    z = np.array([[-2.0, -0.5, 0.0, 0.5, 2.0]])
    for act in (ReLU(), Sigmoid(), Tanh(), Softmax()):
        print(f"{type(act).__name__:8s}", np.round(act.forward(z), 3))

    # 4. Why not zeros? Every neuron computes the same thing.
    zero_layer = Dense(2, 4, rng, init="zeros")
    zero_layer.W += 0.3                                   # any identical value shows the same problem
    print("identical columns with equal init:", np.round(zero_layer.forward(X)[0], 3))

    # 5. Signal size through 10 ReLU layers of 256 units for three initialisations.
    X = rng.normal(size=(500, 256))
    for init in ("0.01", "1.0", "he"):
        H = X
        stds = []
        for depth in range(10):
            H = ReLU().forward(Dense(256, 256, rng, init=init).forward(H))
            stds.append(H.std())
        print(f"init {init:>4s}: std after layer 1 = {stds[0]:.2e}, layer 5 = {stds[4]:.2e}, layer 10 = {stds[9]:.2e}")
  1. class Neuron: the textbook single neuron with np.dot(self.w, x) + self.b and ReLU. We use it once to check the hand calculation, then never again: layers do the same work for many neurons and many examples at once.
  2. Dense.__init__: draws W from a normal distribution whose standard deviation depends on init. "he" uses √(2 / n_in) (for ReLU layers), "xavier" uses √(2 / (n_in + n_out)) (for tanh and sigmoid), and the other options exist for the experiments.
  3. self.b = np.zeros(n_out): biases can safely start at zero, because the random weights already make the neurons different from each other.
  4. return X @ self.W + self.b: the entire layer. Shapes: (batch, n_in) @ (n_in, n_out) + (n_out,).
  5. Softmax.forward: subtracts each row's maximum before np.exp. Softmax doesn't change when you add the same constant to a whole row, but exp(1000) overflows to infinity, so the subtraction keeps the numbers safe.
  6. Experiment 3 prints each activation on z = (-2, -0.5, 0, 0.5, 2). Note that the softmax row sums to 1 and gives the largest input the largest share.
  7. Experiment 4 sets every weight to the same value: all four neurons output exactly 0.9, and (as lesson 3.4 will show) they would also receive identical gradients and stay identical forever. This is the symmetry problem.
  8. Experiment 5 pushes 500 random examples through ten 256-unit ReLU layers and prints the spread (standard deviation) of the signal after layers 1, 5 and 10.
neuron output: 0.10
W shape: (2, 4) | b shape: (4,) | output shape: (3, 4)
ReLU     [[0.  0.  0.  0.5 2. ]]
Sigmoid  [[0.119 0.378 0.5   0.622 0.881]]
Tanh     [[-0.964 -0.462  0.     0.462  0.964]]
Softmax  [[0.013 0.056 0.093 0.153 0.685]]
identical columns with equal init: [0.9 0.9 0.9 0.9]
init 0.01: std after layer 1 = 9.36e-02, layer 5 = 1.64e-05, layer 10 = 4.02e-10
init  1.0: std after layer 1 = 9.44e+00, layer 5 = 1.66e+05, layer 10 = 2.47e+10
init   he: std after layer 1 = 8.31e-01, layer 5 = 7.86e-01, layer 10 = 7.75e-01

The last three lines are the most important result in the lesson. With weights drawn at a fixed standard deviation of 0.01, the signal shrinks roughly tenfold per layer and is effectively zero (4e-10) after ten layers: the network's output no longer depends on its input, and the gradients will be just as tiny. With standard deviation 1.0 the signal explodes to about 2e10. With He initialisation it stays close to 0.8 at every depth. Choosing the initial scale so that signals keep their size is what makes deep networks trainable at all.

Where √(2 / n_in) comes from, and what "universal approximation" really promises

Variance bookkeeping. One pre-activation is a sum of n_in terms wkxk. If the weights are independent with mean 0 and variance σ2, the variance of the sum is about ninσ2 times the average of x2. ReLU zeroes roughly half of its inputs, which halves that average square. To keep the signal's size constant from layer to layer we need ninσ2/2=1, so σ=2/nin. That is He initialisation (He et al., 2015). Xavier/Glorot initialisation (2010) does the same bookkeeping for activations that don't cut half the signal, averaging over the forward and backward directions. In experiment 5, standard deviation 0.01 is far below √(2/256) ≈ 0.088, so each layer multiplies the signal size by about 0.01 / 0.088 ≈ 0.11; that matches the roughly tenfold drop per layer you see.

Universal approximation. A classic theorem says a network with one hidden layer and enough neurons can approximate any continuous function on a bounded region as closely as you like. It is an existence result: it says nothing about how many neurons you need, or whether gradient descent will find the right weights. In practice, deeper networks represent many functions with far fewer parameters than one very wide layer, which is one reason modern models are deep.

Real models. Large transformers also add normalisation layers and residual connections (lesson 4.8) precisely to keep signal sizes under control across dozens of layers, and published recipes often scale some initial weights by depth. The exact initialisation used for Claude is Not public.

Common mistakes and debugging tips

Storing weights as (n_out, n_in) and getting a shape error

Many papers write Wx with x as a column vector, so their W has shape (n_out, n_in). Our code puts examples in rows and computes X @ W, so W is (n_in, n_out). Mixing the two conventions gives "shapes not aligned" errors, or, worse for square layers, silently wrong results.

Fix: pick one convention and write the shapes as comments next to every matrix product. If you port code from the other convention, use W.T.

Initialising all weights to zero (or the same value)

Every neuron in the layer then computes the same output and gets the same gradient, so they stay clones forever: a 64-unit layer behaves like a 1-unit layer.

Fix: random weights from a seeded generator, scaled with He (ReLU) or Xavier (tanh/sigmoid). Zero biases are fine.

"RuntimeWarning: overflow encountered in exp"

np.exp of a large number (about 710 in float64) is infinity; softmax then returns nan. Sigmoid on very negative inputs triggers the same warning.

Fix: subtract the row maximum in softmax (as the code does) and, for losses, use the fused, stable formulas from lesson 3.4 instead of computing probabilities and then taking their log.

Forgetting the activation between layers

The network still runs and still trains, but it can only learn straight-line boundaries, no matter how many layers it has.

Fix: print the model's layer list. Every hidden Dense layer should be followed by an activation; the last layer's activation depends on the task.

Key takeaways

  • A neuron computes z = w·x + b and outputs f(z); one neuron draws one straight boundary.
  • A Dense layer is many neurons at once: X @ W + b, with n_in·n_out + n_out parameters.
  • Non-linear activations are what let stacked layers represent curved boundaries; without them depth collapses.
  • Weights start random and correctly scaled (He for ReLU) so signals neither vanish nor explode.

Exercise: count and build a digit classifier's layers

A classic network for 28×28 pixel handwritten digits has layers 784 → 128 → 64 → 10 (ReLU after the first two, softmax at the end). (a) Count its parameters by hand. (b) Build it from the classes in layers.py, push a random batch of shape (32, 784) through it, and check that the output has shape (32, 10) and every row sums to 1.

Hint

Use n_in·n_out + n_out for each Dense layer. For (b), keep a list of layers and call forward on each in turn; np.allclose(out.sum(axis=1), 1.0) checks the rows.

Show a solution

(a) 784·128 + 128 = 100,480; 128·64 + 64 = 8,256; 64·10 + 10 = 650. Total 109,386 parameters. Note that almost all of them sit in the first layer, because it touches every pixel.

import numpy as np
from layers import Dense, ReLU, Softmax     # run next to layers.py

rng = np.random.default_rng(0)
net = [Dense(784, 128, rng), ReLU(), Dense(128, 64, rng), ReLU(),
       Dense(64, 10, rng, init="xavier"), Softmax()]
X = rng.normal(size=(32, 784))
out = X
for layer in net:
    out = layer.forward(out)
print(out.shape)                             # (32, 10)
print(np.allclose(out.sum(axis=1), 1.0))     # True
print(sum(l.W.size + l.b.size for l in net if isinstance(l, Dense)))   # 109386

Check your understanding

How many parameters does a Dense(3, 5) layer have?

  1. 15
  2. 20
  3. 8
3·5 = 15 weights plus 5 biases (one per output neuron) = 20. 15 forgets the biases; 8 adds the sizes instead of multiplying them.

You remove every activation function from a 10-layer network. What can it still learn?

  1. Anything the original network could, just more slowly
  2. Nothing at all: the gradients become zero
  3. Only what a single linear layer can learn
A composition of linear (affine) maps is one affine map, so the 10 layers collapse into one. Gradients are not zero (it trains fine), but it can only draw straight-line boundaries.

In layers.py, ten ReLU layers initialised with standard deviation 0.01 end with a signal spread of about 4e-10. Why is that a problem for training?

  1. The output barely depends on the input, and the gradients that flow back are similarly tiny, so learning stalls
  2. It is not a problem: small numbers are more precise
  3. The network runs out of memory
When the signal vanishes, every input produces nearly the same output and the backward pass multiplies by the same tiny weights, so updates are negligible. Precision and memory are not the issue.

Lesson 3.3Module 3: Neural network from scratch

Implement forward propagation

  • ⏱ 14 min read
  • Intermediate

Learning objectives

  • Trace a batch through a network layer by layer, predicting every intermediate shape.
  • Compute a forward pass by hand for a tiny network and check it against code.
  • Choose and compute the right loss: mean squared error, binary cross-entropy or categorical cross-entropy.
  • Explain why each layer caches values during the forward pass.

You have layers. Forward propagation (the forward pass) is simply running them in order: the output of one layer becomes the input of the next, until the last layer produces a prediction. Then a loss function turns "prediction versus correct answer" into a single number that says how wrong the network is. That number is what training will push down. This lesson builds both halves, and adds one small detail that makes the next lesson possible: every layer remembers what it saw.

Analogy: an assembly line with receipts

Think of a car assembly line. Each station takes the half-built car from the previous one, does its job and passes it on. At the end, an inspector compares the car with the specification and writes down one score: how far off it is. Now add one rule: every station keeps a receipt of exactly what it received. When the inspector later asks "who is responsible for this scratch?", each station can work out its share using its receipt. The forward pass is the assembly line, the loss is the inspector's score, and the receipts are the cached inputs that backpropagation needs in lesson 3.4.

The flow through a small network

Our running example is a 2-4-1 network for a yes/no question: 2 input features, a hidden layer of 4 ReLU neurons, and 1 output neuron with a sigmoid so the output can be read as a probability. Step through it with a batch of 5 examples and watch the shapes:

  1. A batch of 5 examples arrives, one per row, 2 features each: shape (5, 2).
  2. The first Dense layer multiplies by W1 (2, 4) and adds b1 (4,): every example now has 4 numbers. The layer caches X.
  3. ReLU zeroes the negative entries; the shape stays (5, 4). It caches which entries were positive.
  4. The second Dense layer maps 4 features to 1 number per example: the logits, shape (5, 1).
  5. Sigmoid squashes each logit into a probability between 0 and 1.
  6. The loss compares the 5 probabilities with the 5 labels and averages: one number for the whole batch.
The forward pass of a 2-4-1 network. Shapes change only at Dense layers; activations work element by element.

The raw outputs of the last Dense layer, before any sigmoid or softmax, are called logits. The word will follow you all the way to language models, where the final layer produces one logit per token in the vocabulary (lesson 5.4).

A forward pass by hand

Computing one example by hand is the best way to make sure nothing is hidden. Take a smaller 2-3-1 network with these weights (chosen to give round numbers):

StepComputation for x = (1.0, 2.0)Result
Hidden pre-activationsW1 = [[1, -1, 0.5], [0.5, 1, -1]], b1 = (0, 0.5, 0.2)
z₁ = 1·1 + 2·0.5 + 0, z₂ = 1·(-1) + 2·1 + 0.5, z₃ = 1·0.5 + 2·(-1) + 0.2
(2.0, 1.5, -1.3)
ReLUmax(0, z) element by elementh = (2.0, 1.5, 0.0)
Output logitW2 = (1, -1.5, 2), b2 = -0.3: 2·1 + 1.5·(-1.5) + 0·2 - 0.3-0.55
Sigmoid1 / (1 + e0.55)p ≈ 0.366
Loss if the label is 1-ln(0.366)≈ 1.005

Notice the third hidden neuron: its pre-activation was negative, so ReLU switched it off and its weight in W2 (the 2) had no influence at all on this example. The network says "36.6% chance of class 1", the truth is class 1, and the loss of about 1.0 says that is a fairly poor answer. Play with the same network below: move the inputs and flip the label to see every intermediate number change.

Forward pass of the 2-3-1 networkInteractive

Loss functions: turning "wrong" into a number

The loss must be small when predictions are right, large when they are wrong, and smooth enough that we can compute how it changes when a weight changes. Three cover almost everything you will meet.

Mean squared error (MSE) is the average squared difference. It is the natural choice when the target is a real number, such as a price or a temperature:

MSE=1N∑i=1N(y^i−yi)2

In words: for each of the N examples, square the gap between prediction and target, then average.

For classification we predict probabilities, and a better yardstick is how much probability the network gave to the correct answer. Binary cross-entropy (BCE) does this for yes/no labels:

BCE=−1N∑i=1N[yilnpi+(1−yi)ln(1−pi)]

In words: when the label is 1, the loss is minus the log of the probability given to 1; when it is 0, minus the log of the probability given to 0. Average over the batch.

Categorical cross-entropy (CCE) is the same idea for C classes: take the softmax probability of the correct class and add up minus its log, −1N∑lnpi,yi. This exact loss, with C equal to the vocabulary size, is what language models minimise during pretraining (lesson 2.4 covers the probability background).

Why the logarithm? It punishes confident mistakes very hard and confident correct answers hardly at all. If the right answer gets probability 0.9 the loss is 0.105; at 0.5 it is 0.693; at 0.1 it is 2.303; at 0.01 it is 4.605. MSE on probabilities would never go above 1, so a confidently wrong network would get a weak signal to change. Cross-entropy also has a clean gradient when combined with sigmoid or softmax, which you will derive next lesson.

The code

forward.py repeats the layer classes from lesson 3.2 (each lesson file runs on its own) with one change, the caches, and adds a Sequential container and the three losses.

# @run
# Lesson 3.3: forward propagation through a small network, plus the loss functions.
# Repeats the classes from layers.py (each lesson file runs on its own) and adds caching.
import numpy as np


class Dense:
    def __init__(self, n_in, n_out, rng):
        self.W = rng.normal(0.0, np.sqrt(2.0 / n_in), size=(n_in, n_out))
        self.b = np.zeros(n_out)

    def forward(self, X):
        self.X = X                      # cache the input: backward needs it (lesson 3.4)
        return X @ self.W + self.b


class ReLU:
    def forward(self, Z):
        self.Z = Z                      # cache: the gradient depends on which entries were > 0
        return np.maximum(0.0, Z)


class Sigmoid:
    def forward(self, Z):
        self.out = 1.0 / (1.0 + np.exp(-Z))   # cache the output: s * (1 - s) is its slope
        return self.out


class Sequential:
    def __init__(self, *layers):
        self.layers = list(layers)

    def forward(self, X, verbose=False):
        if verbose:
            print(f"{'input':16s} -> {X.shape}")
        for layer in self.layers:
            X = layer.forward(X)
            if verbose:
                print(f"{type(layer).__name__:16s} -> {X.shape}")
        return X


# ----- loss functions (forward only for now) -----
def mse(pred, target):
    return np.mean((pred - target) ** 2)


def binary_cross_entropy(p, y, eps=1e-12):
    p = np.clip(p, eps, 1.0 - eps)            # never take log(0)
    return -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))


def categorical_cross_entropy(probs, labels, eps=1e-12):
    picked = probs[np.arange(len(labels)), labels]   # probability given to the right class
    return -np.mean(np.log(np.clip(picked, eps, 1.0)))


if __name__ == "__main__":
    rng = np.random.default_rng(0)

    # A 2-4-1 network: 2 inputs, 4 hidden ReLU units, 1 sigmoid output.
    net = Sequential(Dense(2, 4, rng), ReLU(), Dense(4, 1, rng), Sigmoid())
    X = rng.normal(size=(5, 2))              # a batch of 5 points
    y = np.array([[1.0], [0.0], [1.0], [1.0], [0.0]])

    p = net.forward(X, verbose=True)
    print("predictions:", np.round(p.ravel(), 3))
    print("cached input of the 2nd Dense layer:", net.layers[2].X.shape)

    print(f"MSE  = {mse(p, y):.4f}")
    print(f"BCE  = {binary_cross_entropy(p, y):.4f}")

    # Cross-entropy rewards confident right answers and punishes confident wrong ones.
    for q in (0.9, 0.5, 0.1, 0.01):
        print(f"BCE for one example with y=1, p={q:<4}: {binary_cross_entropy(np.array([q]), np.array([1.0])):.3f}")

    # Categorical cross-entropy on 3 classes.
    probs = np.array([[0.7, 0.2, 0.1],
                      [0.1, 0.1, 0.8],
                      [0.3, 0.4, 0.3]])
    labels = np.array([0, 2, 0])
    print(f"CCE  = {categorical_cross_entropy(probs, labels):.4f}")
    print(f"CCE of a uniform guess over 3 classes = {categorical_cross_entropy(np.full((1, 3), 1 / 3), np.array([1])):.4f} (= ln 3)")
  1. self.X = X in Dense.forward: the receipt. The weight gradient in lesson 3.4 is computed from exactly this input.
  2. self.Z = Z in ReLU and self.out in Sigmoid: each activation caches whatever its own derivative will need (for sigmoid, its output s, because the slope is s(1 − s)).
  3. class Sequential: a list of layers and a loop. forward feeds each layer's output into the next; with verbose=True it prints every shape, which is the fastest way to debug a new architecture.
  4. mse: one line with np.mean.
  5. binary_cross_entropy: np.clip(p, eps, 1 - eps) keeps p away from exactly 0 and 1, because np.log(0) is minus infinity and would turn the whole loss into inf or nan.
  6. categorical_cross_entropy: probs[np.arange(len(labels)), labels] picks, for each row, the probability of that row's correct class (the fancy indexing from lesson 3.1).
  7. The main block builds the 2-4-1 network, runs a batch of 5 random points, and prints shapes, predictions and losses. Then it prints BCE for single predictions of 0.9, 0.5, 0.1 and 0.01, and the CCE of a uniform guess over 3 classes.
input            -> (5, 2)
Dense            -> (5, 4)
ReLU             -> (5, 4)
Dense            -> (5, 1)
Sigmoid          -> (5, 1)
predictions: [0.449 0.471 0.487 0.274 0.237]
cached input of the 2nd Dense layer: (5, 4)
MSE  = 0.2742
BCE  = 0.7440
BCE for one example with y=1, p=0.9 : 0.105
BCE for one example with y=1, p=0.5 : 0.693
BCE for one example with y=1, p=0.1 : 2.303
BCE for one example with y=1, p=0.01: 4.605
CCE  = 0.5946
CCE of a uniform guess over 3 classes = 1.0986 (= ln 3)

Read the output critically. The predictions all sit between 0.24 and 0.49: an untrained network with random weights produces mild, uninformed guesses. The BCE of 0.744 is close to ln 2 ≈ 0.693, the loss of always answering 0.5. The last line gives you a precious sanity check: a freshly initialised classifier with C classes should have a loss near ln C (1.0986 for three classes), because it should be roughly uniform. If your first loss is 15, something is broken before training even starts.

Logits, numerical stability and what a forward pass costs at scale

Work in logits. Computing a sigmoid and then taking log of it loses precision: for a logit of -40, the sigmoid rounds to about 4e-18 and the log is fine, but for -800 it rounds to 0 and the log is minus infinity. Mathematically, BCE can be written directly in terms of the logit z as ln(1+ez)−yz, which np.logaddexp(0, z) computes without overflow. Frameworks expose this as "with logits" losses (for example PyTorch's BCEWithLogitsLoss and cross_entropy, which take logits, not probabilities). From lesson 3.4 on, our networks output logits and the loss applies the sigmoid or softmax internally.

Training versus inference. During training every layer must keep its cache until the backward pass, so memory grows with batch size and depth. At inference time (just predicting) caches can be thrown away as soon as the next layer has run. Language models add their own special cache during generation, the key-value cache, which you will meet in module 5.

Cost. A Dense layer does about 2·n_in·n_out floating-point operations per example (a multiply and an add per weight). A widely used rule of thumb from the scaling-law literature is that a transformer's forward pass costs roughly 2 × (number of parameters) operations per token, and a training step about three times that, because the backward pass costs about twice the forward. These are Industry practice approximations, not exact figures for any particular model.

Common mistakes and debugging tips

Labels of shape (N,) against predictions of shape (N, 1)

pred - y with shapes (5, 1) and (5,) broadcasts to a (5, 5) matrix: every prediction minus every label. The loss is a number, the code doesn't crash, and the network trains towards nonsense.

Fix: make labels the same shape as predictions (y.reshape(-1, 1)) and put assert pred.shape == y.shape inside your loss function.

Applying sigmoid or softmax twice

A model that ends with a Sigmoid layer, fed into a loss that also applies a sigmoid, squashes probabilities into the narrow range 0.5–0.73. Training is slow and accuracy plateaus strangely.

Fix: decide where the squashing lives. From lesson 3.4 on, the model outputs logits and the fused loss applies the sigmoid or softmax once.

Loss is nan or inf on the first batch

Usually log(0) from a probability of exactly 0 or 1, or an overflow in exp.

Fix: clip probabilities, or better, compute the loss from logits with stable formulas. Use np.seterr(all="raise") while debugging so NumPy stops at the first bad operation.

Using MSE for classification

It works, sort of, but gives weak gradients for confident mistakes and doesn't produce well-behaved probabilities.

Fix: binary cross-entropy for yes/no, categorical cross-entropy for one-of-C, MSE for real-valued targets.

Key takeaways

  • The forward pass runs layers in order; only Dense layers change the shape.
  • The last Dense layer outputs logits; sigmoid or softmax turn them into probabilities.
  • Cross-entropy is minus the log of the probability given to the right answer; MSE is for real-valued targets.
  • An untrained C-class classifier should start near loss ln C: a quick sanity check.
  • Each layer caches what its backward pass will need.

Exercise: verify the hand calculation in code

Build the 2-3-1 network from the table above with the classes in forward.py, overwrite its random weights with the table's values, and run the input (1.0, 2.0). Print the hidden pre-activations, the logit, the probability and the BCE for label 1. Then change the input to (-1.0, 0.5) and predict, before running it, which hidden neurons will be switched off by ReLU.

Hint

After net = Sequential(Dense(2, 3, rng), ReLU(), Dense(3, 1, rng), Sigmoid()), assign net.layers[0].W = np.array([...]) and so on. W2 must have shape (3, 1), not (3,). After the forward pass, the ReLU layer's cache net.layers[1].Z holds the pre-activations.

Show a solution
import numpy as np
from forward import Dense, ReLU, Sigmoid, Sequential, binary_cross_entropy

rng = np.random.default_rng(0)
net = Sequential(Dense(2, 3, rng), ReLU(), Dense(3, 1, rng), Sigmoid())
net.layers[0].W = np.array([[1.0, -1.0, 0.5], [0.5, 1.0, -1.0]])
net.layers[0].b = np.array([0.0, 0.5, 0.2])
net.layers[2].W = np.array([[1.0], [-1.5], [2.0]])
net.layers[2].b = np.array([-0.3])

for x in ([1.0, 2.0], [-1.0, 0.5]):
    p = net.forward(np.array([x]))
    z1 = net.layers[1].Z                              # ReLU's cache: hidden pre-activations
    logit = net.layers[2].X @ net.layers[2].W + net.layers[2].b
    print(z1.round(3), logit.round(3), f"p={p[0, 0]:.4f}",
          f"BCE(y=1)={binary_cross_entropy(p, np.array([[1.0]])):.4f}")

For (1.0, 2.0) you get z1 = (2.0, 1.5, -1.3), logit -0.55, p = 0.3659 and BCE = 1.0055, matching the table. For (-1.0, 0.5): z₁ = -1 + 0.25 + 0 = -0.75, z₂ = 1 + 0.5 + 0.5 = 2.0, z₃ = -0.5 - 0.5 + 0.2 = -0.8, so neurons 1 and 3 are switched off and only neuron 2 reaches the output: logit = 2.0·(-1.5) - 0.3 = -3.3, p ≈ 0.036.

Check your understanding

A network classifies images into 10 classes and its loss on the very first batch, before any training, is 2.30. What does that suggest?

  1. The network is already well trained
  2. Things look healthy: ln 10 ≈ 2.30 is what a uniform random guess scores
  3. There is a bug: the loss should start at 0
An untrained classifier should be close to uniform, giving each class about 0.1, and −ln 0.1 = 2.30. A trained network would score much lower; a loss of exactly 0 at the start would mean perfect, impossible confidence.

Why does Dense.forward store self.X = X?

  1. The weight gradient in the backward pass is computed from the layer's input
  2. To make the forward pass faster next time
  3. So the optimiser can reset the input after each step
dL/dW = Xᵀ · dL/dY needs the input X that this layer received, so it is cached. Caching doesn't speed up later forward passes, and optimisers only touch parameters, never inputs.

For a single example with true label 1, which prediction gets the largest binary cross-entropy?

  1. p = 0.9
  2. p = 0.5
  3. p = 0.01
BCE is −ln p for label 1: 0.105, 0.693 and 4.605 respectively. Confident wrong answers (p = 0.01 for a true 1) are punished most.

Lesson 3.4Module 3: Neural network from scratch

Implement backpropagation

  • ⏱ 19 min read
  • Intermediate

Learning objectives

  • Explain a gradient as "how much the loss changes per unit change of one number", and apply the chain rule to a small computation graph.
  • Derive and implement the backward pass of a Dense layer: dW = Xᵀ·dY, db = sum of dY, dX = dY·Wᵀ.
  • Implement backward passes for ReLU, sigmoid and tanh, and the fused softmax + cross-entropy gradient p − y.
  • Prove your gradients are correct with a numerical gradient check.

The forward pass tells you how wrong the network is. To improve it you need to know, for each of its parameters, which way to move it and how strongly it matters. That information is the gradient of the loss with respect to every parameter, and backpropagation is the algorithm that computes all of them in one sweep backwards through the network, at roughly the cost of two more forward passes. It is the engine of all deep learning, including the training of every large language model, and after this lesson you will have written it yourself.

Analogy: a chain of gears

Imagine three gears in a row. Turn the first by one notch and the second turns 3 notches; each notch of the second turns the third by 2 notches. How far does the third turn per notch of the first? 3 × 2 = 6. That is the chain rule: rates of change multiply along a chain. A network is a long chain of simple steps, so the sensitivity of the loss to a weight deep inside is the product of the local sensitivities of every step between that weight and the loss. Backpropagation walks the chain from the loss end, multiplying as it goes, and hands each step its share.

What a gradient is

Take one weight w and freeze everything else. The loss becomes a function of w alone. Its derivative dL/dw is the slope of that function at the current w: if dL/dw = −4, nudging w up by a tiny 0.001 lowers the loss by about 0.004. The sign says which way is downhill, the size says how sensitive the loss is. The gradient is just the collection of these slopes for all parameters at once, with the same shape as the parameters themselves. In lesson 3.5 we will move every parameter a small step against its slope. (The calculus background is in lesson 2.5.)

You could estimate each slope by nudging each weight and re-running the network, but with a million weights that is a million forward passes per step. Backpropagation gets all of them exactly from one forward and one backward pass.

The chain rule on one neuron

Here is a single ReLU neuron with a squared-error loss, written as a chain of tiny steps: z = w·x + b, then a = ReLU(z), then L = (a − y)². With x = 2, w = 0.5, b = −0.5 and target y = 1.5, the forward pass gives z = 0.5, a = 0.5 and L = 1.0. Now go backwards, one local derivative at a time:

∂L∂w=∂L∂a·∂a∂z·∂z∂w=2(a−y)·1·x=(−2)·1·2=−4

In words: the loss's sensitivity to w is the product of three local slopes along the chain: loss to activation, 2(a − y) = −2; activation to pre-activation, 1 because z > 0 (ReLU's slope); pre-activation to weight, x = 2.

The other gradients reuse the shared part. The "upstream" gradient arriving at z is dL/dz = −2 · 1 = −2. Then dL/db = dL/dz · 1 = −2 (because z = wx + b changes one-for-one with b) and dL/dx = dL/dz · w = −1. That reuse is the whole trick of backpropagation: compute the gradient at each node once, then each input of that node gets "upstream gradient × local slope". Check the first one numerically: with w = 0.501, z = 0.502 and L = (0.502 − 1.5)² = 0.996004, a change of −0.003996 for a step of 0.001, so the slope is about −4. It matches.

Chain rule on one neuron, forward and backwardInteractive

Try a negative bias such as b = −1.5 with x = 0.5: z becomes negative, ReLU outputs 0, its local slope is 0, and every gradient upstream of it becomes zero. That neuron learns nothing from this example. If it happens for every example, the neuron is "dead", one of the classic ReLU failure modes.

The backward pass of a Dense layer

A layer receives the upstream gradient dY = ∂L/∂Y, one row per example and one column per output, and must return three things: gradients for its weights and bias (to update them) and a gradient for its input (to pass further back). The formulas are the chain rule applied to Y = XW + b, and the easiest way to remember them is that shapes only fit one way:

∂L∂W(nin,nout)=XT(nin,N)dY(N,nout)∂L∂b=∑i=1NdYi∂L∂X(N,nin)=dY(N,nout)WT(nout,nin)

In words: the weight gradient pairs each input feature with each output's error, summed over the batch; the bias gradient adds up the errors of all examples; the input gradient sends each output's error back through the same weights, transposed.

Why these? Weight Wkj connects input feature k to output j, and in example i it contributes Xik·Wkj to Yij. So its slope in that example is Xik times the upstream gradient dYij, exactly the single-neuron rule "upstream × x" from above. The weight is used in every example, so the contributions add up over the batch, and the sum over i of Xik·dYij is entry (k, j) of Xᵀ·dY. The bias is added to every row, so its gradient is the column sums of dY. The input Xik feeds every output j through Wkj, so its gradient sums dYij·Wkj over j: that is dY·Wᵀ.

Activations are simpler, because they act element by element: multiply the upstream gradient by the local slope. ReLU passes the gradient where its input was positive and blocks it elsewhere; sigmoid multiplies by s(1 − s); tanh by 1 − t². That is why each activation cached its input or output in lesson 3.3.

The beautiful shortcut: softmax + cross-entropy

You could backpropagate through the loss and then through softmax separately, but the combination simplifies dramatically. For one example with softmax probabilities p and a one-hot label vector y (1 for the correct class, 0 elsewhere), the gradient of cross-entropy with respect to the logits is:

∂L∂zj=pj−yj

In words: for each class, the gradient is "predicted probability minus truth". The correct class gets a negative gradient (raise its logit); every wrong class gets a positive gradient proportional to the probability it stole.

For logits (2.0, 1.0, 0.1) and correct class 0, softmax gives (0.659, 0.242, 0.099) and the gradient is (−0.341, 0.242, 0.099), which you will see in the output below. Sigmoid with binary cross-entropy gives the same shape of formula, p − y. Averaging the loss over a batch of N examples divides the gradient by N.

The code

Each layer now has backward and parameters methods. Sequential.backward calls the layers in reverse order. Two fused loss classes compute stable losses from logits and return p − y. A gradient_check function compares every analytic gradient against a numerical estimate.

# @run
# Lesson 3.4: backward passes for every layer, the combined softmax + cross-entropy
# gradient, and a numerical gradient check that proves the maths is right.
import numpy as np


class Dense:
    def __init__(self, n_in, n_out, rng):
        self.W = rng.normal(0.0, np.sqrt(2.0 / n_in), size=(n_in, n_out))
        self.b = np.zeros(n_out)

    def forward(self, X):
        self.X = X
        return X @ self.W + self.b

    def backward(self, dY):
        # dY: dLoss/dOutput, shape (batch, n_out)
        self.dW = self.X.T @ dY          # (n_in, batch) @ (batch, n_out) -> (n_in, n_out)
        self.db = dY.sum(axis=0)         # the bias touched every row, so add them up
        return dY @ self.W.T             # dLoss/dX, (batch, n_out) @ (n_out, n_in)

    def parameters(self):
        return [(self.W, self.dW), (self.b, self.db)]


class ReLU:
    def forward(self, Z):
        self.mask = Z > 0
        return Z * self.mask

    def backward(self, dA):
        return dA * self.mask            # gradient passes only where the input was positive

    def parameters(self):
        return []


class Sigmoid:
    def forward(self, Z):
        self.out = 1.0 / (1.0 + np.exp(-Z))
        return self.out

    def backward(self, dA):
        return dA * self.out * (1.0 - self.out)

    def parameters(self):
        return []


class Tanh:
    def forward(self, Z):
        self.out = np.tanh(Z)
        return self.out

    def backward(self, dA):
        return dA * (1.0 - self.out ** 2)

    def parameters(self):
        return []


class Sequential:
    def __init__(self, *layers):
        self.layers = list(layers)

    def forward(self, X):
        for layer in self.layers:
            X = layer.forward(X)
        return X

    def backward(self, grad):
        for layer in reversed(self.layers):
            grad = layer.backward(grad)
        return grad

    def parameters(self):
        return [pg for layer in self.layers for pg in layer.parameters()]


class SoftmaxCrossEntropy:
    """Softmax and categorical cross-entropy fused: simple, stable gradient (p - y) / N."""

    def forward(self, logits, labels):
        Z = logits - logits.max(axis=1, keepdims=True)
        log_probs = Z - np.log(np.exp(Z).sum(axis=1, keepdims=True))
        self.probs = np.exp(log_probs)
        self.labels = labels
        return -log_probs[np.arange(len(labels)), labels].mean()

    def backward(self):
        n = len(self.labels)
        grad = self.probs.copy()
        grad[np.arange(n), self.labels] -= 1.0      # p - one_hot(y)
        return grad / n


class SigmoidBCE:
    """Sigmoid and binary cross-entropy fused: gradient (p - y) / N as well."""

    def forward(self, logits, y):
        self.p = 1.0 / (1.0 + np.exp(-logits))
        self.y = y
        # log(1 + e^z) - y*z is BCE written directly in terms of z (no log(0) possible)
        return np.mean(np.logaddexp(0.0, logits) - y * logits)

    def backward(self):
        return (self.p - self.y) / len(self.y)


def gradient_check(net, loss_fn, X, y, h=1e-5):
    """Compare backprop gradients with central differences for every parameter."""
    loss_fn.forward(net.forward(X), y)
    net.backward(loss_fn.backward())
    worst = 0.0
    for k, (param, grad) in enumerate(net.parameters()):
        analytic = grad.copy()
        numeric = np.zeros_like(param)
        for i in np.ndindex(param.shape):
            old = param[i]
            param[i] = old + h
            plus = loss_fn.forward(net.forward(X), y)
            param[i] = old - h
            minus = loss_fn.forward(net.forward(X), y)
            param[i] = old
            numeric[i] = (plus - minus) / (2 * h)
        # one relative error per tensor: size of the difference vs size of the gradients
        rel = np.linalg.norm(analytic - numeric) / max(1e-12, np.linalg.norm(analytic) + np.linalg.norm(numeric))
        worst = max(worst, float(rel))
        print(f"  parameter {k}: shape {str(param.shape):8s} {'ok' if rel < 1e-7 else 'MISMATCH'}")
    return worst


if __name__ == "__main__":
    rng = np.random.default_rng(1)

    # 1. One Dense layer by hand: the three gradient formulas.
    d = Dense(2, 3, rng)
    X = np.array([[1.0, 2.0], [3.0, -1.0]])        # batch of 2
    d.forward(X)
    dY = np.array([[0.1, -0.2, 0.0], [0.3, 0.0, 0.1]])
    dX = d.backward(dY)
    print("dW = X.T @ dY:\n", np.round(d.dW, 3))
    print("db = sum of dY rows:", np.round(d.db, 3))
    print("dX shape:", dX.shape, "(same as X)")

    # 2. Softmax + cross-entropy gradient is just p - y.
    sce = SoftmaxCrossEntropy()
    sce.forward(np.array([[2.0, 1.0, 0.1]]), np.array([0]))
    print("softmax p:     ", np.round(sce.probs[0], 3))
    print("gradient p - y:", np.round(sce.backward()[0], 3))

    # 3. Gradient check: a 3-class network with ReLU and tanh.
    print("gradient check, softmax + cross-entropy network:")
    net = Sequential(Dense(4, 6, rng), ReLU(), Dense(6, 5, rng), Tanh(), Dense(5, 3, rng))
    Xc = rng.normal(size=(8, 4))
    yc = rng.integers(0, 3, size=8)
    worst1 = gradient_check(net, SoftmaxCrossEntropy(), Xc, yc)

    print("gradient check, sigmoid + binary cross-entropy network:")
    net2 = Sequential(Dense(2, 4, rng), Tanh(), Dense(4, 1, rng))
    Xb = rng.normal(size=(6, 2))
    yb = rng.integers(0, 2, size=(6, 1)).astype(np.float64)
    worst2 = gradient_check(net2, SigmoidBCE(), Xb, yb)

    if max(worst1, worst2) < 1e-7:
        print("gradient check passed: max relative error < 1e-7")
    else:
        print("gradient check FAILED: look for a wrong formula or a missing cache")
  1. self.dW = self.X.T @ dY, self.db = dY.sum(axis=0), return dY @ self.W.T: the three Dense formulas, using the cached input. The layer stores its own gradients and returns the input gradient.
  2. parameters() returns (array, gradient) pairs. Optimisers will receive this list and update the arrays in place.
  3. ReLU.backward: dA * self.mask, with the boolean mask cached in forward. Sigmoid and Tanh multiply by their cached-output slopes.
  4. Sequential.backward: for layer in reversed(self.layers), each layer's returned input gradient is the next one's upstream gradient: the chain rule as a loop.
  5. SoftmaxCrossEntropy.forward: computes log-probabilities as z − max − log Σ ez − max (the stable "log-sum-exp"), never taking the log of a rounded-off probability.
  6. backward: copies the probabilities, subtracts 1 at each row's correct class (grad[np.arange(n), labels] -= 1) and divides by the batch size n because the loss is a mean.
  7. SigmoidBCE: BCE in logit form, np.logaddexp(0, z) - y*z, with gradient (p − y)/N.
  8. gradient_check: runs forward and backward once to get the analytic gradients, then for every single parameter entry evaluates the loss at +h and −h and takes the slope (L₊ − L₋)/(2h). It reports one relative error per parameter tensor.
  9. The main block checks the Dense formulas on a hand-sized example, shows p − y, then gradient-checks two networks with ReLU, tanh, softmax and sigmoid losses.
dW = X.T @ dY:
 [[ 1.  -0.2  0.3]
 [-0.1 -0.4 -0.1]]
db = sum of dY rows: [ 0.4 -0.2  0.1]
dX shape: (2, 2) (same as X)
softmax p:      [0.659 0.242 0.099]
gradient p - y: [-0.341  0.242  0.099]
gradient check, softmax + cross-entropy network:
  parameter 0: shape (4, 6)   ok
  parameter 1: shape (6,)     ok
  parameter 2: shape (6, 5)   ok
  parameter 3: shape (5,)     ok
  parameter 4: shape (5, 3)   ok
  parameter 5: shape (3,)     ok
gradient check, sigmoid + binary cross-entropy network:
  parameter 0: shape (2, 4)   ok
  parameter 1: shape (4,)     ok
  parameter 2: shape (4, 1)   ok
  parameter 3: shape (1,)     ok
gradient check passed: max relative error < 1e-7

Verify the first block by hand: dW = Xᵀ·dY. Entry (0, 0) is 1·0.1 + 3·0.3 = 1.0, and entry (1, 1) is 2·(−0.2) + (−1)·0 = −0.4. The bias gradient (0.4, −0.2, 0.1) is the column sums of dY. Then every parameter of both networks passes the check with a relative error below 10−7. A wrong transpose, a forgotten division by N or a stale cache would show up as "MISMATCH" immediately.

∂L∂θ≈L(θ+h)−L(θ−h)2h,relative error=‖ganalytic−gnumeric‖‖ganalytic‖+‖gnumeric‖

In words: estimate each slope from two nearby loss values (the central difference, accurate to about h²), then compare the two gradient tensors relative to their size.

Reverse-mode autodiff, why p − y, and vanishing gradients

Why backwards? The loss is one number and there are many parameters. Computing derivatives from the output end (reverse mode) gets all of them in one pass, because every intermediate gradient is shared by everything before it. Going forwards (forward mode) would need one pass per input direction. This is why backpropagation costs about two forward passes, regardless of the number of parameters. PyTorch, JAX and TensorFlow implement exactly this: during the forward pass they record a graph of operations and their caches; loss.backward() walks it in reverse, calling a backward rule like ours for each operation.

Deriving p − y. With log-softmax, the loss for the correct class c is L=−zc+ln∑kezk. The derivative of the log-sum-exp term with respect to zj is ezj/∑kezk=pj, and the first term contributes −1 only when j = c. Together: pj − yj. No exponentials of huge numbers, no division by tiny probabilities: that is why every framework fuses the two.

Vanishing gradients. The chain rule multiplies local slopes. Sigmoid's slope is at most 0.25, so through ten sigmoid layers the gradient can shrink by a factor of up to 0.2510 ≈ 10−6. That is one reason ReLU-style activations, careful initialisation and residual connections (which add a path where the slope is exactly 1) made deep networks trainable. The opposite, exploding gradients, is handled in large-model training with gradient clipping (Industry practice).

Check with care. Gradient checks need float64 (float32 has too few digits for h = 1e-5), and ReLU has a kink at 0: if a pre-activation sits within h of zero, the numerical estimate straddles the kink and can disagree legitimately. Use small random inputs and a few examples, as the code does.

Common mistakes and debugging tips

Forgetting to divide by the batch size

If the loss is a mean but the gradient is a sum, gradients grow with batch size, so changing the batch size secretly changes the learning rate. The gradient check catches it as a constant factor N.

Fix: make the loss's backward return (p − y) / N when the forward returns a mean, and nowhere else.

Overwriting a cache before backward runs

If you call forward twice (for example to log the loss on another batch) before calling backward, the layers' caches now belong to the second batch and the gradients are wrong but plausible-looking.

Fix: always run forward → loss → backward → update for the same batch, and do any extra evaluation after the update. Our training loop in lesson 3.6 follows this order.

A transposed formula that happens to have the right shape

For square layers, dY @ W instead of dY @ W.T has the right shape and won't raise an error, but it is wrong.

Fix: gradient-check every new layer type with non-square shapes (as the code does with 4 → 6 → 5 → 3).

Modifying the upstream gradient in place

dA *= self.mask changes the array the next layer may still be using, and in our loss classes grad = self.probs without .copy() would corrupt the cached probabilities.

Fix: in backward passes, create new arrays (dA * self.mask) or copy before editing.

Key takeaways

  • A gradient is the slope of the loss with respect to each parameter; backprop gets all of them from one backward sweep.
  • Chain rule: upstream gradient × local slope, applied node by node from the loss back.
  • Dense: dW = Xᵀ·dY, db = Σ dY, dX = dY·Wᵀ. Activations multiply by their slope element by element.
  • Softmax/sigmoid + cross-entropy fuse into the simple, stable gradient (p − y)/N.
  • A numerical gradient check is the definitive test that your backward code is right.

Exercise: add Leaky ReLU and prove it with a gradient check

A Leaky ReLU outputs z for z > 0 and αz (with α = 0.01) otherwise, so its slope is never exactly 0 and neurons can't die completely. Write a LeakyReLU class with forward, backward and parameters, put it into the 3-class network in backprop.py instead of ReLU, and make the gradient check pass.

Hint

Cache the mask Z > 0. The slope is 1 where the mask is true and α elsewhere: np.where(self.mask, 1.0, self.alpha). It has no parameters, so parameters() returns an empty list.

Show a solution
import numpy as np
from backprop import Dense, Tanh, Sequential, SoftmaxCrossEntropy, gradient_check
class LeakyReLU:
    def __init__(self, alpha=0.01):
        self.alpha = alpha
    def forward(self, Z):
        self.mask = Z > 0
        return np.where(self.mask, Z, self.alpha * Z)
    def backward(self, dA):
        return dA * np.where(self.mask, 1.0, self.alpha)
    def parameters(self):
        return []

rng = np.random.default_rng(1)
net = Sequential(Dense(4, 6, rng), LeakyReLU(), Dense(6, 5, rng), Tanh(), Dense(5, 3, rng))
print(gradient_check(net, SoftmaxCrossEntropy(), rng.normal(size=(8, 4)), rng.integers(0, 3, size=8)))

Every parameter prints ok and the returned worst relative error is far below 1e-7. Try breaking it on purpose (return dA * self.mask, forgetting α) and watch the first Dense layer's check turn into MISMATCH.

Check your understanding

A Dense layer has input X of shape (32, 10) and weights of shape (10, 4). What is the shape of dW, and how is it computed?

  1. (32, 4), as X · W
  2. (4, 10), as dYᵀ · X
  3. (10, 4), as Xᵀ · dY
A gradient always has the same shape as its parameter, (10, 4), and Xᵀ (10, 32) times dY (32, 4) is the only product of the available arrays with that shape. (32, 4) is the shape of the output; dYᵀ · X has the transposed shape.

Softmax gives (0.7, 0.2, 0.1) and the correct class is 1 (the middle one). What is the gradient of the cross-entropy with respect to the logits?

  1. (0.7, −0.8, 0.1)
  2. (−0.3, 0.2, 0.1)
  3. (0.7, 0.2, 0.1)
p − y with y = (0, 1, 0) gives (0.7, −0.8, 0.1): raise the correct logit, lower the others. Option 2 treats class 0 as correct; option 3 forgets to subtract the label.

Why does a ReLU neuron whose pre-activation is negative for every training example stop learning?

  1. Its weights become infinite
  2. ReLU's slope is 0 there, so every gradient flowing to that neuron's weights and bias is multiplied by 0
  3. The optimiser skips neurons with negative outputs on purpose
The chain rule multiplies by the local slope, which is 0 for negative inputs, so the neuron's parameters receive zero gradient and never change. Nothing becomes infinite, and optimisers simply apply whatever gradient they get.

Lesson 3.5Module 3: Neural network from scratch

Implement gradient descent

  • ⏱ 15 min read
  • Intermediate

Learning objectives

  • Write the gradient-descent update and explain what the learning rate controls.
  • Predict when a learning rate is too large, using the curvature of the loss.
  • Implement SGD, momentum and Adam as optimisers that update parameters in place.
  • Use mini-batches, epochs and learning-rate schedules, and explain the trade-offs.

Backpropagation tells you the slope of the loss for every parameter. Gradient descent uses it: move every parameter a small step in the direction that lowers the loss, recompute, repeat. Everything else in this lesson, momentum, Adam, mini-batches and schedules, is a refinement of that single idea. The same refinements, scaled up, are what train large language models.

Analogy: walking downhill in thick fog

You are on a hillside in fog so thick you can only feel the slope under your feet. To reach the valley floor you repeatedly feel which way is steepest downhill and take a step that way. The learning rate is your stride length. Tiny strides are safe but take all day. Huge strides overshoot: in a narrow ravine you leap from one wall to the opposite wall, higher each time. Momentum is like being a heavy ball rather than a hiker: you build up speed along a long gentle slope and your sideways wobbles cancel out.

The update rule

θ←θ−η∂L∂θ

In words: for every parameter θ, subtract the learning rate η (eta) times its gradient. A positive slope means "loss rises if θ grows", so θ shrinks, and vice versa.

In code this is one line per parameter: p -= lr * g. The -= matters: it modifies the layer's own array in place, so the next forward pass sees the new weights. That is why our layers expose (parameter, gradient) pairs: an optimiser can loop over them without knowing anything about layers.

Gradient descent only uses local information. It does not know where the minimum is, only which way is downhill right here. For the losses of neural networks, which are not simple bowls, it is not guaranteed to find the best possible weights. In practice, for large networks, it reliably finds weights that are very good, and understanding exactly why is still an active research area.

The learning rate, and the narrow valley

To see the learning rate's effect clearly, use a loss we fully understand: L=0.5(w02+50w12). Its minimum is at (0, 0), but it is 50 times steeper in the w₁ direction than in w₀: a long, narrow valley. Real loss surfaces have many such directions of very different steepness. The gradient is (w₀, 50·w₁), so one SGD step multiplies w₁ by (1 − 50η). If |1 − 50η| > 1, w₁ grows every step instead of shrinking:

|1−ηλ|<1⟺η<2λmax=250=0.04

In words: along a direction with curvature λ, plain gradient descent is stable only if the learning rate is below 2/λ. The steepest direction sets the limit for the whole model.

That gives the dilemma: the learning rate must be below 0.04 to survive the steep direction, but at that rate the gentle direction (curvature 1) shrinks by only 4% per step. Try it below. With SGD at 0.035 the path zig-zags across the valley and creeps along it; at 0.041 it explodes. Switch to momentum or Adam and watch them handle the valley far better.

Optimisers in a narrow valleyInteractive

Momentum and Adam

Momentum keeps a running "velocity" v: each step it keeps 90% of the old velocity and adds the new gradient, then moves by the velocity. In the narrow valley, the steep direction's gradient flips sign every step, so those contributions largely cancel; the gentle direction's gradient always points the same way, so it accumulates. The ball speeds up along the valley floor.

v←βv+g,θ←θ−ηv

In words: velocity is a decaying sum of past gradients (β = 0.9 keeps roughly the last ten steps' worth), and the parameter moves by the velocity.

Adam (Kingma and Ba, 2014) combines momentum with a per-parameter step size. It keeps two running averages for each parameter: m, the average gradient (direction), and v, the average squared gradient (typical size). It then steps by m divided by the square root of v, so every parameter moves at roughly the learning rate per step, whether its gradients are huge or tiny. In the valley, that rescales the steep and gentle directions to similar step sizes, which is like straightening the valley into a round bowl.

m←β1m+(1−β1)g,v←β2v+(1−β2)g2m^=m1−β1t,v^=v1−β2t,θ←θ−ηm^v^+ε

In words: track the average gradient and the average squared gradient; correct both for starting at zero (step t); move by "average direction divided by typical size". Defaults: β₁ = 0.9, β₂ = 0.999, ε = 10⁻⁸.

Adam, and its variant AdamW with decoupled weight decay, is the default optimiser in most published transformer training recipes; that is Industry practice. The optimiser and hyperparameters used for Claude are Not public.

Mini-batches and epochs

So far "the loss" meant the loss over all training data. Computing that exact gradient for every step (full-batch gradient descent) is expensive when there are millions of examples. Instead, we estimate it from a small random sample, a mini-batch of typically 16 to a few thousand examples. The estimate is noisy but unbiased: on average it points the right way. You take many more, cheaper steps, and the noise can even help escape poor regions. One pass over the whole shuffled training set is an epoch. Strictly, "stochastic gradient descent" means batches of one example, but "SGD" is now used for any mini-batch version.

Shuffling matters. If the data were sorted by class, the first batches would contain only class 0, and the network would lurch from "everything is 0" to "everything is 1" every epoch.

Learning-rate schedules

Early in training, big steps make fast progress; near the end, small steps settle into a minimum instead of bouncing around it. A schedule changes the learning rate over time. Step decay halves it every few epochs; cosine decay lowers it smoothly along half a cosine wave to near zero. Large-model training typically adds a short warm-up, increasing the rate from near zero over the first steps, because Adam's statistics are unreliable at the very start (Industry practice).

The code

# @run
# Lesson 3.5: gradient descent and its upgrades (momentum, Adam), mini-batches and
# learning-rate schedules. Optimisers take a list of (parameter, gradient) pairs and
# update the parameters IN PLACE, so the layers see the new values.
import math

import numpy as np


class SGD:
    def __init__(self, lr=0.1):
        self.lr = lr

    def step(self, params):
        for p, g in params:
            p -= self.lr * g                       # in place: p is the layer's own array


class Momentum:
    def __init__(self, lr=0.1, beta=0.9):
        self.lr, self.beta = lr, beta
        self.v = None

    def step(self, params):
        if self.v is None:
            self.v = [np.zeros_like(p) for p, _ in params]
        for (p, g), v in zip(params, self.v):
            v *= self.beta                         # keep 90% of the old velocity
            v += g                                 # add the new gradient
            p -= self.lr * v


class Adam:
    def __init__(self, lr=0.01, beta1=0.9, beta2=0.999, eps=1e-8):
        self.lr, self.beta1, self.beta2, self.eps = lr, beta1, beta2, eps
        self.m = self.v = None
        self.t = 0

    def step(self, params):
        if self.m is None:
            self.m = [np.zeros_like(p) for p, _ in params]
            self.v = [np.zeros_like(p) for p, _ in params]
        self.t += 1
        for (p, g), m, v in zip(params, self.m, self.v):
            m *= self.beta1
            m += (1 - self.beta1) * g              # running mean of gradients (direction)
            v *= self.beta2
            v += (1 - self.beta2) * g * g          # running mean of squared gradients (scale)
            m_hat = m / (1 - self.beta1 ** self.t) # bias correction: m and v start at 0
            v_hat = v / (1 - self.beta2 ** self.t)
            p -= self.lr * m_hat / (np.sqrt(v_hat) + self.eps)


def iterate_minibatches(X, y, batch_size, rng):
    """One epoch: shuffle once, then hand out consecutive slices."""
    order = rng.permutation(len(X))
    for start in range(0, len(X), batch_size):
        idx = order[start:start + batch_size]
        yield X[idx], y[idx]


def step_decay(lr0, epoch, drop=0.5, every=10):
    return lr0 * drop ** (epoch // every)


def cosine(lr0, epoch, total):
    return 0.5 * lr0 * (1 + math.cos(math.pi * epoch / total))


if __name__ == "__main__":
    # 1. A long, narrow valley: loss = 0.5 * (w0^2 + 50 * w1^2), minimum at (0, 0).
    curv = np.array([1.0, 50.0])

    def run(opt, steps=100):
        w = np.array([-4.0, 1.0])
        losses = []
        for _ in range(steps + 1):
            losses.append(0.5 * float(np.sum(curv * w * w)))
            grad = curv * w
            opt.step([(w, grad)])
        return losses

    print("loss on a narrow valley (start = 33.0)")
    print(f"{'optimiser':24s} {'step 10':>10s} {'step 50':>10s} {'step 100':>10s}")
    for name, opt in [("SGD lr=0.035", SGD(0.035)),
                      ("SGD lr=0.041 (too big)", SGD(0.041)),
                      ("Momentum lr=0.01", Momentum(0.01, 0.9)),
                      ("Adam lr=0.1", Adam(0.1))]:
        L = run(opt)
        print(f"{name:24s} {L[10]:10.4f} {L[50]:10.4f} {L[100]:10.4g}")

    # 2. Mini-batches: 10 examples, batch size 4 -> batches of 4, 4 and 2.
    rng = np.random.default_rng(0)
    X = np.arange(10).reshape(10, 1)
    y = np.arange(10)
    for epoch in range(2):
        batches = [b_y.tolist() for _, b_y in iterate_minibatches(X, y, 4, rng)]
        print(f"epoch {epoch}: batches {batches}")

    # 3. Learning-rate schedules starting at 0.1 for 30 epochs.
    for e in (0, 10, 20, 29):
        print(f"epoch {e:2d}: step decay {step_decay(0.1, e):.4f}   cosine {cosine(0.1, e, 30):.4f}")
  1. SGD.step: p -= self.lr * g for each pair. In place, so the layer's arrays change.
  2. Momentum: creates one zero velocity array per parameter on the first call (np.zeros_like), then v *= beta; v += g; p -= lr * v, all in place.
  3. Adam: two state arrays per parameter and a step counter t. The bias corrections divide by 1 − βt, which is 0.1 for m at step 1, compensating for m and v starting at zero.
  4. iterate_minibatches: a generator that shuffles indices once per epoch with the seeded rng and yields consecutive slices. The last batch can be smaller.
  5. step_decay and cosine: schedules as pure functions of the epoch.
  6. run(opt): starts at (−4, 1), where the loss is 0.5·(16 + 50) = 33, and records the loss over 100 steps. The table prints the loss at steps 10, 50 and 100.
  7. The mini-batch block prints which labels land in which batch for two epochs: different order each epoch, every example exactly once.
loss on a narrow valley (start = 33.0)
optimiser                   step 10    step 50   step 100
SGD lr=0.035                 4.0024     0.2269   0.006435
SGD lr=0.041 (too big)      69.7955  3287.6531  4.323e+05
Momentum lr=0.01             3.2783     0.1520  0.0002643
Adam lr=0.1                  4.6751     0.0270  0.0004452
epoch 0: batches [[4, 6, 2, 7], [3, 5, 9, 0], [8, 1]]
epoch 1: batches [[2, 9, 3, 6], [0, 4, 8, 7], [5, 1]]
epoch  0: step decay 0.1000   cosine 0.1000
epoch 10: step decay 0.0500   cosine 0.0750
epoch 20: step decay 0.0250   cosine 0.0250
epoch 29: step decay 0.0250   cosine 0.0003

The numbers confirm the theory. SGD at 0.035 (just under the 0.04 limit) reaches 0.0064 after 100 steps, slowed by the gentle direction. At 0.041, just over the limit, the loss grows to 432,300: divergence from a 17% larger learning rate. Momentum at a learning rate of only 0.01 reaches 0.00026, and Adam at 0.1 reaches 0.00045. Notice that Adam's learning rate means something different (roughly "step size per parameter"), so learning rates are not comparable across optimisers. The schedule lines show step decay halving every 10 epochs and cosine falling smoothly to almost zero at epoch 29.

Curvature, saddle points, batch size and weight decay

Curvature in many dimensions. Near a minimum, any smooth loss looks like a bowl described by its matrix of second derivatives, the Hessian. Its eigenvalues are the curvatures λ along its principal directions, and the 2/λmax stability limit applies to the largest. The ratio of largest to smallest curvature (the condition number) measures how "narrow" the valley is; ours is 50. Momentum and Adam are, in effect, cheap ways to cope with bad conditioning without ever computing the Hessian, which would have (number of parameters)² entries.

Saddle points. In millions of dimensions, a point where the gradient is zero is far more likely to be a saddle (downhill in some directions) than a true local minimum. Noise from mini-batches and momentum both help move off saddles.

Batch size. A batch of size B reduces gradient noise roughly like 1/√B, so beyond some point, bigger batches give diminishing returns per example processed. Large-model training uses very large batches (counted in millions of tokens), spread across many accelerators, with the learning rate tuned together with the batch size. These are Industry practice patterns from public papers.

Weight decay. Adding λ2‖θ‖2 to the loss adds λθ to the gradient and gently pulls weights towards zero (you will use it in lesson 3.6 as L2 regularisation). With Adam, adding it to the gradient interacts with the per-parameter scaling; AdamW (Loshchilov and Hutter) applies the decay directly to the weights instead, which is the form most transformer recipes use.

Common mistakes and debugging tips

Writing p = p - lr * g inside the optimiser

This creates a new array and binds it to the local name p. The layer still holds the old array, so nothing trains, the loss never moves, and there is no error.

Fix: update in place with p -= lr * g (or p[...] = …). If the loss is perfectly flat from the first step, suspect this first.

Loss becomes nan after a few steps

Usually the learning rate is above the stability limit for some direction: values grow each step until they overflow.

Fix: divide the learning rate by 10 and retry. A learning-rate sweep (0.1, 0.03, 0.01, 0.003…) on a short run is the fastest way to find a good one.

Reusing an optimiser between two models or experiments

Momentum and Adam keep state arrays matched to the parameter list. Reusing them carries old velocities into a new run, or crashes when shapes differ.

Fix: create a fresh optimiser for each model and each experiment, as our training code does.

Forgetting to shuffle between epochs

Batches then contain the same examples in the same order every epoch, and if the data was sorted, each batch is unrepresentative. Training becomes erratic.

Fix: draw a new rng.permutation every epoch.

Key takeaways

  • Gradient descent: θ ← θ − η·∂L/∂θ, applied in place to every parameter.
  • The learning rate must stay below 2/λmax for the steepest direction, which slows progress along gentle directions.
  • Momentum accumulates consistent directions; Adam rescales each parameter's step by its typical gradient size.
  • Mini-batches give cheap, noisy gradient estimates; shuffle every epoch; decay the learning rate over time.

Exercise: implement RMSProp and predict a stability limit

(a) Without running anything, what is the largest stable SGD learning rate for the loss 0.5·(w₀² + 10·w₁²)? (b) Implement RMSProp, Adam's ancestor: keep a running average of squared gradients, s = 0.9*s + 0.1*g*g, and step by lr * g / (sqrt(s) + 1e-8). Add it to the comparison table in optimizers.py with lr=0.01 and compare it with Adam.

Hint

(a) The curvatures are 1 and 10. (b) Copy the structure of Momentum: lazily create one zero array per parameter on the first call, then update everything in place.

Show a solution

(a) η < 2/10 = 0.2.

class RMSProp:
    def __init__(self, lr=0.01, beta=0.9, eps=1e-8):
        self.lr, self.beta, self.eps = lr, beta, eps
        self.s = None

    def step(self, params):
        if self.s is None:
            self.s = [np.zeros_like(p) for p, _ in params]
        for (p, g), s in zip(params, self.s):
            s *= self.beta
            s += (1 - self.beta) * g * g             # running mean of g squared
            p -= self.lr * g / (np.sqrt(s) + self.eps)

# in the table:  ("RMSProp lr=0.01", RMSProp(0.01)),

Because it divides by the typical gradient size, RMSProp moves every parameter by roughly the learning rate per step, however steep or gentle its direction. At lr=0.01 that is slow here: w₀ only travels from −4 to about −2.9 in 100 steps, and the loss is still about 4.5 (Adam at 0.1 reaches 0.00045). At lr=0.03 RMSProp reaches about 0.54. The lesson: adaptive optimisers fix the conditioning problem (w₁ is solved almost immediately), but the learning rate still sets the pace, and without a decaying learning rate the steps never shrink much near the minimum.

Check your understanding

The loss has curvature 200 in its steepest direction. Which SGD learning rate will diverge?

  1. 0.005
  2. 0.02
  3. 0.009
The limit is 2/200 = 0.01. 0.02 exceeds it, so the steep direction grows every step. 0.005 and 0.009 are below the limit (0.009 will oscillate but shrink).

Your loss stays exactly the same from the first step, with no errors. Which bug is most likely?

  1. The learning rate is slightly too large
  2. You forgot to shuffle the data
  3. The optimiser rebinds a local name (p = p - lr*g) instead of updating the layer's array in place
Rebinding leaves the layer's weights untouched, so the network never changes. A too-large learning rate makes the loss jump or explode, not freeze; missing shuffling makes training erratic, not perfectly flat.

What does Adam's second running average, v, do?

  1. Tracks each parameter's typical squared gradient so the step can be divided by its square root, equalising step sizes across parameters
  2. Stores the previous parameter values so steps can be undone
  3. Counts how many steps have been taken
v is a running mean of g²; dividing by √v rescales each parameter's step. The step counter is t (used for bias correction), and Adam never stores old parameter values.

Lesson 3.6Module 3: Neural network from scratch

Train a small neural network without PyTorch or TensorFlow

  • ⏱ 19 min read
  • Intermediate

Learning objectives

  • Assemble data, model, loss and optimiser into a complete training loop in NumPy.
  • Split data into training and validation sets and explain why the split is essential.
  • Train a network that learns a curved decision boundary, and read its progress from the logs.
  • Recognise overfitting and reduce it with L2 regularisation, interpreting the results honestly.

Every piece is ready: layers (lesson 3.2), a forward pass and losses (3.3), gradients (3.4) and optimisers (3.5). This lesson puts them together into the loop that every neural network on earth is trained with, from this 337-parameter toy to large language models. Then you will watch it learn something a straight line can't: two interlocking half-moons.

Analogy: practice papers and the real exam

A student preparing for an exam works through practice papers, checks the answers and adjusts. If they practise on the same ten papers for months, they can end up memorising those exact answers, scoring 100% on them while still failing new questions. A sensible teacher keeps a few papers aside that the student never practises on and uses them to check real understanding. The training set is the practice papers; the validation set is the papers kept aside. Only the validation score tells you whether the network learned the pattern or just memorised the examples.

The training loop

Training repeats four steps for every mini-batch, and repeats the whole pass over the data for many epochs:

  1. Each epoch, shuffle the training set and cut it into batches of 32.
  2. Forward: run the batch through the network to get logits. Every layer caches its input.
  3. Loss: compare logits with labels using sigmoid + binary cross-entropy. One number.
  4. Backward: start from (p − y)/N and walk the layers in reverse, filling every dW and db.
  5. Update: the optimiser moves every parameter against its gradient, in place.
  6. Next batch: repeat until the epoch is done.
  7. After each epoch (or every few), measure loss and accuracy on the full training and validation sets, without updating anything.
The training loop. Forward, loss, backward, update: the same four steps train every neural network, whatever its size.

The data: two moons

Our dataset is "two moons": 600 points in two interleaving half-circles, one per class, with random noise added so the classes overlap a little. No straight line separates them, so a linear model must fail, but a small network with a hidden layer can bend its boundary around the moons. We hold out 25% of the points (150) as a validation set, train on the other 450, and never let validation points influence a weight update. Because of the noise, some points sit on the wrong side of any sensible boundary, so 100% accuracy on fresh data is not a realistic goal; something in the low-to-mid 90s is about as good as it gets with this much noise.

The complete program

train.py repeats the library from lessons 3.2–3.5 (so it runs on its own), adds the data, the loop, a text-mode picture of the decision regions and an overfitting experiment.

# @run
# Lesson 3.6: train a small neural network on the "two moons" dataset with NumPy only.
# Self-contained: it repeats the layers, loss and optimiser from lessons 3.2-3.5.
import numpy as np


# ---------- the library built in lessons 3.2-3.5 ----------
class Dense:
    def __init__(self, n_in, n_out, rng):
        self.W = rng.normal(0.0, np.sqrt(2.0 / n_in), size=(n_in, n_out))   # He init
        self.b = np.zeros(n_out)

    def forward(self, X):
        self.X = X
        return X @ self.W + self.b

    def backward(self, dY):
        self.dW = self.X.T @ dY
        self.db = dY.sum(axis=0)
        return dY @ self.W.T

    def parameters(self):
        return [(self.W, self.dW), (self.b, self.db)]


class ReLU:
    def forward(self, Z):
        self.mask = Z > 0
        return Z * self.mask

    def backward(self, dA):
        return dA * self.mask

    def parameters(self):
        return []


class Sequential:
    def __init__(self, *layers):
        self.layers = list(layers)

    def forward(self, X):
        for layer in self.layers:
            X = layer.forward(X)
        return X

    def backward(self, grad):
        for layer in reversed(self.layers):
            grad = layer.backward(grad)

    def parameters(self):
        return [pg for layer in self.layers for pg in layer.parameters()]

    def dense_layers(self):
        return [layer for layer in self.layers if isinstance(layer, Dense)]


class SigmoidBCE:
    def forward(self, logits, y):
        self.p = 1.0 / (1.0 + np.exp(-logits))
        self.y = y
        return float(np.mean(np.logaddexp(0.0, logits) - y * logits))

    def backward(self):
        return (self.p - self.y) / len(self.y)


class Adam:
    def __init__(self, lr=0.01, beta1=0.9, beta2=0.999, eps=1e-8):
        self.lr, self.beta1, self.beta2, self.eps = lr, beta1, beta2, eps
        self.m = self.v = None
        self.t = 0

    def step(self, params):
        if self.m is None:
            self.m = [np.zeros_like(p) for p, _ in params]
            self.v = [np.zeros_like(p) for p, _ in params]
        self.t += 1
        for (p, g), m, v in zip(params, self.m, self.v):
            m *= self.beta1
            m += (1 - self.beta1) * g
            v *= self.beta2
            v += (1 - self.beta2) * g * g
            m_hat = m / (1 - self.beta1 ** self.t)
            v_hat = v / (1 - self.beta2 ** self.t)
            p -= self.lr * m_hat / (np.sqrt(v_hat) + self.eps)


# ---------- data ----------
def make_moons(n, noise, rng):
    """Two interleaving half circles: a classic dataset no straight line can separate."""
    n0 = n // 2
    t0 = rng.uniform(0, np.pi, n0)
    t1 = rng.uniform(0, np.pi, n - n0)
    upper = np.column_stack([np.cos(t0), np.sin(t0)])
    lower = np.column_stack([1 - np.cos(t1), 0.5 - np.sin(t1)])
    X = np.vstack([upper, lower]) + rng.normal(0, noise, size=(n, 2))
    y = np.concatenate([np.zeros(n0), np.ones(n - n0)]).reshape(-1, 1)
    return X, y


def train_val_split(X, y, val_fraction, rng):
    order = rng.permutation(len(X))
    n_val = int(len(X) * val_fraction)
    val, tr = order[:n_val], order[n_val:]
    return X[tr], y[tr], X[val], y[val]


# ---------- training ----------
def accuracy(net, X, y):
    return float(np.mean((net.forward(X) > 0) == (y > 0.5)))   # logit > 0  <=>  p > 0.5


def evaluate(net, loss_fn, X, y):
    return loss_fn.forward(net.forward(X), y), accuracy(net, X, y)


def train(net, X_tr, y_tr, X_val, y_val, rng, epochs=200, batch_size=32, lr=0.01,
          l2=0.0, log_every=0):
    loss_fn = SigmoidBCE()
    opt = Adam(lr)
    for epoch in range(1, epochs + 1):
        order = rng.permutation(len(X_tr))                       # shuffle every epoch
        for start in range(0, len(X_tr), batch_size):
            idx = order[start:start + batch_size]
            logits = net.forward(X_tr[idx])                      # 1. forward
            loss_fn.forward(logits, y_tr[idx])                   # 2. loss
            net.backward(loss_fn.backward())                     # 3. backward
            if l2:
                for layer in net.dense_layers():                 # L2: pull weights towards 0
                    layer.dW += l2 * layer.W
            opt.step(net.parameters())                           # 4. update
        if log_every and (epoch % log_every == 0 or epoch == 1):
            tr_loss, tr_acc = evaluate(net, loss_fn, X_tr, y_tr)
            va_loss, va_acc = evaluate(net, loss_fn, X_val, y_val)
            print(f"epoch {epoch:4d}  train loss {tr_loss:.4f} acc {tr_acc:6.1%}"
                  f"  |  val loss {va_loss:.4f} acc {va_acc:6.1%}")
    return net


def ascii_plot(net, X, y, width=60, height=22):
    """Decision regions as text: '.' = class 0, '+' = class 1, o/x = data points."""
    x_min, x_max, y_min, y_max = -1.6, 2.6, -1.1, 1.6
    xs = np.linspace(x_min, x_max, width)
    ys = np.linspace(y_max, y_min, height)                       # top row = largest y
    gx, gy = np.meshgrid(xs, ys)
    pred = net.forward(np.column_stack([gx.ravel(), gy.ravel()])) > 0
    grid = np.where(pred.reshape(height, width), "+", ".").astype("<U1")
    for (px, py), label in zip(X, y.ravel()):
        col = int(round((px - x_min) / (x_max - x_min) * (width - 1)))
        row = int(round((y_max - py) / (y_max - y_min) * (height - 1)))
        if 0 <= col < width and 0 <= row < height:
            grid[row, col] = "x" if label > 0.5 else "o"
    print("\n".join("".join(r) for r in grid))


if __name__ == "__main__":
    rng = np.random.default_rng(0)
    X, y = make_moons(600, noise=0.3, rng=rng)
    X_tr, y_tr, X_val, y_val = train_val_split(X, y, 0.25, rng)
    print(f"train {X_tr.shape[0]} points, validation {X_val.shape[0]} points")

    net = Sequential(Dense(2, 16, rng), ReLU(), Dense(16, 16, rng), ReLU(), Dense(16, 1, rng))
    print(f"parameters: {sum(p.size for l in net.dense_layers() for p in (l.W, l.b))}")
    train(net, X_tr, y_tr, X_val, y_val, rng, epochs=150, lr=0.003, log_every=30)

    print("\ndecision regions on the validation set ('.' class 0, '+' class 1, o/x points):")
    ascii_plot(net, X_val, y_val)

    # Overfitting: a big network, only 30 noisy training points, many epochs.
    print("\noverfitting experiment: 30 training points, 2-64-64-1 network, 800 epochs")
    Xs, ys_ = X_tr[:30], y_tr[:30]
    for l2 in (0.0, 0.01):
        r = np.random.default_rng(7)
        big = Sequential(Dense(2, 64, r), ReLU(), Dense(64, 64, r), ReLU(), Dense(64, 1, r))
        train(big, Xs, ys_, X_val, y_val, r, epochs=800, batch_size=30, lr=0.01, l2=l2)
        lf = SigmoidBCE()
        tl, ta = evaluate(big, lf, Xs, ys_)
        vl, va = evaluate(big, lf, X_val, y_val)
        print(f"L2 = {l2:<5}: train loss {tl:.4f} acc {ta:6.1%}  |  val loss {vl:.4f} acc {va:6.1%}")
  1. make_moons: draws angles uniformly in [0, π] and places class 0 on an upper half-circle and class 1 on a shifted lower one, then adds Gaussian noise. Labels have shape (n, 1) to match the network's output.
  2. train_val_split: shuffles indices once and keeps 25% aside. Shuffling before splitting matters because make_moons returns all class-0 points first.
  3. accuracy: net.forward(X) > 0 compares logits with 0, which is the same as comparing probabilities with 0.5, because sigmoid(0) = 0.5. No need to compute the sigmoid.
  4. train: creates a fresh SigmoidBCE and Adam, then for each epoch shuffles (rng.permutation) and runs the four steps for every batch of 32.
  5. if l2: layer.dW += l2 * layer.W: optional L2 regularisation, added to the weight gradients after backward and before the update (biases are not regularised).
  6. evaluate every log_every epochs: loss and accuracy on the whole training set and the whole validation set, measured after the epoch's updates.
  7. ascii_plot: evaluates the network on a 60 × 22 grid of points covering the plane and prints . or + for the predicted class, then overlays validation points as o (class 0) and x (class 1).
  8. Main: a 2-16-16-1 network (337 parameters) trained for 150 epochs with Adam at 0.003, then the overfitting experiment: a 2-64-64-1 network (4,417 parameters) on only 30 training points for 800 epochs, without and with L2.
train 450 points, validation 150 points
parameters: 337
epoch    1  train loss 0.4270 acc  86.0%  |  val loss 0.4422 acc  83.3%
epoch   30  train loss 0.2411 acc  89.6%  |  val loss 0.2421 acc  86.7%
epoch   60  train loss 0.1940 acc  92.2%  |  val loss 0.1943 acc  91.3%
epoch   90  train loss 0.1760 acc  93.6%  |  val loss 0.1716 acc  94.0%
epoch  120  train loss 0.1686 acc  93.6%  |  val loss 0.1665 acc  94.0%
epoch  150  train loss 0.1644 acc  94.2%  |  val loss 0.1621 acc  93.3%

decision regions on the validation set ('.' class 0, '+' class 1, o/x points):
.................................................+++++++++++
...................o............................++++++++++++
......................o.o......................+++++++++++++
..................o....o......................++++++++++++++
............o.o.....o..o....o.................++++++++++++++
......o...o....o.o...........oo..............+++++++++++++++
....o.....o..oo..o.....o..oo.o.oo......o....++++++++++++++++
.....o.o....ooo.oo.....o....oo....o.........++++++++++++++++
.o....o..o..o.o....xo.......oo.............++x++++++++++++++
....o...o..o..o....+++++++.o..o........o..++++++x+++++++++++
.......o.........+++++++++++.xx.ooo......o+++++++++x+xx+++++
...o...o..o....x.+o++++xx+xx++....o..oo..x+++x++++++++x+++++
............x.o..+++++++++++ox+++...o...x++++++++++x++x+x+x+
....o...........++++++++++++++++++o..o++x++x+x++x++++++x++++
....o..........++++xxx++++xxxx+x++x+++++++++++++++++++++++++
............o.+++++x++++++x+x+++x+++++++x+x+xx++++++++++++++
..............+++++++x+++++x++++++++xx+++x++++x++x++++++++++
.............++++++++++++xx+++++x++x++++++++++++++x+++++++++
............+++++++++++++x++++++x+++x++x+++x+++x++++++++++++
...........+++++++++++x++++++++x++++++++++++++x+++++++++++++
..........+++++++++++++++++++++++++++++++++x++++++++++++++++
.........+++++++++++++++++++++++++++++++++++++++++++++++++++

overfitting experiment: 30 training points, 2-64-64-1 network, 800 epochs
L2 = 0.0  : train loss 0.0001 acc 100.0%  |  val loss 0.9318 acc  90.0%
L2 = 0.01 : train loss 0.1511 acc  93.3%  |  val loss 0.2392 acc  90.0%

Reading the results

The log. After the first epoch the network is already at 86% on the training set: the moons are mostly separable by a rough boundary, which is learned quickly. Then progress slows as the network refines the curved parts: validation loss falls from 0.44 to about 0.16 and validation accuracy climbs from 83% to 93–94%. Training and validation numbers stay close together throughout, which is the signature of a model that generalises: it is not doing better on the data it was trained on than on new data.

The picture. In the text plot, the . region (class 0) sweeps over the upper moon and the + region (class 1) curls up into the gap under it. Most o points sit in . and most x points in +; the exceptions are noisy points near the boundary. A linear model could only draw one straight edge between the regions.

The overfitting experiment. With 30 training points and 4,417 parameters, the unregularised network drives its training loss to 0.0001 and its training accuracy to 100%: it has carved a boundary around each individual point. Its validation loss, 0.93, is far worse than the healthy model's 0.16. With L2 = 0.01 the training loss stays at 0.15, and the validation loss is 0.24. Look carefully at accuracy, though: both variants score 90.0% on validation. Overfitting here shows up mainly in the loss, because the memorising network is confidently wrong on the points it misclassifies, and cross-entropy punishes confident mistakes heavily. Its probabilities can't be trusted, even though its yes/no answers happen to be no worse on this validation set. Regularisation helps calibration clearly here; whether it also helps accuracy depends on the data. Both models are also worse than the healthy 450-point model (93.3%): more data is the most reliable cure for overfitting.

Ltotal=Ldata+λ2∑W‖W‖2⇒∂Ltotal∂W=∂Ldata∂W+λW

In words: L2 regularisation adds a penalty for large weights, which simply adds λW to each weight gradient. Smaller weights mean smoother, less extreme functions.

Training playground

The same algorithm, rewritten in JavaScript, runs in your browser below: a small ReLU or tanh network with Adam and binary cross-entropy, trained with mini-batches of 32 on 300 points (with no validation split, to keep it simple; lesson 3.7 adds one). The shading shows the network's predicted class and confidence over the plane, and the small chart shows the training loss. Try the XOR and spiral datasets with a tiny network, then a bigger one.

Train a network in your browserInteractive

Things to notice: a 1 × 4 network can only make a few "bends", so on the spiral it gives up and draws a rough compromise. Tanh boundaries look smooth, ReLU boundaries are made of straight pieces (each hidden unit adds one hinge, as lesson 3.2 predicted). A learning rate near the top of the slider makes the loss curve jagged or makes training collapse; near the bottom, nothing seems to happen for a long time.

The same loop in PyTorch, and the same loop at frontier scale

Here is our training step written with PyTorch, for comparison. It needs pip install torch and was not executed by our tests. Every line maps onto something you wrote by hand: nn.Linear is Dense, loss.backward() is our Sequential.backward generated automatically, opt.step() is our Adam.step, and weight_decay in AdamW plays the role of our L2 term (in the decoupled form).

import torch
from torch import nn

net = nn.Sequential(nn.Linear(2, 16), nn.ReLU(), nn.Linear(16, 16), nn.ReLU(), nn.Linear(16, 1))
opt = torch.optim.AdamW(net.parameters(), lr=0.003, weight_decay=0.0)
loss_fn = nn.BCEWithLogitsLoss()               # sigmoid + BCE, fused and stable

for epoch in range(150):
    for idx in torch.randperm(len(X_tr)).split(32):
        logits = net(X_tr[idx])                # 1. forward
        loss = loss_fn(logits, y_tr[idx])      # 2. loss
        opt.zero_grad()                        # gradients accumulate unless cleared
        loss.backward()                        # 3. backward (autograd)
        opt.step()                             # 4. update

One difference worth knowing: PyTorch adds new gradients to existing ones, so you must call zero_grad() each step. Our layers overwrite dW on every backward pass instead.

At frontier scale the loop is recognisably the same: forward, cross-entropy on next-token predictions, backward, AdamW-style update, learning-rate warm-up and decay. What changes is everything around it. Public estimates for frontier models in general describe trillions of training tokens, thousands to tens of thousands of accelerators running for weeks to months, and costs in the tens to hundreds of millions of dollars, with the model and data split across many devices and frequent checkpoints so that hardware failures don't lose work. These are general industry figures; the corresponding details for Claude are Not public. What you can realistically train yourself is covered in lesson 10.7.

Common mistakes and debugging tips

Only looking at training accuracy

A big enough network will reach 100% on its training data by memorising it. That number says nothing about new data, as the overfitting experiment shows.

Fix: always hold out a validation set and make decisions (architecture, learning rate, when to stop) on validation numbers. Keep a separate test set for the final, once-only report.

Validation data leaking into training

Normalising with statistics computed on all data, duplicates that appear in both sets, or tuning settings until the validation score is perfect all make validation optimistic.

Fix: split first, then compute anything data-dependent (means, vocabularies) on the training set only, and deduplicate before splitting.

Loss goes down, accuracy stays at 50%

Often a label/prediction shape mismatch that broadcasts, a sigmoid applied twice, or accuracy computed with a wrong threshold (comparing logits with 0.5 instead of 0).

Fix: overfit a tiny batch first: a correct pipeline drives the loss of 10 examples close to 0 within a few hundred steps. If it can't, the bug is in the code, not the data.

Inputs on very different scales

If one feature is in the thousands and another between 0 and 1, the loss surface becomes a very narrow valley (lesson 3.5) and training is slow or unstable.

Fix: standardise features (the lesson 3.1 exercise) using training-set statistics.

Key takeaways

  • The training loop is forward → loss → backward → update, over shuffled mini-batches, for many epochs.
  • A hidden layer with a non-linearity learns curved boundaries that no linear model can.
  • Judge a model on held-out validation data; close training and validation numbers mean it generalises.
  • Overfitting shows first in validation loss (confident mistakes); L2 regularisation and, above all, more data reduce it.

Exercise: circles, and how many neurons a shape needs

Write make_circles(n, noise, rng): half the points on a ring of radius 1 (class 0), half on a ring of radius 0.4 (class 1), with Gaussian noise. Train a 2-h-1 ReLU network for h = 1, 3 and 8 with the functions in train.py and print the validation accuracy. Before running, predict the smallest h that can do well, and why.

Hint

Each ReLU unit contributes one straight "hinge" line. How many straight lines do you need to fence in a disc? Import Dense, ReLU, Sequential, train, train_val_split and accuracy from train.py.

Show a solution
import numpy as np
from train import Dense, ReLU, Sequential, train, train_val_split, accuracy
def make_circles(n, noise, rng):
    t = rng.uniform(0, 2 * np.pi, n)
    inner = np.arange(n) >= n // 2                      # second half = inner ring = class 1
    r = np.where(inner, 0.4, 1.0)
    X = np.column_stack([r * np.cos(t), r * np.sin(t)]) + rng.normal(0, noise, (n, 2))
    return X, inner.astype(np.float64).reshape(-1, 1)

rng = np.random.default_rng(0)
X, y = make_circles(600, 0.1, rng)
X_tr, y_tr, X_val, y_val = train_val_split(X, y, 0.25, rng)
for hidden in (1, 3, 8):
    net = Sequential(Dense(2, hidden, rng), ReLU(), Dense(hidden, 1, rng))
    train(net, X_tr, y_tr, X_val, y_val, rng, epochs=150, lr=0.01)
    print(f"{hidden} hidden units: val acc {accuracy(net, X_val, y_val):.1%}")
1 hidden units: val acc 59.3%
3 hidden units: val acc 98.7%
8 hidden units: val acc 99.3%

One unit gives one straight cut, so it can only do slightly better than guessing. Three hinges can fence the inner disc inside a triangle, which is already enough for 98.7%; eight make a smoother, rounder boundary. The exact percentages depend on the seed, so run a few seeds before drawing strong conclusions.

Check your understanding

A model reaches 100% training accuracy and 70% validation accuracy. What is the most likely diagnosis?

  1. The learning rate is too small
  2. Overfitting: it memorised the training set instead of learning the general pattern
  3. The validation set is too easy
A large gap between training and validation performance is the definition of overfitting. A too-small learning rate would leave training accuracy low too; an easy validation set would make validation scores higher, not lower.

In the overfitting experiment, both models have 90.0% validation accuracy, but validation losses of 0.93 and 0.24. What explains the difference?

  1. The unregularised model is confidently wrong on the points it misclassifies, and cross-entropy punishes confident mistakes heavily
  2. The loss was computed on different validation points
  3. Cross-entropy is unrelated to accuracy
Same yes/no answers, very different confidence. Memorising pushes probabilities to near 0 or 1, so each mistake costs a lot of loss. Both used the same validation set, and loss and accuracy are related (lower loss usually means higher accuracy) but measure different things.

What is the correct order of the four steps inside the training loop?

  1. Update, forward, backward, loss
  2. Forward, backward, loss, update
  3. Forward, loss, backward, update
You need predictions (forward) to compute the loss; the loss's gradient starts the backward pass; the update uses the gradients. Backward can't come before the loss, which provides its starting gradient.

Lesson 3.7Module 3: Neural network from scratch

Visualize training and loss

  • ⏱ 29 min read
  • Intermediate

Learning objectives

  • Record a training history (train loss, validation loss, accuracy per epoch) and plot it as text or with matplotlib.
  • Diagnose common problems from the shape of loss curves: learning rate too low or too high, overfitting, bugs.
  • Explain why validation loss and validation accuracy can disagree, and choose what early stopping should watch.
  • Build and evaluate a three-class classifier end to end in the mini-project.

A training run produces a stream of numbers, and the single most useful thing you can do with them is draw them. A loss curve shows in one glance whether training is working, whether it has finished, whether the learning rate is sensible and whether the model is starting to memorise. Machine-learning engineers spend a surprising share of their time looking at these curves, from toy models like ours to the largest training runs, so it is worth learning to read them properly.

Analogy: a heart monitor

A doctor glancing at a heart monitor doesn't read individual numbers; they recognise shapes. A steady rhythm is fine; a flat line, a racing jagged trace or a slow drift each points to a specific problem. Loss curves work the same way. A smooth fall that levels off is healthy; a flat line, a jagged sawtooth, a sudden spike to infinity or two curves drifting apart each has a short list of usual causes. This lesson teaches you those shapes.

What to record

At the end of every epoch (or every few hundred steps in a long run), record at least:

  • Training loss, measured on the full training set or a fixed sample of it, after the epoch's updates. The average of the mini-batch losses during the epoch is a cheaper alternative, but it lags behind, because early batches were seen by an older model.
  • Validation loss on the held-out set: the honest measure of generalisation.
  • A task metric people care about, such as validation accuracy. It is easier to explain, but coarser than the loss.
  • For longer runs: the current learning rate (to see the schedule) and the gradient norm (sudden growth warns of instability).

Store them as lists in a dictionary, one value per epoch. That is all a "history" is, and it is what libraries such as Keras return from fit or what experiment trackers log for you.

Recording and drawing a history

loss_history.py reuses the library from lesson 3.6, with a fit function that returns a history, and draws curves as text so that it runs anywhere (including the ▶ Run button). It runs three experiments: a healthy run, a learning-rate comparison and an overfitting run.

# @run
# Lesson 3.7: record a training history and read it. Text charts of the loss curves,
# a learning-rate comparison and an early-stopping check. NumPy only, self-contained.
import numpy as np


# ---------- the library from lessons 3.2-3.6 (same code as train.py) ----------
class Dense:
    def __init__(self, n_in, n_out, rng):
        self.W = rng.normal(0.0, np.sqrt(2.0 / n_in), size=(n_in, n_out))
        self.b = np.zeros(n_out)

    def forward(self, X):
        self.X = X
        return X @ self.W + self.b

    def backward(self, dY):
        self.dW = self.X.T @ dY
        self.db = dY.sum(axis=0)
        return dY @ self.W.T

    def parameters(self):
        return [(self.W, self.dW), (self.b, self.db)]


class ReLU:
    def forward(self, Z):
        self.mask = Z > 0
        return Z * self.mask

    def backward(self, dA):
        return dA * self.mask

    def parameters(self):
        return []


class Sequential:
    def __init__(self, *layers):
        self.layers = list(layers)

    def forward(self, X):
        for layer in self.layers:
            X = layer.forward(X)
        return X

    def backward(self, grad):
        for layer in reversed(self.layers):
            grad = layer.backward(grad)

    def parameters(self):
        return [pg for layer in self.layers for pg in layer.parameters()]


class SigmoidBCE:
    def forward(self, logits, y):
        self.p = 1.0 / (1.0 + np.exp(-logits))
        self.y = y
        return float(np.mean(np.logaddexp(0.0, logits) - y * logits))

    def backward(self):
        return (self.p - self.y) / len(self.y)


class Adam:
    def __init__(self, lr=0.01, beta1=0.9, beta2=0.999, eps=1e-8):
        self.lr, self.beta1, self.beta2, self.eps = lr, beta1, beta2, eps
        self.m = self.v = None
        self.t = 0

    def step(self, params):
        if self.m is None:
            self.m = [np.zeros_like(p) for p, _ in params]
            self.v = [np.zeros_like(p) for p, _ in params]
        self.t += 1
        for (p, g), m, v in zip(params, self.m, self.v):
            m *= self.beta1
            m += (1 - self.beta1) * g
            v *= self.beta2
            v += (1 - self.beta2) * g * g
            m_hat = m / (1 - self.beta1 ** self.t)
            v_hat = v / (1 - self.beta2 ** self.t)
            p -= self.lr * m_hat / (np.sqrt(v_hat) + self.eps)


def make_moons(n, noise, rng):
    n0 = n // 2
    t0 = rng.uniform(0, np.pi, n0)
    t1 = rng.uniform(0, np.pi, n - n0)
    upper = np.column_stack([np.cos(t0), np.sin(t0)])
    lower = np.column_stack([1 - np.cos(t1), 0.5 - np.sin(t1)])
    X = np.vstack([upper, lower]) + rng.normal(0, noise, size=(n, 2))
    y = np.concatenate([np.zeros(n0), np.ones(n - n0)]).reshape(-1, 1)
    return X, y


# ---------- training that remembers what happened ----------
def fit(net, X_tr, y_tr, X_val, y_val, rng, epochs, lr, batch_size=32):
    """Train and return a history: one entry per epoch for every metric."""
    loss_fn, opt = SigmoidBCE(), Adam(lr)
    history = {"train_loss": [], "val_loss": [], "val_acc": []}
    for epoch in range(epochs):
        order = rng.permutation(len(X_tr))
        for start in range(0, len(X_tr), batch_size):
            idx = order[start:start + batch_size]
            loss_fn.forward(net.forward(X_tr[idx]), y_tr[idx])
            net.backward(loss_fn.backward())
            opt.step(net.parameters())
        # measure on the FULL sets once per epoch, after the updates
        history["train_loss"].append(loss_fn.forward(net.forward(X_tr), y_tr))
        val_logits = net.forward(X_val)
        history["val_loss"].append(loss_fn.forward(val_logits, y_val))
        history["val_acc"].append(float(np.mean((val_logits > 0) == (y_val > 0.5))))
    return history


def text_chart(series, height=10, width=50):
    """Draw several curves in a character grid. series: {symbol: list of values}; '*' = overlap."""
    top = max(max(v) for v in series.values())
    bottom = min(min(v) for v in series.values())
    grid = [[" "] * width for _ in range(height)]
    for symbol, values in series.items():
        for col in range(width):
            i = round(col * (len(values) - 1) / (width - 1))      # which epoch this column shows
            row = round((top - values[i]) / (top - bottom) * (height - 1))
            grid[row][col] = "*" if grid[row][col] not in (" ", symbol) else symbol
    lines = []
    for r, cells in enumerate(grid):
        label = top - r * (top - bottom) / (height - 1)
        lines.append(f"{label:6.3f} |" + "".join(cells))
    lines.append(" " * 7 + "+" + "-" * width)
    return "\n".join(lines)


def sparkline(values, lo, hi):
    """One line, one character per value, on a shared scale: lo = '_', hi = '#'."""
    ramp = "_.-~=*%#"
    return "".join(ramp[int((v - lo) / (hi - lo + 1e-12) * (len(ramp) - 1))] for v in values)


if __name__ == "__main__":
    rng = np.random.default_rng(0)
    X, y = make_moons(600, noise=0.3, rng=rng)
    order = rng.permutation(len(X))
    X_tr, y_tr, X_val, y_val = X[order[150:]], y[order[150:]], X[order[:150]], y[order[:150]]

    # 1. A healthy run: both curves fall and stay close together.
    r = np.random.default_rng(1)
    net = Sequential(Dense(2, 16, r), ReLU(), Dense(16, 16, r), ReLU(), Dense(16, 1, r))
    h = fit(net, X_tr, y_tr, X_val, y_val, r, epochs=100, lr=0.003)
    print("1. healthy run, 100 epochs  (t = train loss, v = validation loss)")
    print(text_chart({"t": h["train_loss"], "v": h["val_loss"]}))
    print(f"   final: train {h['train_loss'][-1]:.4f}  val {h['val_loss'][-1]:.4f}  val acc {h['val_acc'][-1]:.1%}")

    # 2. The learning rate decides the shape of the curve.
    print("\n2. learning rate vs. train-loss curve (40 epochs, one character per epoch)")
    curves = {}
    for lr in (0.0001, 0.003, 0.3):
        r = np.random.default_rng(1)
        net = Sequential(Dense(2, 16, r), ReLU(), Dense(16, 16, r), ReLU(), Dense(16, 1, r))
        curves[lr] = fit(net, X_tr, y_tr, X_val, y_val, r, epochs=40, lr=lr)["train_loss"]
    lo = min(min(c) for c in curves.values())
    hi = max(max(c) for c in curves.values())
    print(f"   one shared scale: '_' = {lo:.3f} ... '#' = {hi:.3f}")
    for lr, tl in curves.items():
        print(f"   lr {lr:<6}: {sparkline(tl, lo, hi)}  first {tl[0]:.3f}  last {tl[-1]:.3f}  min {min(tl):.3f}")

    # 3. Overfitting: 40 training points, a big network, 300 epochs.
    print("\n3. overfitting: 40 training points, 2-64-64-1 network, 300 epochs")
    r = np.random.default_rng(3)
    big = Sequential(Dense(2, 64, r), ReLU(), Dense(64, 64, r), ReLU(), Dense(64, 1, r))
    h = fit(big, X_tr[:40], y_tr[:40], X_val, y_val, r, epochs=300, lr=0.003, batch_size=40)
    print(text_chart({"t": h["train_loss"], "v": h["val_loss"]}))
    best = int(np.argmin(h["val_loss"]))
    best_acc = int(np.argmax(h["val_acc"]))
    print(f"   lowest val loss   {h['val_loss'][best]:.4f} at epoch {best + 1:3d} (val acc {h['val_acc'][best]:.1%})")
    print(f"   highest val acc   {h['val_acc'][best_acc]:.1%} at epoch {best_acc + 1:3d} (val loss {h['val_loss'][best_acc]:.4f})")
    print(f"   at epoch 300: train loss {h['train_loss'][-1]:.4f}  val loss {h['val_loss'][-1]:.4f}"
          f"  val acc {h['val_acc'][-1]:.1%}")
  1. history = {"train_loss": [], "val_loss": [], "val_acc": []}: one list per metric. After each epoch, fit appends the loss on the full training set and the loss and accuracy on the validation set.
  2. val_logits = net.forward(X_val): one forward pass reused for both validation loss and accuracy. Evaluation happens after the epoch's updates and never calls backward.
  3. text_chart: maps each value to a row of a character grid (top = largest value) and each column to an epoch, writing t or v, and * where the two curves share a cell.
  4. sparkline: one character per epoch from a ramp _.-~=*%#, using one shared scale for all three runs so they can be compared directly.
  5. Experiment 1: the 2-16-16-1 network on the 450 training points for 100 epochs.
  6. Experiment 2: the same network and seed with learning rates 0.0001, 0.003 and 0.3 for 40 epochs.
  7. Experiment 3: a 2-64-64-1 network on only 40 training points for 300 epochs, then the epochs with the lowest validation loss and the highest validation accuracy.
1. healthy run, 100 epochs  (t = train loss, v = validation loss)
 0.597 |*
 0.549 |
 0.501 |
 0.453 |
 0.405 | *
 0.357 |
 0.309 |  **tt
 0.261 |    vv***************
 0.212 |                     **********
 0.164 |                               *******************
       +--------------------------------------------------
   final: train 0.1651  val 0.1665  val acc 93.3%

2. learning rate vs. train-loss curve (40 epochs, one character per epoch)
   one shared scale: '_' = 0.198 ... '#' = 0.769
   lr 0.0001: %%%%%%%%%%%%***************=============  first 0.769  last 0.550  min 0.550
   lr 0.003 : =~-............_________________________  first 0.585  last 0.241  min 0.241
   lr 0.3   : ...-...__.__..__~___*-..____~~-.__._~.._  first 0.286  last 0.239  min 0.198

3. overfitting: 40 training points, 2-64-64-1 network, 300 epochs
 0.512 |*
 0.461 |                                             vvvvv
 0.409 |                                     vvvvvvvv
 0.358 |                            vvvvvvvvv
 0.306 | vvvvvvvvvvvvvvvvvvvvvvvvvvv
 0.255 | t
 0.203 |  ttttttttt
 0.152 |           tttttttttttttt
 0.101 |                         ttttttttttttttt
 0.049 |                                        tttttttttt
       +--------------------------------------------------
   lowest val loss   0.2934 at epoch  11 (val acc 83.3%)
   highest val acc   92.0% at epoch 218 (val loss 0.3774)
   at epoch 300: train loss 0.0493  val loss 0.4670  val acc 90.0%

Reading the three experiments

1. Healthy. Both curves drop steeply in the first few epochs, then flatten, and they lie on top of each other almost everywhere (the * cells). The model ends at a training loss of 0.165 and a validation loss of 0.167. When the curves are this close and both have levelled off, more epochs won't help much; a bigger model, better features or more data might.

2. Learning rate. At 0.0001 the loss slides down slowly and steadily: after 40 epochs it is still at 0.55, far above what the network can reach. That is the "too low" signature: smooth, but slow. At 0.003 the loss falls fast and then levels out smoothly at 0.24. At 0.3 the first epoch already reaches 0.29 (big steps help at first), and it even touches the lowest value of all, 0.198, but then the sparkline jumps around: the steps are too large to settle into the minimum, and the final value, 0.239, is no better than the sensible rate. Jagged curves that stop improving are the "too high" signature; much higher still and the loss would explode to nan.

3. Overfitting. The training loss keeps falling towards zero, while the validation loss bottoms out at 0.293 around epoch 11 and then climbs steadily to 0.467. The widening gap between the curves is the classic picture of overfitting. Here is the same run drawn properly from the real numbers:

0.00.20.40.6 loss validation losstraining losslowest val loss, epoch 11 50%70%90% validation accuracy 1100200300
Experiment 3, drawn from the real numbers (every third epoch). Top: loss. Bottom: validation accuracy. Validation loss is lowest at epoch 11 and then rises, yet validation accuracy keeps improving for another 200 epochs before slipping back to 90%.

Now look at the accuracy. At the epoch with the lowest validation loss, validation accuracy is only 83.3%; it keeps rising to 92.0% at epoch 218 even though the validation loss has been rising for 200 epochs. How can the model get "worse" and "better" at the same time? Cross-entropy measures confidence as well as correctness. As the network memorises its 40 training points, it becomes more and more certain about everything, so the few validation points it gets wrong are wrong with very high confidence, which costs a lot of loss, while the boundary itself is still improving in places and fixing some borderline points. Accuracy counts only right versus wrong; the loss counts how sure you were.

This matters for early stopping, the practice of keeping the weights from the best validation epoch rather than the last one. Which "best" depends on what you need: if you will use the model's probabilities (to rank, to set thresholds, or, in a language model, to sample text), watch the validation loss; if only the final yes/no decision matters, validation accuracy may be the better guide, although on 150 validation points a 1–2% difference is only a few points and may be noise. Either way, the real fix here is more training data: the 450-point model in lesson 3.6 beat both.

A field guide to loss curves

What you seeLikely causesWhat to try
Loss perfectly flat from step 1Parameters not actually updated (rebinding instead of in-place), learning rate 0, gradients not connectedPrint a weight before and after one step; gradient-check
Slow, smooth, steady declineLearning rate too lowMultiply it by 3–10
Jagged, stops improving, or jumps upLearning rate too high, batch too smallDivide it by 3–10, add a decay schedule
Sudden jump to nan or infDivergence, log(0), exp overflowLower the learning rate, use stable logit losses, clip gradients
Train falls, validation risesOverfittingMore data, L2/weight decay, smaller model, early stopping
Both high and flatUnderfitting: model too small, poor features, or a bugBigger model; check you can overfit 10 examples
Validation better than trainingRegularisation active only during training, or an easier validation setUsually harmless; check the split
Starts far above ln CBad initialisation or wrong output layerCheck init scale and that logits start small

Two habits make curves easier to read. First, plot the loss on a log scale: late training often improves a loss from 0.02 to 0.01, which is invisible on a linear axis but a halving of the error. Second, smooth noisy per-step losses with an exponential moving average, the same running average Adam uses:

st=βst−1+(1−β)Lt

In words: the smoothed value keeps a fraction β (say 0.9) of its previous value and mixes in a little of the newest loss. Larger β is smoother but reacts more slowly.

Overfitting lab

This demo trains the same kind of network as experiment 3, live, with a separate validation set of 200 points that it never trains on. Filled dots are training points, hollow rings validation points. Shrink the training set and enlarge the network to provoke overfitting; then add L2 and watch the gap close.

Train vs. validation, liveInteractive

training lossvalidation losslowest validation loss

Real charts with matplotlib Optional

Text charts are enough to diagnose problems, but for reports you want real plots. This script reuses fit from loss_history.py and draws three panels: the two losses on a log scale with the best epoch marked, validation accuracy, and the decision regions with the boundary (the 0.5 contour) drawn in black. It needs pip install matplotlib and was not executed by our tests; we ran it once locally to check it, and it saves training_curves.png, which shows the same curves as the figure above.

# Lesson 3.7: the same training history drawn as real charts with matplotlib.
# Needs: pip install matplotlib, and loss_history.py in the same folder.
# Not executed by the course tests (matplotlib is not part of the runnable set); it saves training_curves.png.
import matplotlib

matplotlib.use("Agg")                      # draw to a file; remove this line to open a window instead
import matplotlib.pyplot as plt
import numpy as np

from loss_history import Dense, ReLU, Sequential, fit, make_moons

rng = np.random.default_rng(0)
X, y = make_moons(600, noise=0.3, rng=rng)
order = rng.permutation(len(X))
X_tr, y_tr, X_val, y_val = X[order[150:]], y[order[150:]], X[order[:150]], y[order[:150]]

r = np.random.default_rng(3)
net = Sequential(Dense(2, 64, r), ReLU(), Dense(64, 64, r), ReLU(), Dense(64, 1, r))
h = fit(net, X_tr[:40], y_tr[:40], X_val, y_val, r, epochs=300, lr=0.003, batch_size=40)
epochs = np.arange(1, len(h["train_loss"]) + 1)
best = int(np.argmin(h["val_loss"])) + 1

fig, (ax_loss, ax_acc, ax_map) = plt.subplots(1, 3, figsize=(15, 4.5))

# 1. Loss curves: the gap between them is the story.
ax_loss.plot(epochs, h["train_loss"], label="train loss")
ax_loss.plot(epochs, h["val_loss"], label="validation loss")
ax_loss.axvline(best, linestyle="--", color="gray", label=f"lowest val loss (epoch {best})")
ax_loss.set_xlabel("epoch")
ax_loss.set_ylabel("binary cross-entropy")
ax_loss.set_yscale("log")                  # log scale shows the late, small changes too
ax_loss.legend()

# 2. Validation accuracy on its own axis (it can move differently from the loss).
ax_acc.plot(epochs, h["val_acc"], color="tab:green")
ax_acc.set_xlabel("epoch")
ax_acc.set_ylabel("validation accuracy")
ax_acc.set_ylim(0.5, 1.0)

# 3. Decision regions: evaluate the network on a grid of points and colour by probability.
gx, gy = np.meshgrid(np.linspace(-1.6, 2.6, 200), np.linspace(-1.1, 1.6, 200))
logits = net.forward(np.column_stack([gx.ravel(), gy.ravel()])).reshape(gx.shape)
prob = 1.0 / (1.0 + np.exp(-logits))
ax_map.contourf(gx, gy, prob, levels=20, cmap="RdBu_r", alpha=0.6)
ax_map.contour(gx, gy, prob, levels=[0.5], colors="black")          # the decision boundary
ax_map.scatter(X_tr[:40, 0], X_tr[:40, 1], c=y_tr[:40, 0], cmap="RdBu_r", edgecolors="k")
ax_map.set_title("decision regions (training points)")

fig.tight_layout()
fig.savefig("training_curves.png", dpi=120)
print("saved training_curves.png")
  1. matplotlib.use("Agg"): draw into an image file without opening a window (works on servers). Remove it to get an interactive window.
  2. from loss_history import …, fit, make_moons: importing a module runs its top level but not its if __name__ == "__main__": block, so nothing is printed.
  3. ax_loss.set_yscale("log"): the log scale that makes the late, small changes in training loss visible.
  4. ax_loss.axvline(best, …): a dashed line at the epoch with the lowest validation loss.
  5. np.meshgrid + net.forward on 200 × 200 points, then contourf for the probability shading and contour(…, levels=[0.5]) for the decision boundary: the same idea as the text plot in lesson 3.6, at a higher resolution.
What gets monitored in large training runs

The curves you drew here are, in essence, what teams watch during large-model training too, plus a few extras. Public reports from labs and open-model projects describe watching for loss spikes (sudden jumps that sometimes recover and sometimes don't), tracking the gradient norm and clipping it, logging the learning-rate schedule, and evaluating on many held-out datasets and benchmarks at regular checkpoints. When a run goes wrong, a common remedy is to roll back to an earlier checkpoint and change something, such as the data order or the learning rate. All of this is Industry practice; Anthropic's internal monitoring is Not public.

Loss curves also became a research tool. Scaling-law papers (for example Kaplan et al., 2020, and Hoffmann et al., 2022) fit simple formulas to final losses of many runs of different sizes and showed that language-model loss falls smoothly and predictably as model size, data and compute grow. That predictability is how labs plan very expensive runs from small, cheap ones. One more contrast with this lesson: large pretraining runs typically see each training token only once or a few times, so the dramatic overfitting of experiment 3 is not the main worry there; with fine-tuning on small datasets (module 10), it is again.

Common mistakes and debugging tips

Comparing an epoch-average training loss with an end-of-epoch validation loss

The average of mini-batch losses during an epoch includes batches seen by older, worse weights, so it sits above the true end-of-epoch training loss. Early on it can make validation look better than training, which is confusing.

Fix: measure both at the same moment with the same weights, as fit does, or accept the lag and know it is there.

Reading too much into one run

On small datasets, a different seed can change accuracy by a few percent. A "1% improvement" may be luck.

Fix: run 3–5 seeds and compare averages (and spreads) before deciding anything.

Only plotting accuracy

Accuracy changes in steps of 1/N and ignores confidence, so it can hide both progress and overfitting (experiment 3).

Fix: always plot the loss too, preferably on a log scale.

Choosing hyperparameters on the test set

If you look at the test score to pick the learning rate or the stopping epoch, it stops being an unbiased estimate.

Fix: choose with validation data; touch the test set once, at the end.

Key takeaways

  • Record train loss, validation loss and a metric every epoch; plot them, ideally on a log scale.
  • Curve shapes have usual suspects: flat (no updates), slow (low learning rate), jagged or nan (high learning rate), diverging curves (overfitting).
  • Validation loss and accuracy can disagree; loss also measures confidence.
  • Early stopping keeps the best validation epoch, but more data is the more reliable cure for overfitting.

Exercise: diagnose four runs

A colleague sends four descriptions. For each, name the most likely cause and one thing to try. (a) Training and validation loss both fall smoothly from 0.69 to 0.62 over 200 epochs and are still falling. (b) The loss falls for 30 epochs, then becomes nan. (c) Training loss reaches 0.001; validation loss bottoms out at 0.35 at epoch 20 and is 1.4 at epoch 300. (d) The first logged loss of a 100-class classifier is 46.

Hint

Compare each with the field guide table. For (d), what should the first loss of a C-class classifier be?

Show a solution
  • (a) Learning rate too low (0.69 is ln 2, the starting point of a binary classifier, and progress is slow but steady): increase it 3–10×, or use Adam.
  • (b) Instability: learning rate too high for a region reached later, or a log(0)/overflow: lower the learning rate or add decay, use stable logit-based losses, clip gradients, and check the batch where it happened.
  • (c) Overfitting: keep the epoch-20 weights (early stopping), add L2/weight decay or use a smaller model, and get more data if you can.
  • (d) Broken start: ln 100 ≈ 4.6 is expected. 46 means the logits are huge at initialisation (weights scaled far too large, inputs not normalised) or the loss is being summed instead of averaged. Fix the initialisation and input scaling and check the loss reduction.

Mini-project: a three-class spiral classifier

Put the whole module together. Build a classifier for three interleaved spiral arms, a classic dataset that a linear model cannot handle, using only NumPy and your own layers. The target is at least 95% validation accuracy, together with the evidence that you got there honestly: a linear baseline, logged training curves and a confusion matrix.

  1. Write make_spiral(n_per_class, n_classes, noise, rng): for each class k, radii from 0.05 to 1 and angles from 0 to 5 radians, shifted by k·2π/3, with noise added to the angle. Return X of shape (600, 2) for 200 points per class and integer labels 0, 1, 2.
  2. Shuffle and hold out 20% (120 points) as a validation set.
  3. Replace the sigmoid loss with SoftmaxCrossEntropy from lesson 3.4, so the last layer has 3 outputs. Check that the untrained network's loss is near ln 3 ≈ 1.10.
  4. Train a linear baseline (one Dense(2, 3), no hidden layer) and record its validation accuracy. This tells you how much the hidden layers add.
  5. Train a network with two hidden ReLU layers using Adam and mini-batches. Log train and validation loss and accuracy every 25 epochs; add a little L2 if the curves start to separate.
  6. Report the final validation accuracy and a 3 × 3 confusion matrix (rows: true class, columns: predicted class) so you can see which arms get confused.
  7. Stretch goals: draw the decision regions (text or matplotlib), try tanh instead of ReLU, or try a smaller network and find the smallest one that still reaches 95%.
Hints / reference solution

Accuracy for softmax outputs is net.forward(X).argmax(axis=1) == y. Labels for SoftmaxCrossEntropy are integers of shape (N,), not one-hot vectors. A 2-64-64-3 network with Adam at 0.005, batches of 32 and 150 epochs is plenty; the reference uses L2 = 1e-4. Our reference solution, a single self-contained file:

# @run
# Lesson 3.7 mini-project (reference solution): classify a 3-arm spiral with a softmax
# output and Adam, and reach at least 95% validation accuracy. NumPy only, self-contained.
import numpy as np


# ---------- the library built in lessons 3.2-3.5 ----------
class Dense:
    def __init__(self, n_in, n_out, rng):
        self.W = rng.normal(0.0, np.sqrt(2.0 / n_in), size=(n_in, n_out))   # He init
        self.b = np.zeros(n_out)

    def forward(self, X):
        self.X = X
        return X @ self.W + self.b

    def backward(self, dY):
        self.dW = self.X.T @ dY
        self.db = dY.sum(axis=0)
        return dY @ self.W.T

    def parameters(self):
        return [(self.W, self.dW), (self.b, self.db)]


class ReLU:
    def forward(self, Z):
        self.mask = Z > 0
        return Z * self.mask

    def backward(self, dA):
        return dA * self.mask

    def parameters(self):
        return []


class Sequential:
    def __init__(self, *layers):
        self.layers = list(layers)

    def forward(self, X):
        for layer in self.layers:
            X = layer.forward(X)
        return X

    def backward(self, grad):
        for layer in reversed(self.layers):
            grad = layer.backward(grad)

    def parameters(self):
        return [pg for layer in self.layers for pg in layer.parameters()]

    def dense_layers(self):
        return [layer for layer in self.layers if isinstance(layer, Dense)]


class SoftmaxCrossEntropy:
    def forward(self, logits, labels):
        Z = logits - logits.max(axis=1, keepdims=True)
        log_probs = Z - np.log(np.exp(Z).sum(axis=1, keepdims=True))
        self.probs = np.exp(log_probs)
        self.labels = labels
        return float(-log_probs[np.arange(len(labels)), labels].mean())

    def backward(self):
        n = len(self.labels)
        grad = self.probs.copy()
        grad[np.arange(n), self.labels] -= 1.0
        return grad / n


class Adam:
    def __init__(self, lr=0.01, beta1=0.9, beta2=0.999, eps=1e-8):
        self.lr, self.beta1, self.beta2, self.eps = lr, beta1, beta2, eps
        self.m = self.v = None
        self.t = 0

    def step(self, params):
        if self.m is None:
            self.m = [np.zeros_like(p) for p, _ in params]
            self.v = [np.zeros_like(p) for p, _ in params]
        self.t += 1
        for (p, g), m, v in zip(params, self.m, self.v):
            m *= self.beta1
            m += (1 - self.beta1) * g
            v *= self.beta2
            v += (1 - self.beta2) * g * g
            m_hat = m / (1 - self.beta1 ** self.t)
            v_hat = v / (1 - self.beta2 ** self.t)
            p -= self.lr * m_hat / (np.sqrt(v_hat) + self.eps)


# ---------- data: three interleaved spiral arms ----------
def make_spiral(n_per_class, n_classes, noise, rng):
    X, y = [], []
    for k in range(n_classes):
        r = np.linspace(0.05, 1.0, n_per_class)                    # radius grows along the arm
        t = (np.linspace(0, 5.0, n_per_class) + k * 2 * np.pi / n_classes
             + rng.normal(0, noise, n_per_class))                   # angle, shifted per class
        X.append(np.column_stack([r * np.sin(t), r * np.cos(t)]))
        y.append(np.full(n_per_class, k))
    return np.vstack(X), np.concatenate(y)


def accuracy(net, X, y):
    return float(np.mean(net.forward(X).argmax(axis=1) == y))


if __name__ == "__main__":
    rng = np.random.default_rng(0)
    X, y = make_spiral(200, 3, noise=0.3, rng=rng)
    order = rng.permutation(len(X))
    val, tr = order[:120], order[120:]                              # 20% held out
    X_tr, y_tr, X_val, y_val = X[tr], y[tr], X[val], y[val]

    loss_fn = SoftmaxCrossEntropy()

    # Baseline: a linear classifier (one Dense layer, no hidden units) cannot bend.
    linear = Sequential(Dense(2, 3, rng))
    opt = Adam(lr=0.01)
    for epoch in range(100):
        loss_fn.forward(linear.forward(X_tr), y_tr)
        linear.backward(loss_fn.backward())
        opt.step(linear.parameters())
    print(f"linear baseline: val acc {accuracy(linear, X_val, y_val):.1%}")

    net = Sequential(Dense(2, 64, rng), ReLU(), Dense(64, 64, rng), ReLU(), Dense(64, 3, rng))
    opt = Adam(lr=0.005)
    for epoch in range(1, 151):
        perm = rng.permutation(len(X_tr))
        for start in range(0, len(X_tr), 32):
            idx = perm[start:start + 32]
            loss_fn.forward(net.forward(X_tr[idx]), y_tr[idx])
            net.backward(loss_fn.backward())
            for layer in net.dense_layers():
                layer.dW += 1e-4 * layer.W                          # a little L2
            opt.step(net.parameters())
        if epoch % 25 == 0:
            tr_loss = loss_fn.forward(net.forward(X_tr), y_tr)
            va_loss = loss_fn.forward(net.forward(X_val), y_val)
            va_acc = accuracy(net, X_val, y_val)
            print(f"epoch {epoch:3d}  train loss {tr_loss:.4f}  val loss {va_loss:.4f}"
                  f"  train acc {accuracy(net, X_tr, y_tr):6.1%}  val acc {va_acc:6.1%}")

    final = accuracy(net, X_val, y_val)
    print(f"final validation accuracy: {final:.1%}")
    print("target reached (>= 95%)" if final >= 0.95 else "target NOT reached: train longer or tune")

    # confusion matrix: rows = true class, columns = predicted class
    pred = net.forward(X_val).argmax(axis=1)
    cm = np.zeros((3, 3), dtype=int)
    for t, p in zip(y_val, pred):
        cm[t, p] += 1
    print("confusion matrix (rows true, cols predicted):")
    print(cm)
linear baseline: val acc 44.2%
epoch  25  train loss 0.0260  val loss 0.0549  train acc  99.8%  val acc  97.5%
epoch  50  train loss 0.0081  val loss 0.0275  train acc 100.0%  val acc  98.3%
epoch  75  train loss 0.0282  val loss 0.0655  train acc  99.4%  val acc  98.3%
epoch 100  train loss 0.0037  val loss 0.0148  train acc 100.0%  val acc  99.2%
epoch 125  train loss 0.0032  val loss 0.0147  train acc 100.0%  val acc  99.2%
epoch 150  train loss 0.0177  val loss 0.0568  train acc  99.8%  val acc  98.3%
final validation accuracy: 98.3%
target reached (>= 95%)
confusion matrix (rows true, cols predicted):
[[40  0  1]
 [ 0 36  1]
 [ 0  0 42]]

The linear baseline scores 44.2%, barely better than the 33% of guessing: spiral arms wrap around each other, so no three straight cuts can separate them. The two-hidden-layer network reaches 97.5% by epoch 25 and finishes at 98.3%, with only two of 120 validation points misclassified (the off-diagonal ones in the confusion matrix). Notice the small bumps in the log at epochs 75 and 150: with Adam at a fixed learning rate, the loss wobbles a little near the end. A decaying schedule (lesson 3.5) would smooth it. This dataset is easy compared with real data; treat 98% here as a sign that the code works, not as a measure of what such small networks can do on harder problems.

Check your understanding

Training loss keeps falling while validation loss has been rising for 100 epochs. What should early stopping keep?

  1. The weights from the last epoch, because the training loss is lowest there
  2. The weights from the first epoch
  3. The weights from the epoch with the best validation score
Early stopping keeps the checkpoint that did best on held-out data. The last epoch is the most overfitted, and the first is barely trained.

Validation accuracy improves while validation loss gets worse. Which explanation fits?

  1. The model fixes some borderline points but becomes overconfident on the ones it still gets wrong
  2. This is impossible: one of the numbers must be a bug
  3. The validation set changed between epochs
Loss measures confidence as well as correctness; accuracy only counts right and wrong. Experiment 3 shows exactly this, with a fixed validation set and no bug.

Why plot loss on a logarithmic axis late in training?

  1. It makes the loss smaller
  2. Halving a small loss (0.02 → 0.01) is invisible on a linear axis but clearly visible on a log axis
  3. Matplotlib requires it for loss curves
A log axis shows relative changes, so late, small improvements remain visible. It doesn't change the values, and nothing requires it.