Building a Neural Network from First Principles in C++

How does a neural network learn? I wanted to gain a practical understanding of some of the fundamental principles of machine learning by implementing artificial neural networks, rather than simply use an existing library or call an AI service.

I developed four C++ programs, starting with a single artificial neuron and progressing to a network with a hidden layer capable of learning the logical XOR function. No machine-learning libraries are used.

The source code and instructions for compiling and running the programs are in the GitHub repository:
GitHub Repo
GitHub Repository

1. A Single Artificial Neuron

The first program, nn_neuron.cpp, demonstrates how a neuron learns from a training example. The example provides two inputs (x1 and x2) and a target (t), which is the correct output. The neuron has three trainable parameters: two weights (w1 and w2) and a bias (b). The weights determine the contribution of each input, and the bias shifts the weighted sum even when both inputs are zero.

Training consists of three stages: forward propagation (calculate the prediction and loss), backpropagation (calculate how the loss responds to changes in each parameter), and gradient descent (adjust the parameters). We will follow one complete training iteration using these initial values. Numerical results below are rounded for readability; calculations in the program use unrounded intermediate values:

x1 = 1       x2 = 0       t = 1
w1 = 0.8     w2 = -0.4    b = -0.1
learning rate = 0.1

Forward propagation

Step 1: Calculate the weighted sum (z). Multiply each input by its corresponding weight and add the bias. The second input is zero, so its weight contributes nothing to this particular prediction.

z = x1 * w1 + x2 * w2 + b
  = 1 * 0.8 + 0 * (-0.4) - 0.1
  = 0.7

Step 2: Calculate the prediction (p). The weighted sum can be any real number. The sigmoid activation function converts it to a value between 0 and 1. The function exp(-z) means e raised to the power -z, where e is approximately 2.71828. In C++ this is calculated using std::exp(). A weighted sum of zero gives a prediction of 0.5; positive sums give predictions above 0.5 and negative sums give predictions below 0.5.

p = 1 / (1 + exp(-z))
  = 1 / (1 + exp(-0.7))
  = 0.668188

Step 3: Calculate the loss (L). Compare the prediction with the target. Squaring the difference makes the loss non-negative regardless of whether the prediction is too high or too low. The closer the prediction is to the target, the smaller the loss.

L = (t - p)^2
  = (1 - 0.668188)^2
  = 0.110099

The neuron has produced a prediction and measured its error, but none of the parameters has changed yet. The next stage determines how to change them.

Backpropagation

A derivative is a rate of change. For example, dL/dp tells us approximately how much the loss would change for a small increase in the prediction. A positive derivative means increasing the prediction increases the loss locally; a negative derivative means increasing the prediction decreases the loss. The derivatives below are evaluated at the current inputs and parameters.

Step 4: Calculate the loss slope (dL/dp). Differentiating the squared error function with respect to p gives twice the difference between the prediction and the target. The negative result tells us that the prediction is too low and increasing it would reduce the loss.

dL/dp = 2 * (p - t)
      = 2 * (0.668188 - 1)
      = -0.663624

Step 5: Calculate the prediction slope (dp/dz). The prediction depends on the weighted sum through the sigmoid function. Its derivative can be expressed using the prediction already calculated in Step 2, without calculating the exponential again. The result tells us how sensitive the prediction is to a small change in z.

dp/dz = p * (1 - p)
      = 0.668188 * (1 - 0.668188)
      = 0.221713

Step 6: Calculate the weighted sum slope (dL/dz). Changing z changes p, which in turn changes L. The chain rule combines these two rates of change by multiplication: the change in loss per unit change in prediction, multiplied by the change in prediction per unit change in weighted sum. The negative result means increasing z would reduce the loss locally.

dL/dz = (dL/dp) * (dp/dz)
      = -0.663624 * 0.221713
      = -0.147134

Step 7: Calculate the parameter gradients. We now know how the weighted sum affects the loss, but we need to know how each weight and bias affects it. From Step 1, increasing w1 by a small amount changes z by that amount multiplied by x1. The same applies to w2 and x2. Increasing the bias changes z by exactly the same amount, so its derivative is 1. Applying the chain rule again gives:

dL/dw1 = (dL/dz) * x1 = -0.147134 * 1 = -0.147134
dL/dw2 = (dL/dz) * x2 = -0.147134 * 0 =  0
dL/db  = (dL/dz) * 1  = -0.147134

These three gradients tell us the local effect of changing each parameter on the loss. Weight 2 has a zero gradient because x2 is zero. Notice that the numerical loss calculated in Step 3 is not used directly to calculate the parameter updates; the gradients are calculated from the prediction, target, inputs and derivatives.

