Close the windows and show the desktop

Blog

That's how I wrote a neural network from scratch in C++

This is how I wrote a neural network in C++ with no ML libraries. It reads handwritten digits from MNIST and it works. The code is here, and you’re welcome to read it, run it and break it: SonicallGameXGit/EE_EE.

Heads up: this is not a guide from an expert in computer science or machine learning. It’s a blog post from a regular person figuring things out, and I’m sure I still understand a lot of it wrong. But I made some progress, and maybe my way of looking at it will help you. If you spot a mistake, tell me.

The main idea: you don’t need pure math to write your own neural network. No formulas here. Just what each piece does and why, in plain words, so that it makes sense on an intuitive level. If it does, the code follows.

Step 1: a feedforward network

Layers of numbers, with a weight on every connection between two layers. A neuron in the next layer is the sum of the previous layer’s neurons times their weights, squashed by an activation function. Data goes in on one side and comes out on the other. That’s the whole “feedforward” part.

A feedforward neural network: three input neurons, four hidden neurons and two output neurons, every neuron connected to every neuron of the next layer
Every neuron is connected to every neuron of the next layer. Each line has its own weight.

In code it’s two loops. This is forward() from the very first version of my network: for every neuron of the next layer, go through every neuron of the previous layer and add value * weight.

void forward() {
    for (size_t i = 0; i < this->b->neurons.size(); i++) {
        this->b->neurons[i].value = 0.0f;
        for (size_t j = 0; j < this->a->neurons.size(); j++) {
            this->b->neurons[i].value += this->a->neurons[j].value * this->weights[j + i * this->a->neurons.size()];
        }
        this->b->neurons[i].applyBias(this->b->bias);
        this->b->neurons[i].applySigmoid();
    }
}

Two details are worth knowing before moving on.

Not every feedforward network is a perceptron

A perceptron is just a feedforward network with a threshold as the output activation: below some value you get 0, above it you get 1. It’s a special case, not the general name.

A step function: 0 for negative inputs, 1 for positive inputs A smooth S-shaped sigmoid curve going from 0 to 1
A hard threshold on the left (perceptron), a smooth squash on the right (sigmoid). Images: Lennart Kudling and Qef, public domain, via Wikimedia Commons.

Bias is a weight

A common first guess, and the one I started with (see applyBias above), is that bias is one number per layer, added to every neuron’s sum and tweaked by training. That’s about 50% right.

The cleaner way is a “phantom” neuron whose value is always 1.0, connected to the next layer like any other neuron, with its own outgoing weights. Its contribution is 1.0 * weight, so that weight is the bias. Training treats it like any other weight, so there are no special cases.

Weight and bias diagram: a constant neuron with value 1 and its own weight w0, next to the regular inputs and their weights, all going into a weighted sum and a step function
The constant 1 gets its own weight like any other input. That weight (w0) is the bias.Image: YouTube

I don’t create the neuron for real. It would need exceptions to keep it at 1.0, and it would waste memory. Each connection just stores one extra weight per next-layer neuron. That’s the + 1 in my weights array size:

// +1 for bias weights
const size_t capacity = (a.neurons.size() + 1) * b.neurons.size();

The extra weight sits at the end of each neuron’s group of weights, and forward() adds it without multiplying, because multiplying by 1.0 changes nothing:

float getBiasWeight(const size_t bIndex) const {
    return this->weights[this->a->neurons.size() + bIndex * (this->a->neurons.size() + 1)];
}
void forward() {
    for (size_t i = 0; i < this->b->neurons.size(); i++) {
        this->b->neurons[i].value = 0.0f;
        for (size_t j = 0; j < this->a->neurons.size(); j++) {
            this->b->neurons[i].value += this->a->neurons[j].value * this->getWeight(j, i);
        }
        this->b->neurons[i].value += this->getBiasWeight(i); // bias weight
        this->b->neurons[i].value = this->b->neurons[i].getActivatedValue(this->b->neurons[i].value);
    }
}

Step 2: training

My network with no hidden layers worked, so I tried to “backpropagate” it. That’s where it got hard.

Backpropagation is not training

It’s easy to assume it’s the algorithm that magically trains the network. It isn’t. It only answers one question: for every weight, how much should I change it, and in which direction? It does that exactly and fast, thanks to math. The training itself is a separate thing.

To understand it, I built training without backprop first.

