Skip to content

Coding a neural network in C

Neural networks are the backbone of every state-of-the-art use case of AI at the moment. Let's see how they work by writing one from scratch in C.

Mathematical functions

From the outside, a neural network is basically a function like \(f(x) = y\) that takes an input \(x\) and spits out \(y\). And under the hood, there's just a bunch of math going on, so there's nothing magical about them.

The \(x\) and \(y\) could be single numbers, but they can also be arrays of numbers (vectors, matrices, etc.)

Take this function for example:

\[ f(x) = ax \]

Assuming that \(x\) and \(y\) are single numbers (scalars), the function describes a straight line:

Plot of a straight line with one parameter −2 −1 0 1 2 3 4 −1 0 1 2 x f(x)

The parameter \(a\) can be used to adjust the slope of the line. We can turn it into a mini neural network like this:

Mini neural network

It's a bit wild to call this a neural network, but technically it is. And this is about as small as they get.

The circles are the artificial neurons, the line that connects them is the artificial "synapse" if you will, but we can just call it a connection to keep it simple. The connection always has a certain "strength" or weight assigned to it, \(a\) in this example. The weights of the connections are the parameters of the math function that can be tuned.

Training

Neural networks have to be "trained" before they become useful. Training a neural network is like choosing a function you want to fit through some data points and finding the right parameters that make it fit well to the data.

So in order to train a neural network, we need some training data, or training examples. Then we mess around with the weights, and try to find the best set of weights that fit the training data well.

In the case of our simple \(f(x) = ax\) example, that means finding the right value for \(a\) that best fits our data points:

A line fitted through data points −1 0 1 2 3 4 5 −1 0 1 2 3 x f(x)

For this simple example, finding the right \(a\) is easy, and using a neural network is unnecessary. But if you want to model something way more complicated, with not a single \(a\) parameter but parameters in the thousands, millions or more, neural networks offer a very elegant way of finding the right values for those parameters. We'll get to this.

Multiple incoming connections

Going back to our mini neural network:

Mini neural network

The calculation works by taking the value of the first neuron \(x\), multiplying it by the connection weight \(a\), and then collecting the resulting value at the last neuron \(y\).

What happens if multiple neurons are connected to \(y\)? We take the sum of all incoming values.

So if we add a new constant neuron with a value of 1, and a connection with a weight \(b\) we get this:

Neural network with bias

This extra \(1\) node allows us to simply add a constant \(b\) to the final output.

So with that, we can model a function like this:

\[ f(x) = ax + b \]

The input of the function is still \(x\), but we now have more parameters: \(a\) and \(b\). These parameters allow us to change the function and fit it to some data points.

This extra \(b\) parameter is useful in case our data points are shifted up / down. It gives us more freedom to find the perfect line through these data points:

A line fitted through data points with extra bias parameter −1 0 1 2 3 4 5 −1 0 1 2 3 4 x f(x)

This ability to shift the value around by a constant is very important in neural networks; we call this bias.

Activation functions

One final piece we need is the concept of an activation function. This is a function that belongs to a neuron and maps the incoming value to the final output of the neuron.

Instead of just summing up all incoming values like we did before, we pass this sum through a function to calculate what's called the activation of the neuron.

The reason it's called an activation function is because this mimics the concept of real neurons, which can be active (firing) or inactive.

If you want to model interesting behaviour with a neural network, it turns out this activation function should be something non-linear.

In the rest of this article, I will be using the sigmoid function as the activation function in all neurons. This is a very commonly used activation function. And once we get the basics, we can implement it in a way where it's easy to swap it out for other activation functions.

The sigmoid function squeezes every value between 0 and 1 in a smooth way:

Plot of the sigmoid function −8 −6 −4 −2 0 2 4 6 8 −0.5 0 0.5 1 1.5 x σ(x)

The formula is:

\[ \sigma(x) = \frac{1}{1 + e^{-x}} \]

In C we can implement sigmoid like this:

#include <math.h>

float sigmoid(float x) {
  return 1.0f / (1.0f + expf(-x));
}

Note that I'm using expf which works with the 32-bit float type instead of the more natural-sounding exp, which would work on the 64-bit double type.

If we apply this to the last neuron of our mini neural network, the total neural network would become a function that looks like this:

