Epoch After Epoch

Training Deep NetworksHard+30 XP+30

Epoch After Epoch

Chapter 5 ended with a full training run: forward pass, loss, backward pass, update, batch after batch and epoch after epoch. Here you write that loop yourself, for the smallest network that still has a hidden layer, with nothing random in it so every run is reproducible.

The network. An input xxx has ddd numbers. A hidden layer of hhh ReLU neurons feeds a single output with no activation:

zj=∑ixi Wij(1)+bj(1),aj=max⁡(0,zj),y^=∑jaj Wj(2)+b(2)z_j = \sum_{i} x_i \, W^{(1)}_{ij} + b^{(1)}_j, \qquad a_j = \max(0, z_j), \qquad \hat{y} = \sum_{j} a_j \, W^{(2)}_j + b^{(2)}zj​=i∑​xi​Wij(1)​+bj(1)​,aj​=max(0,zj​),y^​=j∑​aj​Wj(2)​+b(2)

In code these are W1[i][j] (the weight from input iii to hidden neuron jjj), b1[j], W2[j] (one number per hidden neuron) and b2 (a single number).

The ReLU's slope. When you send gradients back through a hidden neuron, its slope is 111 where zj>0z_j > 0zj​>0 and 000 where zj≤0z_j \le 0zj​≤0. That includes zjz_jzj​ being exactly 000: there the slope is 000.

The loss. Mean squared error: the average of (y^−y)2(\hat{y} - y)^2(y^​−y)2 over whichever examples are being scored. For a batch of mmm rows, each row's prediction receives ∂L/∂y^=2m(y^−y)\partial L / \partial \hat{y} = \tfrac{2}{m}(\hat{y} - y)∂L/∂y^​=m2​(y^​−y); every other gradient follows from the chain rule.

The run.

  • Mini-batches are taken in order, with no shuffling: rows 0 to batch_size - 1, then the next batch_size rows, and so on. If the rows don't divide evenly, the last batch is simply smaller.
  • For each batch, compute the gradient of that batch's mean squared error with respect to every weight and bias, then update all of them with plain gradient descent: θ←θ−lr⋅∂L∂θ\theta \leftarrow \theta - \text{lr} \cdot \dfrac{\partial L}{\partial \theta}θ←θ−lr⋅∂θ∂L​.
  • One epoch is one pass through every batch.

Task: write train(X, y, W1, b1, W2, b2, lr, batch_size, epochs). X is a list of rows and y a list of targets.

Return a list with one number per epoch: the mean squared error over the whole training set, measured with the weights as they stand at the end of that epoch, rounded to 4 decimal places.

Examples

X = [[1.0], [2.0], [3.0]]
y = [2.0, 3.5, 5.0]
W1 = [[0.5, -0.4]]
b1 = [0.1, 1.0]
W2 = [1.0, 0.5]
b2 = 0.0
lr = 0.05
batch_size = 2
epochs = 3
returns [6.7297, 6.5034, 4.8261]
X = [[1.0, 0.0], [0.0, 1.0], [1.0, 1.0], [2.0, 1.0]]
y = [1.0, -1.0, 0.5, 1.5]
W1 = [[0.3, -0.2, 0.5], [0.1, 0.4, -0.3]]
b1 = [0.0, 0.1, 0.0]
W2 = [0.6, -0.5, 0.2]
b2 = 0.1
lr = 0.1
batch_size = 2
epochs = 2
returns [0.3409, 0.2305]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run