Training the dumb way

  1. Loss. Compare each output neuron with the correct answer, square the difference and sum it up. Zero is perfect and bigger is worse. Squared, not abs, because a smooth curve is much easier to descend. More on that when we get to real backprop.
  2. Poke. Change one weight by a tiny step.
  3. Recompute. Run the entire forward pass again and get the new loss.
  4. Slope. Divide the loss change by the step. That gives a stable number that doesn’t depend on how small the poke was. It says how much and which way the loss moves.

If the loss dropped, move the weight further that way. If it grew, move it the opposite way. Both cases are one rule:

const float step = 0.001f
const float lossBefore = calculateLoss()

weight += step
const float lossAfter = calculateLoss()
weight -= step // put it back

const float slope = (lossAfter - lossBefore) / step
weight -= slope * learnRate

Do that for every weight, on every example. Even this slow, approximate method trains the network.

steploss changed by this muchbeforeafterloss fell: move this waylossone weight
Poke one weight by a step, measure how the loss changed. Dividing the two gives the slope. (The step is drawn huge so you can see it.)

Learning rate

The slope is only valid right where the weight stands, and the loss is a huge multi-dimensional shape (our network is that shape). So you don’t move the full distance.

Picture a ball on hills. Nudge it and it settles into a valley, maybe only a local minimum. Shove it and it flies over the valley and lands somewhere else. Shove it every step and it never settles. The learning rate is how hard you push. Too big and you jump over good spots, too small and you crawl.

Animation of three balls rolling down a hilly surface, each settling in a different valley
Three balls rolling downhill from different starting points. Different starts can end in different valleys.Image: Jacopo Bertolotti, CC0, via Wikimedia Commons

Why backprop exists

  • Cost. One full forward pass per weight, for a single update.
  • Poke size. Too small and floating-point error eats the difference. Too big and the slope is wrong because the shape curved in between.

Backprop gives the same answer for every weight for roughly the price of one extra pass, with no step size at all.

Step 3: backpropagation

I’m really bad at math. Functions, derivatives and the chain rule, explained with no context, were torture for me. What finally worked was a couple of great videos (this one and this one) and a lot of asking an AI the same question five different ways. Now I roughly get it, and I implemented the whole algorithm myself, formulas included. Here’s the intuition that made it click.

It’s game physics

Remember the rolling ball? It’s the same thing as a player moving in a game. Every tick you change the position by the velocity. That’s all.

Now map it onto training:

  • Position is the loss from the forward pass.
  • Time (the x on a graph, like in Desmos) is the weight we’re changing.
  • Velocity is the slope we measured by poking. In math it’s called the derivative: how fast the position changes per unit of time.
  • Delta time, the size of one tick, is our learning rate.

Two cases to feel it.

Case 1. The player moves at a constant 1 unit per second. What’s the derivative? Just 1.0, forever.

Animation: a dot moves along a track at constant speed while its position over time is drawn as a straight line with a constant slope of 1.0
Constant speed: the position is a straight line and the slope never changes.

Case 2. The velocity equals x itself: the longer it goes, the faster it moves. The player speeds up more and more, and the path is a parabola. Same thing as gravity pulling something down.

Animation: a dot falls faster and faster while its position over time is drawn as a parabola and the slope at the current point keeps getting steeper
Speeding up: the position is a parabola, and the slope (the orange line) gets steeper every second.

Now the important part. When you find the derivative of a function as a formula, you can plug in any point (a weight, an activation value, whatever) and get the slope right there, instantly and exactly. No poke, no second forward pass, no step size. That’s backpropagation: a formula for the slope instead of a measurement.

The chain rule

Our loss is not one simple function. It’s a long chain: weight, multiplied by an input, summed with others, squashed by the activation, compared with the answer, squared. Nobody writes one derivative for that monster.

The chain rule says: split it into small steps, take the slope of each step, and multiply them all. Each small step has a well-known slope:

weightinputweightx input1sumactivation slopeactivation2 x errorlossbackpropagation walks this way and multiplies the slopes
The loss is a chain of small steps. Every link has a simple slope. Multiply them all and you get the slope of the weight.
  • The squared difference. Its slope is the error itself, doubled. A big mistake gives a big push, a small one a gentle push, and it’s smooth around zero. That’s why I use squared and not abs: abs has the same slope everywhere and a sharp corner at zero.
  • The activation. Sigmoid and ReLU both have simple slopes. Sigmoid’s can even be computed from its own output, so I don’t need to remember the sum.
  • Multiplication by an input. The slope of input * weight with respect to the weight is just the input.
  • Addition. The slope is 1. Nothing changes, it just passes through. That’s also why the bias weight, which is multiplied by the constant 1.0, gets the same treatment as every other weight with no input factor at all.

Multiply them together and you get exactly “how much does the loss change if I move this weight”. This is the output layer from my Network::backward():

for (size_t i = 0; i < lastConnection.b->neurons.size(); i++) {
    const float chainRuleOutput = lastConnection.b->neurons[i].value;
    // dLoss/dz: (loss slope) * (activation slope)
    const float chainRuleGeneralSlope = -2.0f * (answers[i] - chainRuleOutput) * lastConnection.b->neurons[i].getActivationSlope(chainRuleOutput);
    lastConnection.b->deltas[i] = chainRuleGeneralSlope;
}

The first factor is the loss slope (with the minus sign, because the error is answer - output), the second is the activation slope. I store the result per neuron because the next step reuses it. Then every weight pointing into that neuron multiplies it by its own input, and that’s the slope of that weight:

for (size_t j = 0; j < lastConnection.a->neurons.size(); j++) {
    lastConnection.setWeight(j, i, lastConnection.getWeight(j, i) - delta * lastConnection.a->neurons[j].value * learnRate);
}
lastConnection.setBiasWeight(i, lastConnection.getBiasWeight(i) - delta * learnRate);

Look at the last line. It’s the same update, weight - slope * learnRate, as in my poke loop. The bias weight just skips the input factor, since its input is 1.0.

Swap and go

That’s all. Take the slow training from before, throw away everything between “poke the weight” and “get the slope”, and put this in its place. The slope now comes from the formula, the weight update stays exactly the same, and the network trains. Same result, but without a forward pass per weight.

Step 4: hidden layers

Applying the same rule to every layer is not enough. The output layer knows the correct answer, so it can compute its own error. A hidden neuron has no answer to compare with. Its mistake only exists through the neurons after it.

The chain rule handles that too, but it asks for a lot: to get the slope of a weight in an early layer, you have to multiply the slopes of everything between that weight and the loss. Doing that from scratch for every weight would be a mess, and most of the multiplications would repeat.

So I do it once and keep the results. That’s what the deltas array in every layer is for. Every neuron stores one number: how much the loss changes if this neuron’s sum changes. Computing it goes backwards, layer by layer:

  1. The output layer computes its deltas from the answers, as in step 3.
  2. A hidden neuron asks every neuron it feeds: “how much do you care about me?” Each answer is that neuron’s delta times the weight connecting them. The neuron adds them all up and multiplies by its own activation slope. That’s its delta.
  3. Repeat, one layer further back, until you reach the input.
inputhiddenoutputdeltadeltahighlighted neuron: delta = (their delta x weight, added up)x its own activation slope
A hidden neuron has no answer to compare with. It collects the deltas of the neurons it feeds, scaled by the weights between them.
for (size_t i = this->connections.size() - 1; i > 0; i--) {
    const Connection &connection = this->connections[i];
    for (size_t j = 0; j < connection.a->neurons.size(); j++) {
        const float inputValue = this->connections[i].a->neurons[j].value;
        const float inputActivationSlope = this->connections[i].a->neurons[j].getActivationSlope(inputValue);
        this->connections[i].a->deltas[j] = 0.0f;
        for (size_t k = 0; k < connection.b->deltas.size(); k++) {
            this->connections[i].a->deltas[j] += inputActivationSlope * connection.getWeight(j, k) * connection.b->deltas[k];
        }
    }
}

Only after all deltas are filled do I touch the weights. If I changed weights while walking backwards, the earlier layers would use already-modified weights and the slopes would be wrong. So backward() is two passes: first fill the deltas, then update every weight with the same rule as before, delta times the input times the learning rate:

connection.setWeight(k, j, connection.getWeight(k, j) - delta * connection.a->neurons[k].value * learnRate);

The video that made this part click for me is this one. It’s the same one as before, and it’s worth a rewatch for this step in particular.

Step 5: teaching it digits