\[ f(x) = \sigma(ax + b) = \frac{1}{1 + e^{-(ax + b)}} \]

I like using sigmoid, especially for the output layer of a neural network, because this way we always get a clean output between 0 and 1. This allows us to model problems in a "binary" way, where the input is just 0's and 1's, and the output is, too.

Layers of neurons

To create functions that can model more complex and interesting things, we just use a bigger network by adding more neurons and connections.

Instead of randomly throwing in more circles and connections, we're going to organise the neurons in vertical layers. We'll have an input layer on the left that corresponds to the input \(x\). It can be a single neuron for a single input number, or multiple neurons if \(x\) is a vector.

In the same way we'll have an output layer on the right that represents the \(y\). If \(y\) is a single number, it's one neuron, but it can be multiple as well just like \(x\).

With this layered approach, the input and output layers are mandatory, so we need at least two layers. In addition, we have some optional in-between layers. These are called hidden layers because they never connect to the outside of the network:

Neural network with hidden layer

You usually want to have at least one hidden layer to be able to model some interesting behaviour with your network.

Connections only go from neurons in one layer to neurons in the next layer. There are more exotic neural network architectures possible where we break this rule, but in the rest of the article I'll assume connections only going from one layer to the next.

Also, I'm going to assume that every neuron is connected with every neuron in the next layer. This is also known as a fully connected neural network. Again, this rule can definitely be broken, but for simplicity we'll stick to fully connected networks for the sake of fitting this into one article instead of a three-volume book series.

The hello world of neural nets

Now that we have established all building blocks for a neural network, we're going to start with a simple toy example: a neural network that models the behaviour of the XOR (exclusive OR) operation.

XOR is a binary operation, taking in two bits and spitting out one. It's similar to OR, except when both input bits are true, the output is false.

This is the truth table of XOR and will be serving as our training data:

\(x_1\) \(x_2\) \(y\)
0 0 0
0 1 1
1 0 1
1 1 0

This is a good example to start with, because it's small enough to write out all the calculations by hand, but still challenging enough of a task that requires at least one hidden layer with a non-linear activation function. (If we don't give it a hidden layer, the network won't be able to fit to the data of the truth table.)

What would this training data look like in C? In the matrix article we created mat.c. So we can use a bunch of Mat structs to put this data into matrices:

#include "mat/mat.h"

int main(void) {

  // TRAINING DATA
  Mat xs = mat_new(4, 2, (float[]) {
    0, 0,
    0, 1,
    1, 0,
    1, 1,
  });

  Mat ys = mat_new(4, 1, (float[]) {
    0,
    1,
    1,
    0,
  });

  return 0;
}

Now we have the input data in a 4×2 Mat matrix called xs, and the output data (or labels) in a 4×1 matrix ys.

Since we use \(x\) and \(y\) to describe the training data, the value that the network actually spits out for a given \(x\) needs a different name. In math notation we'll call it \(\hat{y}\) and the goal is to get this as close as possible to \(y\).

Architecture

The architecture of a fully connected neural network consists of the number of layers, and the number of neurons in each layer. The number of neurons in the input and output layers depends on the type of function we want to model. For the XOR network, the input layer needs 2 neurons, and the output layer will get 1 neuron.

The hidden layers are where we have some flexibility.

We're going to use one hidden layer with two neurons, because that is the minimum number we need to make XOR work. But it will keep the neural network small enough to look closely at how the values flow through it.

So with two input neurons, two hidden neurons, and one output neuron, this is what the XOR neural network looks like:

XOR neural network architecture

Notation

To keep track of the values and how to evaluate the function that our neural network models, let's figure out a consistent notation for everything.

We need three different types of variables. The value of a neuron, or activation which we'll call \(a\) (the number that comes out of a neuron). For the weights we'll use \(w\) (the strength of a connection). And we need \(z\), which is the sum of all the activations \(a\) multiplied by the weights \(w\) that are incoming into a neuron.

"Sum" doesn't start with a \(z\), but this is the convention of most of the literature. Also, instead of \(w\) for weights, \(\theta\) (theta) is more commonly used for parameters. But I'm more of a programmer than a mathematician, so I prefer using \(w\), which will translate better to a variable name like w in the code.

