A Neural Network from Scratch

Handwritten digit recognition with a three-layer ReLU network, derived by hand and trained in NumPy

Shreeyansh Das

Revised September 2026

Abstract We build a fully connected network of shape 784 → 20 → 15 → 10 with no framework beyond NumPy, derive every gradient by hand, and train it on the 60,000 MNIST training images with full-batch gradient descent. The network has 16,175 parameters. After epochs it classifies of held-out test digits correctly. We check the analytic gradients against finite differences, visualise what the first layer learns, and document the corrections made to the original notebook. The trained weights run live in your browser in Figure 1.
  1. 1The MNIST dataset
  2. 2Architecture and notation
  3. 3Forward propagation
  4. 4Softmax and the loss
  5. 5Backpropagation
  6. 6Training
  7. 7What the network learned
  8. 8Corrections to the notebook
  9. 9Limitations and future work
  10. References
Draw a digit here
Network input, 28 × 28
No input yet
Figure 1. The trained network, running in your browser. Your drawing is cropped, scaled to fit a 20 × 20 box and centred by its centre of mass inside a 28 × 28 frame, the same normalisation used to build MNIST. Circles show the activations of the two hidden layers; lines show each connection's contribution $w\cdot a$ to the next layer (blue excites, red inhibits). Bars on the right are the softmax probabilities.

1The MNIST dataset

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.

Hover over the digit to find each pixel in the unrolled vector.
Figure 2. Unrolling. The first test image is shown on the left and as a 784-component vector on the right, where each row of the image becomes a run of 28 consecutive values.

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.

2Architecture and notation

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.

Figure 3. The 784 → 20 → 15 → 10 architecture. Every unit is connected to every unit in the next layer.

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.

Table 1. Parameter shapes and counts.
Layer$W^{[l]}$$b^{[l]}$ActivationParameters
120 × 78420 × 1ReLU15,700
215 × 2015 × 1ReLU315
310 × 1510 × 1softmax160
Total16,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.

3Forward propagation

Each layer applies an affine map followed by a non-linearity. For the whole batch at once:

$$ \begin{aligned} Z^{[1]} &= W^{[1]} X + b^{[1]}, & A^{[1]} &= \operatorname{ReLU}\!\big(Z^{[1]}\big), \\ Z^{[2]} &= W^{[2]} A^{[1]} + b^{[2]}, & A^{[2]} &= \operatorname{ReLU}\!\big(Z^{[2]}\big), \\ Z^{[3]} &= W^{[3]} A^{[2]} + b^{[3]}, & \hat{Y} &= \operatorname{softmax}\!\big(Z^{[3]}\big), \end{aligned} \tag{1} $$

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.

Table 2. Shapes through the forward pass, for a batch of $m$ examples.
QuantityComputed asShape
$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 column10 × $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.

4Softmax and the loss

The softmax maps a vector $z \in \mathbb{R}^{K}$ to a probability distribution over $K$ classes:

$$ \hat{y}_k = \frac{e^{z_k}}{\sum_{j=1}^{K} e^{z_j}}, \qquad k = 1, \dots, K. \tag{2} $$

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:

$$ \mathcal{L} = -\frac{1}{m} \sum_{i=1}^{m} \sum_{k=1}^{K} y_k^{(i)} \log \hat{y}_k^{(i)} \;+\; \frac{\lambda}{2m} \sum_{l=1}^{3} \big\lVert W^{[l]} \big\rVert_F^2. \tag{3} $$

Why the output gradient is $\hat{y} - y$

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:

$$ \frac{\partial \mathcal{L}}{\partial z_k} = -\sum_{j} \frac{y_j}{\hat{y}_j}\, \hat{y}_j\big(\delta_{jk} - \hat{y}_k\big) = -y_k + \hat{y}_k \sum_j y_j = \hat{y}_k - y_k, \tag{4} $$

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.

5Backpropagation

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:

$$ \begin{aligned} dZ^{[3]} &= \hat{Y} - Y \\ dW^{[3]} &= \tfrac{1}{m}\, dZ^{[3]} A^{[2]\top} + \tfrac{\lambda}{m} W^{[3]}, & db^{[3]} &= \tfrac{1}{m} \textstyle\sum_{i} dZ^{[3]}_{:,i} \\ dZ^{[2]} &= W^{[3]\top} dZ^{[3]} \odot \mathbb{1}\big[Z^{[2]} > 0\big] \\ dW^{[2]} &= \tfrac{1}{m}\, dZ^{[2]} A^{[1]\top} + \tfrac{\lambda}{m} W^{[2]}, & db^{[2]} &= \tfrac{1}{m} \textstyle\sum_{i} dZ^{[2]}_{:,i} \\ dZ^{[1]} &= W^{[2]\top} dZ^{[2]} \odot \mathbb{1}\big[Z^{[1]} > 0\big] \\ dW^{[1]} &= \tfrac{1}{m}\, dZ^{[1]} X^{\top} + \tfrac{\lambda}{m} W^{[1]}, & db^{[1]} &= \tfrac{1}{m} \textstyle\sum_{i} dZ^{[1]}_{:,i} \end{aligned} \tag{5} $$

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,

$$ W^{[l]} \leftarrow W^{[l]} - \alpha\, dW^{[l]}, \qquad b^{[l]} \leftarrow b^{[l]} - \alpha\, db^{[l]}, \tag{6} $$

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

Checking the gradients

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.

Table 3. Analytic versus numerical gradients for randomly chosen parameter entries.
EntryBackpropFinite differenceRelative error

6Training

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.

Figure 4. Training cross-entropy per epoch. At $\alpha = 0.1$ the loss falls steadily but slowly. At $\alpha = 0.3$ it drops faster, with brief spikes early on where a step overshoots and the optimiser recovers. The notebook's original loss curve showed the same behaviour.
Table 4. Accuracy on each split. Validation is the first half of the official test set and test is the second half.
ModelEpochsTrainValidationTest

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.

7What the network learned

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).

negativepositive
Figure 5. The 20 rows of $W^{[1]}$ reshaped to 28 × 28, each scaled to its own range. The final weights are dominated by the random initialisation, because training moves them by only about a quarter of their typical size. Subtracting the initial values shows what gradient descent actually learned: blobs and strokes in the central region where digits have ink. The outer border does not change at all, because MNIST has no ink there and those weights never receive a gradient.
Figure 6. Left: confusion matrix on the 5,000 test images. Rows are true labels and columns are predictions, with the diagonal omitted from the shading so that the errors stand out. Right: misclassified test digits, labelled as true → predicted. Some would puzzle a human reader too. Others, such as the 3s read as 5s, are plain mistakes.

8Corrections to the notebook

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.

Table 5. Differences between the original notebook and this paper.
IssueOriginalCorrected
Output layerReLU applied to $Z^{[3]}$ before softmax, although the text described a linear outputLinear logits, then softmax
LossPer-class binary cross-entropy on softmax outputs, which is inconsistent with the gradient $\hat Y - Y$Categorical cross-entropy, Eq. (3)
RegularisationPenalty computed on the initial weights and absent from the gradients, so every $\lambda > 0$ only added a constant and $\lambda = 0$ always won the sweepPenalty on the current weights, with $\tfrac{\lambda}{m}W$ in each $dW$
Bias gradientsnp.sum(dZ) collapsed each gradient to one scalar shared by every unitsum(axis=1, keepdims=True)
Batch size in lossFixed 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 directlySubtract 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.

9Limitations and future work

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.

References

  1. Y. LeCun, L. Bottou, Y. Bengio and P. Haffner. Gradient-based learning applied to document recognition. Proceedings of the IEEE, 86(11):2278–2324, 1998.
  2. I. Goodfellow, Y. Bengio and A. Courville. Deep Learning, chapter 6. MIT Press, 2016.
  3. K. He, X. Zhang, S. Ren and J. Sun. Delving deep into rectifiers: surpassing human-level performance on ImageNet classification. ICCV, 2015.
  4. X. Glorot and Y. Bengio. Understanding the difficulty of training deep feedforward neural networks. AISTATS, 2010.