A neural network in pure NumPy
Every layer is a forward and a backward method. Write four of them and backpropagation falls out.
- Implement forward and backward for a fully connected layer, ReLU and softmax
- Explain why softmax followed by cross-entropy has the gradient p − y
- Check a layer's gradients numerically, and catch a shape bug that tests miss
PyTorch computes gradients for you. 01_ANN does it by hand: each layer is a class with forward(input) and backward(error), and the network is a list of layers run forwards, then backwards in reverse.
def forward(self):
data, self.label = copy.deepcopy(self.data_layer.next())
for layer in self.layers:
data = layer.forward(data)
return self.loss_layer.forward(data, copy.deepcopy(self.label))
def backward(self):
y = self.loss_layer.backward(copy.deepcopy(self.label))
for layer in reversed(self.layers):
y = layer.backward(y)
Each backward receives \(\partial L / \partial \text{output}\) and must return \(\partial L / \partial \text{input}\) — the chain rule, one layer at a time.
The four layers
Fully connected. Forward is \(Y = XW + b\) for a batch \(X\) of shape (batch, in). Backward needs three products:
dx = np.dot(error_tensor, self.weights.T) # passed to the previous layer
dw = np.dot(self.lastIn.T, error_tensor) # gradient for this layer's weights
ReLU passes the error through where its input was positive and blocks it elsewhere: np.where(self.lastIn > 0, error_tensor, 0).
Softmax subtracts the row maximum before exponentiating — mathematically a no-op, numerically the difference between a probability and inf/inf.
Cross-entropy is \(L = -\sum y \log \hat{y}\). Its backward, \(-y / \hat{y}\), fed through softmax’s backward, collapses to the simplest gradient in deep learning:
\[\frac{\partial L}{\partial z} = p - y\]With the repository’s own layers, logits \((2.0, 1.0, 0.1)\) and true class 0 give \(p = (0.659, 0.242, 0.099)\) and exactly \(p - y = (-0.341, 0.242, 0.099)\).
A bias that grows a batch dimension
The weight update uses dw, summed over the batch by the matrix product. The bias update does not sum:
self.bias = self._optimizer.calculate_update(self.bias, error_tensor)
error_tensor has shape (batch, out), so after the first update the bias — which started as (1, out) — has shape (batch, out). Run on a batch of 9: after one step the bias is (9, 3), a forward pass on a single sample returns 9 rows, and a batch of 5 fails with a broadcasting error. The layer tests keep one batch size from start to finish, so the extra dimension goes unnoticed there.
The fix is one sum, db = np.sum(error_tensor, axis=0) — and the CNN version of the same file in the next lesson has it, along with separate optimizer copies for weights and bias, which matter as soon as the optimizer keeps state.
Checking gradients
The repository’s Helpers.gradient_check compares each analytic gradient with a central difference, \((L(x + \varepsilon) - L(x - \varepsilon)) / 2\varepsilon\). It is the single most useful test for hand-written backprop: on the small network above the two agree to \(7 \times 10^{-11}\).
Try it yourself. Apply the bias fix, then train the network in NeuralNetworkTests.py’s Iris test and confirm test() now works on a batch of any size. Next, write gradient_check for the bias and show that it fails before the fix (the shapes disagree) and passes after.