Sheikh

Project · 2025

mlp-from-scratch

A multilayer perceptron with every derivative worked out by hand

Stack
Python, NumPy, pandas
Licence
MIT

Abstract

A multilayer perceptron written from first principles in NumPy, as a way to learn how neural networks actually train. The network is 784-64-32-10, with ReLU hidden layers, a softmax output and a clipped cross-entropy loss. Its gradients are derived by hand and it trains by stochastic gradient descent with momentum. On MNIST it classifies 97.3% of the 10,000 test images correctly. Trained networks save and reload without retraining.

Keywords backpropagation · gradient descent · MNIST · NumPy

Prose paragraphs are stand-ins for Sheikh to rewrite; numbers, tables and references come from the repo.

1Introduction

I built this to learn how neural networks train: the forward pass, the backward pass and the update written by hand instead of called from a framework. The classifier is how I knew it worked, and the notebook keeps the derivations, in LaTeX, beside the code.

2Data

MNIST, in its CSV form from Kaggle [1, 2]: 60,000 training and 10,000 test images of handwritten digits, 28 by 28 pixels (Figure 1). Each image becomes a vector of 784 values scaled to [0, 1] (Figure 2), and each label a one-hot vector of length 10.

3Model

Each layer multiplies, adds a bias and applies an activation:

ReLU in the two hidden layers and softmax at the output:

The loss is cross-entropy with the prediction clipped away from 0 and 1, so the logarithm stays finite:

4Backpropagation

Gradients come from backpropagation [3]. With softmax and cross-entropy together, the error at the output is the prediction minus the label:

Each hidden layer’s error is the next layer’s, sent back through its weights and gated by the ReLU derivative:

and the gradients follow from and :

5Training

Weights and biases start uniform on [−0.5, 0.5]. Training visits the samples in a new random order each epoch and updates after every one, with momentum:

A trained network saves its weights as a compressed .npz file, with its layer sizes, activations and parameter count in JSON beside it.

6Results

Table 1. Accuracy on MNIST.
SetImagesWrongAccuracy
Training60,00037099.38%
Test10,00027097.30%

The gap between the two rows is the usual one for a dense network on pixels: it fits the training set almost exactly and loses a little on digits it has not seen.

7Code

The notebook, with the derivations in LaTeX beside the code: github.com/shyagehike/mlp-from-scratch ↗.

References

  1. LeCun, Y., Bottou, L., Bengio, Y., & Haffner, P. (1998). Gradient-based learning applied to document recognition. Proceedings of the IEEE, 86(11), 2278–2324.
  2. oddrationale. MNIST in CSV. Kaggle. kaggle.com/datasets/oddrationale/mnist-in-csv ↗
  3. Rumelhart, D. E., Hinton, G. E., & Williams, R. J. (1986). Learning representations by back-propagating errors. Nature, 323, 533–536.