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:
Assuming that x and y are single numbers (scalars), the function describes a straight line:
The parameter a can be used to adjust the slope of the line. We can turn it into a mini neural network like this:
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:
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:
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:
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:
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:
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:
The formula is:
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:
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:
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:
| x1 | x2 | 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 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:
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) 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:
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 aL shows which layer index we're on. The superscript n for an and zn 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:
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 wi,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 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 a0 's to the value of x .
From there, the a0 's are multiplied by every connection's weights w0 , and at z0 we take the sum of all these a⋅w products. For the first sum z00 this looks like:
And the calculation:
Related posts
Building Medication Quality Intelligence into Healthcare AI
Why an email agency is a better client than a Shopify store
streamft 1.0.5: serve adapters with the alpha they were trained with
법학 시험에서 가장 어려운 518문항: LEXam-hard 리더보드 1위 Darwin-180B-RSI 45.72점을 API로 직접 확인하는 법