Now we have everything to train a real network. The classic first task is MNIST: 70,000 images of handwritten digits, 28x28 pixels, in grayscale. The files are in the repo under assets/mnist.

Ten MNIST training images, one for each digit from 0 to 9, white handwriting on black
A few MNIST images, one per digit, as they are in the files (scaled up 5x).

Reading MNIST

The files are in a simple binary format called IDX. A small header, then raw bytes. All integers in the header are big-endian, but your CPU is almost certainly little-endian, so every integer has to have its bytes flipped after reading.

Images (train-images.idx3-ubyte):

OffsetTypeMeaning
0int32magic number, always 2051 (a sanity check)
4int32number of images (60,000 for training)
8int32image height, 28
12int32image width, 28
16unsigned bytepixels of the first image, row by row, 0 is black and 255 is white. All other images follow one after another with no gaps

Labels (train-labels.idx1-ubyte):

OffsetTypeMeaning
0int32magic number, always 2049
4int32number of labels
8unsigned bytethe digit 0-9 of the first image, one byte per image, in the same order as the images

My implementation is just that table in code. The byte flip, the header, then the pixels scaled to 0..1, because that’s what a sigmoid neuron likes as input:

int32_t flipBytesInt32(const int32_t value) {
    return (value << 24) & 0xFF000000 |
           (value << 8)  & 0x00FF0000 |
           (value >> 8)  & 0x0000FF00 |
           (value >> 24) & 0x000000FF;
}

// ...inside ImagesMNIST::fromFile
int32_t magicNumber;
file.read(reinterpret_cast<char*>(&magicNumber), sizeof(magicNumber));
magicNumber = flipBytesInt32(magicNumber); // 2051, or this is not an images file
// numImages, imageHeight and imageWidth are read and flipped the same way

for (size_t i = 0; i < imageCount; i++) {
    for (size_t j = 0; j < imageWidth * imageHeight; j++) {
        char pixel;
        file.read(&pixel, sizeof(pixel));
        items[i].push_back(static_cast<float>(static_cast<uint8_t>(pixel)) / 255.0f);
    }
}

The network gets 784 inputs (one per pixel) and 10 outputs (one per digit). For the correct answer I set the output of the right digit to 1.0 and all others to 0.0. After training, whichever output is the largest is the network’s guess.

Making it harder to cheat

I use hidden layers of 16, 8 and 16 neurons, and a learning rate of 0.01. The network is a black box, so it’s hard to know how well a layout like that will train. What I do know is that training on the original images alone is not great. They’re all nicely centered and straight, and the digits people draw by hand are not.

So after the first pass over the dataset, every following pass shows the same images with random distortions: rotated up to 15 degrees either way, stretched or squeezed by up to 10%, and shifted by up to 2 pixels.

The same handwritten 7 six times: the original on the left, then five randomly rotated, stretched and shifted copies
One 7: the original, then five random distortions of it.
const float angle = glm::linearRand(-15.0f, 15.0f) * pi / 180.0f;
const float scaleX = glm::linearRand(0.9f, 1.1f);
const float scaleY = glm::linearRand(0.9f, 1.1f);
const float translateX = glm::linearRand(-2.0f, 2.0f);
const float translateY = glm::linearRand(-2.0f, 2.0f);

The network never sees the exact same picture twice, so it can’t just memorize them. It has to learn what a “7” looks like in general. I run 25 passes like this, and the whole training loop is: pick an image, run forward(), set the answers, run backward(), repeat.

Does it work?

To try it, I wrote a tiny drawing app with raylib: a 28x28 canvas, a soft brush, and a forward pass after every stroke. The app picks the output neuron with the highest value and says “I guess… N!“. Press E to clear.

size_t maxGuessId = 0;
float maxGuess = 0.0f;
for (size_t i = 0; i < network.outputLayer.neurons.size(); i++) {
    if (network.outputLayer.neurons[i].value > maxGuess) {
        maxGuess = network.outputLayer.neurons[i].value;
        maxGuessId = i;
    }
}
Drawing a digit on a 28x28 canvas while the network updates its guess live
Drawing a digit, and the network guessing live.

That’s so cool. Something I typed out as a pile of loops reads my handwriting.

That’s the whole thing. The code is in the repo. Run it, change the layers, break the learning rate, and see what happens. That’s the fastest way I know to build an intuition for it.

Talk about it

Liked it, or want to argue? Share it: