Neural Network from Scratch
A feedforward neural network written in Java with no libraries, trained to count the fingers held up in a photo.
What it does
A feedforward neural network with adjustable depth and layer widths, written without any machine learning libraries. Given a photo of my hand, it says how many fingers I’m holding up, from one to five. On photos it had never seen, it was right 81% of the time.
I derived backpropagation by hand using multivariable calculus and the chain rule, then wrote the training loop and every matrix operation myself.
Six versions
I grew the network one step at a time, testing each version on small problems before moving to images.
- Sep 2025
One hidden layer and a single output, trained with gradient descent.
- Oct 2025
Several outputs at once. One network learned AND, OR, and XOR together. Weights could be saved to and loaded from a binary file.
- Oct 2025
Backpropagation replaced the slower weight-by-weight gradient descent, and every setting moved into a config file.
- Nov 2025
A second hidden layer.
- Dec 2025
Any number of layers, set by one line in the config:
layerSizes = 102400, 100, 40, 5. - Jan 2026
Training on folders of images, saving progress every 100 iterations so long runs could be stopped and resumed.
The training photos
I took six photos for each finger count. Java tools prepared them: each photo was turned to grayscale, cropped to a fixed box centred on the hand’s centre of mass so every hand lands in the same place, and scaled down to 256 × 400 pixels. Every pixel becomes one input between 0 and 1, which is where the 102,400 inputs come from.
The output layer has five nodes, one per finger count. Training aims for 1 on the right node and 0 on the others.
Getting it to generalize
An earlier setup, with 75 and 30 nodes in the hidden layers and a lower learning rate, learned the training photos but got new ones wrong. It had memorized rather than learned. The final network is wider, with 100 and 40 nodes, uses sigmoid activations and a learning rate of 0.65, and starts from random weights between −1.5 and 1.5.
Trained, its 10.2 million weights fill an 82 MB file, which the network loads to classify new photos without retraining.