This is what it looks like in the neural network sketch:

Neural network notation

Notice that we have a lot of different \(a\)'s, \(z\)'s and \(w\)'s everywhere. To be able to keep them apart I'm using subscripts and superscripts.

The subscript \(L\) in \(a_L\) shows which layer index we're on. The superscript \(n\) for \(a^n\) and \(z^n\) means the neuron index inside a certain layer (not to be confused with taking it to the power \(n\)).

Note that \(L\) in this context is not strictly looking at a certain layer of neurons, rather the space between two layers:

Neural network layer indices

The weights are a bit more complicated because they are sitting between the neurons and connect every neuron on the left to every neuron on the right. So we need a two-dimensional superscript \(i,j\) for the weights. So \(w^{i,j}\) means the weight that connects neuron \(i\) on the left to neuron \(j\) on the right.

It's more conventional for the super- and subscripts to be swapped, but I prefer it this way because we can soon get rid of the superscripts altogether by vectorising the whole operation. And I think it looks cleaner to denote the index of a variable with a subscript instead of a superscript. As long as we're consistent with the notation, it'll work fine.

Forward pass

The forward pass in the context of a neural network means we're simply evaluating the math function: passing in \(x\) and calculating \(\hat{y}\). (Remember, the regular \(y\) is reserved for the training data.)

We're simply taking the input \(x\), and moving it through the network from left to right, step by step.

The first step is setting the \(a_0\)'s to the value of \(x\).

From there, the \(a_0\)'s are multiplied by every connection's weights \(w_0\), and at \(z_0\) we take the sum of all these \(a \cdot w\) products. For the first sum \(z_0^0\) this looks like:

Forward pass z-0-0

And the calculation:

\[ z_0^0 = a_0^0 \cdot w_0^{0,0} + a_0^1 \cdot w_0^{1,0} \]

The next one, \(z_0^1\) is very similar:

Forward pass z-0-1
\[ z_0^1 = a_0^0 \cdot w_0^{0,1} + a_0^1 \cdot w_0^{1,1} \]

This can be generalised like this:

\[ z_L^n = \sum_m a_L^m \cdot w_L^{m,n} \]

Where \(m\) is the neuron index on the left layer, \(n\) the neuron index on the right layer. And \(L\) is the layer we're looking at.

I found this works well when we move on to implementing it in C, because all the variables can start at index 0 this way.

Moving on to the next layer \(L=1\), \(a\) is calculated by taking the \(z\)'s through the activation function of the neurons:

\[ a_1^n = \sigma(z_0^n) = \frac{1}{1 + e^{-z_0^n}} \]

We keep doing this until we reach the final \(a\) in the output layer, and that is the final output \(\hat{y}\). This is the entire forward pass written out number by number from \(x\) to \(\hat{y}\):

\[ \begin{aligned} a_0^0 &= x^0 \\ a_0^1 &= x^1 \\ z_0^0 &= a_0^0 \cdot w_0^{0,0} + a_0^1 \cdot w_0^{1,0} \\ z_0^1 &= a_0^0 \cdot w_0^{0,1} + a_0^1 \cdot w_0^{1,1} \\ a_1^0 &= \sigma(z_0^0) \\ a_1^1 &= \sigma(z_0^1) \\ z_1^0 &= a_1^0 \cdot w_1^{0,0} + a_1^1 \cdot w_1^{1,0} \\ a_2^0 &= \sigma(z_1^0) \\ \hat{y}^0 &= a_2^0 \\ \end{aligned} \]

The first steps \(a_0^0 = x^0\), and \(a_0^1 = x^1\) are a bit silly; we just set \(x\) equal to the input layer's \(a\). Same goes for \(\hat{y}\) and \(a\) in the output layer.

\(\hat{y}^0\) and \(x\) are useful when looking at the neural network from the outside. But internally it's nice to stick to the convention of using \(a\) for the activation of neurons because it generalises well into a consistent pattern.

Vectorising

You might have recognised that \(w\) in a certain layer looks a lot like a matrix, and calculating \(z\) from \(a\) and \(w\) looks a lot like a matrix multiplication.

That's because it is :)

Let's take the following two equations:

\[ \begin{aligned} z_0^0 &= a_0^0 \cdot w_0^{0,0} + a_0^1 \cdot w_0^{1,0} \\ z_0^1 &= a_0^0 \cdot w_0^{0,1} + a_0^1 \cdot w_0^{1,1} \end{aligned} \]

We could pack both \(a_0\) values into a \(1 \times 2\) vector:

\[ \vec{a}_0 = \begin{bmatrix} a_0^0 & a_0^1 \end{bmatrix} \]

Same for the \(z_0\) values:

\[ \vec{z}_0 = \begin{bmatrix} z_0^0 & z_0^1 \end{bmatrix} \]

How about the weights \(w_0\)? We can pack them all into a single matrix!

\[ \mathbf{w}_0 = \begin{bmatrix} w_0^{0,0} & w_0^{0,1} \\ w_0^{1,0} & w_0^{1,1} \end{bmatrix} \]

This weight matrix holds all the connections between two layers of neurons. Assume the number of neurons in the left layer is \(m\) and the number of neurons in the right layer is \(n\), then the matrix will be of size \(m \times n\).

And because of this property, the equations collapse down to a single matrix multiply:

\[ \vec{z}_0 = \vec{a}_0 \mathbf{w}_0 \]

We can now get rid of the superscripts, because \(\vec{a}_0\) and \(\vec{z}_0\) hold the values of all neurons in layer 0, and \(\mathbf{w}_0\) is a matrix of all weights at layer 0.

This takes care of calculating the \(z\)'s from \(a\)'s, which are now vectors, so we should start calling them \(\vec{z}\)'s and \(\vec{a}\)'s. What about calculating the next \(\vec{a}\)'s using the activation function sigmoid? This is just an element-wise sigmoid applied to the vector \(\vec{z}\), and we can write it like this:

\[ \vec{a}_1 = \sigma(\vec{z}_0) \]

So with that, we have everything we need to write down the entire forward pass in vectorised form:

\[ \begin{aligned} \vec{a}_0 &= \vec{x} \\ \vec{z}_0 &= \vec{a}_0 \mathbf{w}_0 \\ \vec{a}_1 &= \sigma(\vec{z}_0) \\ \vec{z}_1 &= \vec{a}_1 \mathbf{w}_1 \\ \vec{a_2} &= \sigma(\vec{z}_1) \\ \vec{\hat{y}} &= \vec{a}_2 \\ \end{aligned} \]

What about bias?

If you've been asking this question, good job. I mentioned that bias is important, but so far, we haven't been using it at all in the XOR neural network.

I wanted to wait until we have a concise way to express the forward pass as vector operations first, before adding the concept of bias.

There are multiple ways we can add bias. They are just another parameter of the function; it's like adding the \(b\) to \(f(x) = ax + b\). In a neural network, every neuron needs a bias, so it's adding a \(b\) for every neuron that has an activation function (so every neuron except the input layer neurons).

We could just do this: add this \(b\) bias to our equations. For example, this scalar version:

\[ a_1^0 = \sigma(z_0^0) \]

would become:

\[ a_1^0 = \sigma(z_0^0 + b_0^0) \]

We'd just have a \(b_L^n\) for every layer \(L\) and neuron in that layer \(n\).

In vectorised form this would become another vector \(\vec{b}_L\) per layer that has the same size as \(\vec{z}_L\).

But I want to propose a more elegant solution (in my opinion). We have all our neural network parameters tucked away in the \(\mathbf{w}_L\) matrices so nicely. What if we just add another row to this matrix (which happens to be the exact size we need) that holds the biases?

We can do this by adding a single "imaginary" neuron on the previous layer. So every neuron layer gets a bias neuron, except the output layer, because it doesn't have a set of weights on its right. This neuron will always have the value of \(1\). So the weights connected to this neuron will act like a constant bias added to the input of every neuron on the next layer:

Bias neurons

The two changes we have to make to add bias this way are:

  1. The \(\vec{a}_L\) vectors get an extra \(1\) appended to the end (except the one in the output layer)

  2. The weight matrices all get an extra row and go from \(m \times n\) to \(m + 1 \times n\).

Let's look at \(\vec{a}_0\) and \(\mathbf{w}_0\) for example. Before, \(\vec{a}_0\) looked like this:

