Handwritten digit recognition with a three-layer ReLU network, derived by hand and trained in NumPy
Revised September 2026
MNIST contains 70,000 greyscale images of handwritten digits, split into 60,000 for training and 10,000 for testing [1]. Each digit was size-normalised into a 20 × 20 box and centred by centre of mass in a 28 × 28 image. Pixel values range from 0 (background) to 255 (full ink). The data ships as four IDX files, which we read with idx2numpy.
A fully connected network has no notion of two-dimensional space, so each image is unrolled row by row into a vector of 784 numbers and divided by 255. Stacking the training examples as columns gives the input matrix $X \in \mathbb{R}^{784 \times m}$ with $m = 60{,}000$. Pixel $(r, c)$ becomes component $j = 28r + c$ of the vector.
We keep the 60,000 training images for fitting and split the official test set in half. The first 5,000 images form a validation set for choosing hyperparameters, and the last 5,000 are held out as the test set.11The two halves are not equally hard. Our models consistently score several points higher on the last 5,000 images than on the first 5,000, which is why test accuracy can exceed training accuracy in Table 4.
The network has an input layer of 784 units, two hidden layers of 20 and 15 units with ReLU activations, and an output layer of 10 units followed by a softmax. We write $a^{[l]}$ for the activations of layer $l$, with $A^{[0]} = X$, and $W^{[l]}, b^{[l]}$ for the parameters mapping layer $l-1$ to layer $l$. A superscript $(i)$ refers to the $i$-th training example.
If layer $l-1$ has $s_{l-1}$ units and layer $l$ has $s_l$ units, then $W^{[l]}$ is $s_l \times s_{l-1}$ and $b^{[l]}$ is $s_l \times 1$. Table 1 lists the resulting shapes.
| Layer | $W^{[l]}$ | $b^{[l]}$ | Activation | Parameters |
|---|---|---|---|---|
| 1 | 20 × 784 | 20 × 1 | ReLU | 15,700 |
| 2 | 15 × 20 | 15 × 1 | ReLU | 315 |
| 3 | 10 × 15 | 10 × 1 | softmax | 160 |
| Total | 16,175 | |||
Weights cannot start at zero. If they did, every unit in a layer would compute the same output and receive the same gradient, and the units would never differentiate. We therefore draw each weight and bias uniformly from $[-\epsilon, \epsilon]$ with $\epsilon = 0.5$ and a fixed seed of 42.
Each layer applies an affine map followed by a non-linearity. For the whole batch at once:
where $\operatorname{ReLU}(x) = \max(0, x)$ acts elementwise and the bias column is broadcast across all $m$ examples. Without the non-linearity the three layers would collapse into a single linear map. ReLU is non-linear because of its flat region, cheap to compute, and its gradient does not shrink for positive inputs. Table 2 tracks the shapes through each layer.
| Quantity | Computed as | Shape |
|---|---|---|
| $Z^{[1]}$ | (20 × 784)(784 × $m$) + (20 × 1) | 20 × $m$ |
| $Z^{[2]}$ | (15 × 20)(20 × $m$) + (15 × 1) | 15 × $m$ |
| $Z^{[3]}$ | (10 × 15)(15 × $m$) + (10 × 1) | 10 × $m$ |
| $\hat{Y}$ | softmax over each column | 10 × $m$ |
The output layer is linear. Its ten values $z_k$, called logits, can be any real numbers, and the softmax turns them into probabilities.
The softmax maps a vector $z \in \mathbb{R}^{K}$ to a probability distribution over $K$ classes:
Each $\hat{y}_k$ lies in $(0, 1)$, the components sum to one, and larger logits receive larger probabilities. Adding a constant to every $z_k$ leaves the result unchanged. In code we therefore subtract $\max_j z_j$ before exponentiating so that $e^{z}$ cannot overflow.
With one-hot labels $y^{(i)} \in \{0,1\}^{10}$, the loss is the categorical cross-entropy averaged over the batch, plus an optional L2 penalty on the weights:
For a single example, the derivative of softmax output $j$ with respect to logit $k$ is $\partial \hat{y}_j / \partial z_k = \hat{y}_j(\delta_{jk} - \hat{y}_k)$. Applying the chain rule to the cross-entropy term:
since the one-hot labels sum to one. This simple result depends on pairing softmax with categorical cross-entropy.22The original notebook combined softmax with a per-class binary cross-entropy, $\sum_k [y_k \log \hat y_k + (1-y_k)\log(1-\hat y_k)]$. Its gradient is not $\hat y - y$, so the loss being reported and the gradient being followed belonged to different objectives. See §8. The output error is simply the predicted distribution minus the true one.
Backpropagation applies the chain rule layer by layer, from the output back to the input, reusing the values of $Z^{[l]}$ and $A^{[l]}$ stored during the forward pass. Writing $\odot$ for the elementwise product and $\mathbb{1}[\cdot]$ for the ReLU derivative:
Each gradient has the same shape as its parameter. For example, $dW^{[3]}$ is (10 × $m$)(15 × $m$)$^\top$ = 10 × 15. The bias gradients sum across examples, one row at a time, so they keep one entry per unit. Gradient descent then moves every parameter a small step against its gradient,
with learning rate $\alpha$. In NumPy, Equations (1) and (5) translate almost line for line:
# forward
Z1 = W1 @ X + b1; A1 = np.maximum(0, Z1)
Z2 = W2 @ A1 + b2; A2 = np.maximum(0, Z2)
Z3 = W3 @ A2 + b3
Z3 = Z3 - Z3.max(axis=0, keepdims=True) # stable softmax
H = np.exp(Z3) / np.exp(Z3).sum(axis=0, keepdims=True)
# backward
dZ3 = H - Y
dW3 = dZ3 @ A2.T / m + lbd / m * W3; db3 = dZ3.sum(axis=1, keepdims=True) / m
dZ2 = (W3.T @ dZ3) * (Z2 > 0)
dW2 = dZ2 @ A1.T / m + lbd / m * W2; db2 = dZ2.sum(axis=1, keepdims=True) / m
dZ1 = (W2.T @ dZ2) * (Z1 > 0)
dW1 = dZ1 @ X.T / m + lbd / m * W1; db1 = dZ1.sum(axis=1, keepdims=True) / m
Hand-derived gradients are easy to get subtly wrong, so we compare them with a central finite difference, $\big(\mathcal{L}(\theta + h) - \mathcal{L}(\theta - h)\big) / 2h$ with $h = 10^{-5}$. We use 64 training examples, $\lambda = 0.1$ and randomly chosen entries of every parameter. Table 3 shows agreement to about eight significant figures.
| Entry | Backprop | Finite difference | Relative error |
|---|
We train with full-batch gradient descent, where every step uses all 60,000 examples. The original notebook stopped after 250 epochs. Figure 4 compares two learning rates over that budget and then follows $\alpha = 0.3$ out to epochs.
| Model | Epochs | Train | Validation | Test |
|---|
With the corrected implementation and the same 250-epoch budget, accuracy is essentially the same as the notebook's. The errors in the original mostly affected the reported loss and the regularisation experiment, not the fitted weights. Training for longer is what helps: the extra epochs raise test accuracy to . The whole run takes about minutes on a single CPU core.
Each row of $W^{[1]}$ holds 784 weights, one per pixel, so it can be reshaped back into a 28 × 28 image. The result shows which pixels push that hidden unit to fire (blue) and which suppress it (red).
This paper is based on an earlier notebook. While rewriting the derivations, we found several places where the code did not match the mathematics. They are listed in Table 5 because each one is a common mistake in from-scratch implementations.
| Issue | Original | Corrected |
|---|---|---|
| Output layer | ReLU applied to $Z^{[3]}$ before softmax, although the text described a linear output | Linear logits, then softmax |
| Loss | Per-class binary cross-entropy on softmax outputs, which is inconsistent with the gradient $\hat Y - Y$ | Categorical cross-entropy, Eq. (3) |
| Regularisation | Penalty computed on the initial weights and absent from the gradients, so every $\lambda > 0$ only added a constant and $\lambda = 0$ always won the sweep | Penalty on the current weights, with $\tfrac{\lambda}{m}W$ in each $dW$ |
| Bias gradients | np.sum(dZ) collapsed each gradient to one scalar shared by every unit | sum(axis=1, keepdims=True) |
| Batch size in loss | Fixed at 60,000, so the 5,000-image validation and test losses were about 12× too small | $m$ taken from the data |
| Softmax | $e^{z}$ computed directly | Subtract the column maximum first |
The regularisation issue explains a result in the notebook that looked puzzling. The cross-validation sweep picked $\lambda = 0$, and the notebook concluded that regularisation does not help. In fact the sweep could not have picked anything else. With only 16,175 parameters and 60,000 examples the network underfits more than it overfits, so a small $\lambda$ probably still would not help. That conclusion now needs to be tested properly, though.
Optimisation. Full-batch gradient descent takes one step per pass over the data. Mini-batch SGD with momentum or Adam would take hundreds of steps per pass and would probably reach the accuracy of the long run in a small fraction of the time.
Initialisation. A uniform $[-0.5, 0.5]$ initialisation ignores layer width. He initialisation [3], which scales the variance by $2/s_{l-1}$, is designed for ReLU networks and would likely reduce the early loss spikes seen in Figure 4.
Capacity. Hidden layers of 20 and 15 units are small. Widening them to a few hundred units typically pushes fully connected MNIST accuracy past 98%. Convolutional networks, which build in the two-dimensional structure that unrolling throws away, exceed 99% [1].
Hyperparameters. The learning rate, the number of epochs and $\lambda$ should be chosen together on the validation set and averaged over several random seeds, since a single seed can land in an unusually good or bad solution.
Robustness. The playground shows the network's main weakness. It has only seen centred, tidy MNIST digits, so digits drawn thin, off-centre or in unfamiliar styles are misread more often. Data augmentation with small shifts, rotations and stroke-width changes would help.