Gradient descent

Step 8: Update the parameters. The gradient points in the direction of increasing loss, so we subtract the gradient multiplied by the learning rate to move in the opposite direction. The learning rate controls the size of the adjustment. A negative gradient therefore causes an increase in the parameter, and a positive gradient causes a decrease. All gradients are calculated before updating any parameter.

new parameter = old parameter - learning_rate * gradient

w1 =  0.8 - (0.1 * -0.147134) =  0.814713
w2 = -0.4 - (0.1 *  0)        = -0.4
b  = -0.1 - (0.1 * -0.147134) = -0.085287

In the C++ implementation, np holds the current neuron parameters and ng holds the gradients calculated in Step 7:

np.weight_1 -= learning_rate * ng.weight_1;
np.weight_2 -= learning_rate * ng.weight_2;
np.bias     -= learning_rate * ng.bias;

One training iteration is complete. To see whether the update has improved the prediction, perform the forward calculations again using the updated parameters:

z = x1 * w1 + x2 * w2 + b           = 0.729427
p = 1 / (1 + exp(-z))                 = 0.674679
L = (1 - p)^2                        = 0.105833

The prediction is now closer to 1 and the loss is lower. Performing ten training iterations in total with the same training example produces these results:

$ ./nn_neuron

                         Initial       Final
Prediction               0.668188      0.722971
Loss                     0.110099      0.0767452

Weight 2 remains unchanged throughout because its input is always zero. Gradient descent aims to reduce loss, although an excessively large learning rate can overshoot a minimum.

2. Learning Logical OR

The next program, nn_or.cpp, trains a single neuron using the four possible combinations of two binary inputs. The expected output is 1 if either or both inputs are 1. An epoch is one complete pass through the training dataset. The same eight steps are applied to each example, using its own inputs and target and the parameters left by the previous example. The weights and bias are updated after each training example, a technique known as stochastic gradient descent. In these demonstrations the examples are processed in a fixed order. Four updates are made per epoch, so 1,000 epochs means 4,000 updates.

Using the same initial weights and bias as before, the program produces these final predictions after 1,000 epochs (output extract):

$ ./nn_or 1000

PREDICTIONS:
[0, 0] target 0 -> 0.136448
[0, 1] target 1 -> 0.916753
[1, 0] target 1 -> 0.917035
[1, 1] target 1 -> 0.998704

These are continuous sigmoid predictions, not exact binary outputs. To convert them into classes, use a threshold of 0.5: predictions below 0.5 represent 0 and predictions at or above 0.5 represent 1. For example, 0.136448 is classified as 0, whereas 0.916753 is classified as 1. All four classifications match their targets.

3. Attempting to Learn Logical XOR

In the third program, nn_xor.cpp, the training dataset is changed to XOR (exclusive OR). The target is 1 when exactly one input is 1, and 0 otherwise. The architecture and training algorithm remain the same.

Final predictions (output extract):

$ ./nn_xor 1000

PREDICTIONS:
[0, 0] target 0 -> 0.506302
[0, 1] target 1 -> 0.499995
[1, 0] target 1 -> 0.493669
[1, 1] target 0 -> 0.487363

With the same 0.5 threshold, only the final example is classified correctly. For example, the prediction 0.499995 is below 0.5, although its target is 1. Why does the neuron fail to learn XOR?

From Step 2, the sigmoid prediction is exactly 0.5 when z is zero. Therefore the boundary between the classes is where the weighted sum is zero:

w1 * x1 + w2 * x2 + b = 0

For two inputs this describes a straight line (when at least one weight is non-zero). Changing the weights changes the line's orientation; changing the bias moves it. The OR inputs can be separated into their target classes by a single straight line, as shown on the left below. For XOR, the two examples of each class occupy opposite corners, so no straight line can separate them. This is a limitation of the architecture, not a problem that can be resolved by increasing the number of epochs.

Logical OR The zero at the origin can be separated from the three ones by a straight line. 111 0 101x1x2

OR: linearly separable

Logical XOR The zeros and ones occupy opposite corners of a square, so no single straight line separates them. 11 00 101x1x2

XOR: not linearly separable

4. Learning XOR Using a Hidden Layer

The final program, nn_hidden_xor.cpp, introduces two hidden neurons. Both receive the original inputs, and their predictions are passed as inputs to the output neuron. Each of the three neurons has two weights and a bias, giving a total of nine trainable parameters.

Neural network with a hidden layer Each of two inputs connects to both hidden neurons. Both hidden predictions connect to a single output neuron. Each neuron has two trainable weights and a bias. x1x2h1h2p InputsHidden layerOutput2 neurons1 neuron

The following initial parameters were used for a training run of 5,000 epochs, with a learning rate of 0.1:

NeuronWeight 1Weight 2Bias
Hidden 10.8-0.4-0.1
Hidden 2-0.30.60.2
Output0.7-0.50.1

We will work through the first training example, x1 = 0, x2 = 0, target = 0, using the initial parameters above. The same weighted sum and sigmoid functions from Section 1 are used for each neuron.

Forward propagation through the network

Step 1: Calculate both hidden predictions. Each hidden neuron receives the original inputs but has its own weights and bias. We use z1 and z2 for their weighted sums and h1 and h2 for their predictions.

z1 = 0 * 0.8 + 0 * (-0.4) - 0.1 = -0.1
h1 = 1 / (1 + exp(-z1))           = 0.475021

z2 = 0 * (-0.3) + 0 * 0.6 + 0.2 = 0.2
h2 = 1 / (1 + exp(-z2))           = 0.549834

Step 2: Calculate the output prediction. The hidden predictions now become the inputs to the output neuron. We call its weights wo1 and wo2, its bias bo, and its weighted sum zo. The calculation is exactly the same as before, but uses h1 and h2 instead of the original x1 and x2.

zo = h1 * wo1 + h2 * wo2 + bo
   = 0.475021 * 0.7 + 0.549834 * (-0.5) + 0.1
   = 0.157598
p  = 1 / (1 + exp(-zo)) = 0.539318

Step 3: Calculate the network loss. Compare only the final prediction with the target. The hidden neurons do not have their own targets: their purpose is to produce intermediate values that help the output neuron predict correctly.

L = (t - p)^2 = (0 - 0.539318)^2 = 0.290864

Backpropagation through the network

Step 4: Calculate the output neuron's slopes. Start at the output because this is where the loss is measured. Apply the three derivative calculations from Section 1 to its prediction and weighted sum. The positive weighted sum slope tells us that increasing zo would increase the loss locally.

dL/dp  = 2 * (p - t) = 2 * (0.539318 - 0) = 1.078636
dp/dzo = p * (1 - p)                     = 0.248454
dL/dzo = (dL/dp) * (dp/dzo)              = 0.267992

Step 5: Calculate the output parameter gradients. Multiply the weighted sum slope by the actual input to each output weight (h1 or h2). The bias gradient equals the weighted sum slope.

dL/dwo1 = 0.267992 * 0.475021 = 0.127302
dL/dwo2 = 0.267992 * 0.549834 = 0.147351
dL/dbo  = 0.267992

Step 6: Propagate the loss backwards to the hidden neurons. We cannot calculate their loss slopes from individual targets, because no such targets exist. Instead, use the effect of each hidden prediction on zo. The formula for zo in Step 2 tells us that a change in h1 changes zo in proportion to wo1, and a change in h2 changes zo in proportion to wo2. Multiply these weights by the output weighted sum slope from Step 4:

dL/dh1 = (dL/dzo) * wo1 = 0.267992 *  0.7 =  0.187594
dL/dh2 = (dL/dzo) * wo2 = 0.267992 * -0.5 = -0.133996

The two slopes have opposite signs because the output weights have opposite signs. Increasing h1 would increase the final loss locally, whereas increasing h2 would reduce it. This is how the output error provides a learning signal to neurons that have no individual targets. In the C++ implementation, the first of these calculations is:

double hidden_1_loss_slope =
    net_results.output.weighted_sum_slope *
    net_params.output.weight_1;

Step 7: Calculate the hidden weighted sum slopes. Each hidden prediction depends on its own weighted sum through the sigmoid. Use the same sigmoid derivative and chain rule as in Section 1, multiplying the loss slopes from Step 6 by the respective prediction slopes.

Hidden neuron 1:
dh1/dz1 = h1 * (1 - h1)              =  0.249376
dL/dz1  = (dL/dh1) * (dh1/dz1)       =  0.0467815

Hidden neuron 2:
dh2/dz2 = h2 * (1 - h2)              =  0.247517
dL/dz2  = (dL/dh2) * (dh2/dz2)       = -0.0331662

Step 8: Calculate the hidden parameter gradients. The original inputs, rather than the hidden predictions, are the inputs to these two neurons. Multiply each hidden weighted sum slope by x1 and x2 to obtain its two weight gradients. Its bias gradient is simply its weighted sum slope.

Hidden neuron 1:
 weight 1 gradient =  0.0467815 * 0 = 0
 weight 2 gradient =  0.0467815 * 0 = 0
 bias gradient     =  0.0467815

Hidden neuron 2:
 weight 1 gradient = -0.0331662 * 0 = 0
 weight 2 gradient = -0.0331662 * 0 = 0
 bias gradient     = -0.0331662

All nine gradients are now available. No parameters have been changed yet: every gradient must be calculated using the same weights and biases that produced the forward prediction. Otherwise the gradients would refer to different versions of the network.

Gradient descent and repeated training

Step 9: Update all nine parameters. Apply the same update rule as in Section 1. For example, the first output weight becomes 0.7 - (0.1 * 0.127302) = 0.687270. The complete set of updated values is:

NeuronWeight 1Weight 2Bias
Hidden 10.8-0.4-0.104678
Hidden 2-0.30.60.203317
Output0.687270-0.5147350.0732008

The hidden weights do not change for this example because both original inputs are zero. The hidden biases change, and both output weights change because their inputs (h1 and h2) are non-zero. When the next example is processed, the network uses these updated parameters. Other examples with non-zero original inputs can also change the hidden weights.

The existing functions for calculating a neuron's weighted sum, prediction, derivatives and gradients were refactored so that they could be reused for each neuron. Only the network-level functions need to know how the neurons are connected.

After processing all four XOR examples, calculate the average loss for the epoch by adding the four losses measured before their respective parameter updates and dividing by four. This gives a single measure of training progress. For example, the first epoch of the program produces these four losses:

Average loss = (0.290864 + 0.255935 + 0.175392 + 0.309428) / 4
             = 0.257905

After 5,000 epochs the network has performed 20,000 updates, each to the nine trainable parameters.

Selected lines from the training output and final evaluation:

$ ./nn_hidden_xor 5000

TRAINING EPOCH 1 of 5000 Average Loss = 0.257905
...
TRAINING EPOCH 5000 of 5000 Average Loss = 0.00406541

FINAL EVALUATION

PREDICTIONS:
[0, 0] target 0 -> 0.0704146
[0, 1] target 1 -> 0.936063
[1, 0] target 1 -> 0.942592
[1, 1] target 0 -> 0.0623882

The network now correctly classifies all four XOR examples. The average loss encountered during training has decreased considerably, from 0.257905 to 0.00406541. The epoch average is calculated from the loss for each example before its parameter update, not from a separate evaluation using fixed final parameters. The final evaluation uses the trained parameters without updating them. These are the original training examples, not a test of generalisation to unseen data. To examine the intermediate calculations, run ./nn_hidden_xor 1 -v with the same initial parameters.

Examining the final weights and biases reveals something interesting. The final trained parameters are shown below:

Neuron       Weight 1    Weight 2    Bias
Hidden 1      5.64875    -5.64032    -3.31192
Hidden 2     -4.69398     4.39934    -2.45078
Output        6.75472     6.91133    -3.3665

To understand what the network has learned, apply the forward calculations again using these trained parameters. For example, with inputs (1, 0), the first hidden neuron's weighted sum is 5.64875 - 3.31192 = 2.33683, giving a sigmoid prediction of approximately 0.911882. The second hidden neuron has a negative weighted sum and produces a prediction close to zero. Applying the same calculation to all four input combinations gives these approximate hidden predictions:

Inputs      Hidden 1     Hidden 2
[0, 0]      0.035165     0.079382
[0, 1]      0.000129     0.875290
[1, 0]      0.911882     0.000788
[1, 1]      0.035452     0.060346

Using 0.5 as a threshold to interpret these intermediate values, hidden neuron 1 behaves like x1 AND NOT x2, and hidden neuron 2 like x2 AND NOT x1. The output neuron combines their continuous predictions with its own weights and bias, behaving approximately like OR. The network does not actually round the hidden predictions before passing them to the output neuron. This decomposition of XOR was not explicitly programmed into the network; it emerged through training.

Initialising the Weights and Biases

During development I questioned why the program asks for nine initial parameter values when it might be possible to enter three values and use them for all the neurons. Even if the two hidden neurons start with identical parameters, different output weights can give them different gradients, allowing them to learn different functions.

If the hidden neurons start with identical parameters and the two output weights are also identical, their gradients remain identical in this network. The hidden neurons then learn the same function rather than different features. Using different initial parameters helps break this symmetry. Successful convergence is not guaranteed for every initialisation.



C++ Source Code

For the complete source code and reproducible examples, see the AI GitHub repository.