\[ \vec{a}_0 = \begin{bmatrix} a_0^0 & a_0^1 \end{bmatrix} \]

After adding bias it looks like this:

\[ \vec{a}_0 = \begin{bmatrix} a_0^0 & a_0^1 & 1 \end{bmatrix} \]

And the weights matrix \(\mathbf{w}_0\) goes from this:

\[ \mathbf{w}_0 = \begin{bmatrix} w_0^{0,0} & w_0^{0,1} \\ w_0^{1,0} & w_0^{1,1} \end{bmatrix} \]

to this:

\[ \mathbf{w}_0 = \begin{bmatrix} w_0^{0,0} & w_0^{0,1} \\ w_0^{1,0} & w_0^{1,1} \\ b_0^{0} & b_0^{1} \end{bmatrix} \]

But the cool thing is that we don't really have to give these bias weights in the last row any special treatment. We will just use them to calculate the \(\vec{z}_0\) vector like before; everything stays as is.

The matrix multiplication \(\vec{z}_0 = \vec{a}_0 \mathbf{w}_0\) just works the same as before, and all our forward pass equations remain the same.

Batches

Imagine a function like \(f(x) = ax + b\). You typically just run one number \(x\) through the function, and look at the output \(y\) which is also one number.

In our XOR example, \(\vec{x}\) is two numbers and \(\vec{y}\) is one number. We've been assuming that we're just calculating one example at a time in our forward pass.

But we've vectorised the whole forward pass and are now using matrix multiplications.

We can use this power to calculate multiple examples with a single matrix multiply!

Before, we assumed that \(\vec{a}_0\) was a \(1 \times 3\) vector (2 neurons + 1 bias neuron). Then the result \(\vec{z}_0\) is also a vector.

The dimensions look like this:

\[ \underset{1 \times 2}{\vec{z}_0} = \underset{1 \times 3}{\vec{a}_0} \, \underset{3 \times 2}{\mathbf{w}_0} \]

If we add an extra dimension (multiple rows) to \(\vec{a}_0\), essentially turning it from a vector into a matrix as well, the matrix multiply still works.

We could run all 4 training examples through the neural network in a single forward pass. The vectors turn into matrices, and the dimensions look like this:

\[ \underset{4 \times 2}{\mathbf{z}_0} = \underset{4 \times 3}{\mathbf{a}_0} \, \underset{3 \times 2}{\mathbf{w}_0} \]

Note that the dimensions of the weights \(\mathbf{w}_0\) can remain the same; the dimensions still work out. The matrix multiply operation just uses the weights multiple times now, once per example.

Applying the activation function sigmoid now happens to a matrix instead of a vector, but it's just the same element-wise operation as before:

\[ \mathbf{a}_1 = \sigma(\mathbf{z}_0) \\ \]

So vectorising didn't just buy us some simpler-looking equations; we can now run multiple training examples through the network in a single forward pass. These are the new equations. They barely change, but all the vectors are now matrices:

\[ \begin{aligned} \mathbf{a}_0 &= \mathbf{x} \\ \mathbf{z}_0 &= \mathbf{a}_0 \mathbf{w}_0 \\ \mathbf{a}_1 &= \sigma(\mathbf{z}_0) \\ \mathbf{z}_1 &= \mathbf{a}_1 \mathbf{w}_1 \\ \mathbf{a_2} &= \sigma(\mathbf{z}_1) \\ \mathbf{\hat{y}} &= \mathbf{a}_2 \\ \end{aligned} \]

Forward pass in C

Now that we have the vectorised forward pass and everything is represented as a matrix, we can try to implement it in C with our own matrix library.

After setting up the matrices with Mat structs, the forward pass is just 5 lines of code:

#include "mat/mat.h"

float sigmoid(float x) {
  return 1.0f / (1.0f + expf(-x));
}

int main(void) {

  // TRAINING DATA
  Mat xs = mat_new(4, 2, (float[]) {
    0, 0,
    0, 1,
    1, 0,
    1, 1,
  });

  Mat ys = mat_new(4, 1, (float[]) {
    0,
    1,
    1,
    0,
  });

  // CREATE MATRICES
  Mat a0 = mat_new(4, 3, (float[4, 3]) {});
  Mat w0 = mat_new(3, 2, (float[3, 2]) {});
  Mat z0 = mat_new(4, 2, (float[4, 2]) {});

  Mat a1 = mat_new(4, 3, (float[4, 3]) {});
  Mat w1 = mat_new(3, 2, (float[3, 2]) {});
  Mat z1 = mat_new(4, 2, (float[4, 2]) {});

  Mat a2 = mat_new(4, 2, (float[4, 2]) {});

  // FORWARD PASS
  mat_cpy(a0, xs);
  mat_mul(z0, a0, w0);
  mat_fun(a1, z0, sigmoid);
  mat_mul(z1, a1, w1);
  mat_fun(a2, z1, sigmoid);

  return 0;
}

Note that the last step, setting \(\vec{\hat{y}}\) equal to \(\vec{a}_2\), is skipped. This is because it's kind of unnecessary, and we'll use matrix a2 here as the network output.

Copying the xs into a0 is useful however, because this allows us to add the bias neurons of 1. A second benefit is that it allows us to use a batch size that's smaller than our entire training set xs.

This creates all the matrices and does the calculations, but we're missing an important part of our neural network (or math function): the parameters!

The parameters are all in the weight matrices w0 and w1. So they are there, but currently they are all zeros.

The usual workflow for a neural network before running the first forward pass is to choose random values for our weights. So let's do that:

...

  // RANDOM INIT WEIGHTS
  mat_gen(w0, rng_norm);
  mat_gen(w1, rng_norm);

...

Also, our bias neurons in a0 and a1 haven't been set to \(1\) yet. Let's do that as well:

...

  // SET BIAS NEURONS
  mat_set(a0, 1.0f);
  mat_set(a1, 1.0f);

...

I'm using a mat_set function here that sets all the elements of a matrix equal to a certain value. We only need the last column of the a matrices to be set to 1.0f but this is just a quick way to get it done. And in the forward pass, the rest of a0 and a1 will be overwritten so it doesn't matter that it starts off as a matrix full of ones.

At the end, it could be useful to print the final output of the neural network. We have a mat_print in our toolbox so let's use that:

...

  // SHOW THE RESULT
  mat_print(a2);

...

That's about all we need for a first run of our forward pass. The full code looks like this now:

#include "mat/mat.h"

float sigmoid(float x) {
  return 1.0f / (1.0f + expf(-x));
}

int main(void) {

  // TRAINING DATA
  Mat xs = mat_new(4, 2, (float[]) {
    0, 0,
    0, 1,
    1, 0,
    1, 1,
  });

  Mat ys = mat_new(4, 1, (float[]) {
    0,
    1,
    1,
    0,
  });

  // CREATE MATRICES
  Mat a0 = mat_new(4, 3, (float[4 * 3]) {0});
  Mat w0 = mat_new(3, 2, (float[3 * 2]) {0});
  Mat z0 = mat_new(4, 2, (float[4 * 2]) {0});

  Mat a1 = mat_new(4, 3, (float[4 * 3]) {0});
  Mat w1 = mat_new(3, 1, (float[3 * 1]) {0});
  Mat z1 = mat_new(4, 1, (float[4 * 1]) {0});

  Mat a2 = mat_new(4, 1, (float[4 * 1]) {0});

  // RANDOM INIT WEIGHTS
  mat_gen(w0, rng_norm);
  mat_gen(w1, rng_norm);

  // SET BIAS NEURONS
  mat_set(a0, 1.0f);
  mat_set(a1, 1.0f);

  // FORWARD PASS
  mat_cpy(a0, xs);
  mat_mul(z0, a0, w0);
  mat_fun(a1, z0, sigmoid);
  mat_mul(z1, a1, w1);
  mat_fun(a2, z1, sigmoid);

  // SHOW THE RESULT
  mat_print(a2);

  return 0;
}

When we compile and run, this is what we get:

   0.75
   0.71
   0.75
   0.71

Nowhere near the actual target:

  Mat ys = mat_new(4, 1, (float[]) {
    0,
    1,
    1,
    0,
  });

But remember, the weights are literally random numbers here. So now, we need a way to tune these weights into something that makes the network perform well. How? Stay tuned for the next part :)