Below is an example of a more advanced C program that "trains" a simple neural network—a basic two-layer (input–hidden–output) feedforward network—to learn the XOR function. In one way, you could say that it “learns” or memorizes patterns that resemble a very small slice of human knowledge. (Of course, real human knowledge is vastly more complex, but this example shows how a system can learn from data.)
This example uses:
- A 2–2–1 architecture (2 inputs, 2 hidden neurons, and 1 output).
- The sigmoid activation function for non-linearity.
- A simple backpropagation training loop over many epochs.
Compile and run this code using a C compiler such as gcc (e.g. gcc simple_nn_train.c -o simple_nn_train -lm && ./simple_nn_train).
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
// Sigmoid activation function.
double sigmoid(double x) {
return 1.0 / (1.0 + exp(-x));
}
// Derivative of the sigmoid function.
// Note that when using backpropagation, we typically apply the derivative
// to the output of the sigmoid function already computed.
double sigmoid_derivative(double output) {
return output * (1.0 - output);
}
int main() {
// Seed the random number generator for weight initialization.
srand(time(NULL));
// XOR input and output data.
double inputs[4][2] = {
{0.0, 0.0},
{0.0, 1.0},
{1.0, 0.0},
{1.0, 1.0}
};
double expected_outputs[4] = {0.0, 1.0, 1.0, 0.0};
// Define the network architecture:
// 2 input neurons, 2 hidden neurons, and 1 output neuron.
int input_nodes = 2;
int hidden_nodes = 2;
int output_nodes = 1;
// Initialize weights and biases with random values between -1 and 1.
// Weights for connections from input to hidden layer.
double weight_ih[2][2]; // 2 inputs x 2 hidden neurons
// Weights for connections from hidden to output layer.
double weight_ho[2]; // 2 hidden neurons x 1 output neuron
// Biases for hidden neurons.
double bias_h[2];
// Bias for output neuron.
double bias_o;
// Randomly initialize the weights for input-to-hidden and hidden biases.
for (int i = 0; i < hidden_nodes; i++) {
bias_h[i] = ((double)rand() / RAND_MAX) * 2 - 1;
for (int j = 0; j < input_nodes; j++) {
weight_ih[j][i] = ((double)rand() / RAND_MAX) * 2 - 1;
}
}
// Randomly initialize the weights for hidden-to-output and its bias.
bias_o = ((double)rand() / RAND_MAX) * 2 - 1;
for (int i = 0; i < hidden_nodes; i++) {
weight_ho[i] = ((double)rand() / RAND_MAX) * 2 - 1;
}
// Training parameters.
double learning_rate = 0.5;
int epochs = 10000;
// Training loop.
for (int epoch = 0; epoch < epochs; epoch++) {
double total_error = 0.0;
// Process each training example.
for (int i = 0; i < 4; i++) {
// Forward propagation
double hidden[2];
// Calculate activations for the hidden layer.
for (int j = 0; j < hidden_nodes; j++) {
double activation = bias_h[j];
for (int k = 0; k < input_nodes; k++) {
activation += inputs[i][k] * weight_ih[k][j];
}
hidden[j] = sigmoid(activation);
}
// Calculate activation for the output neuron.
double output_activation = bias_o;
for (int j = 0; j < hidden_nodes; j++) {
output_activation += hidden[j] * weight_ho[j];
}
double predicted = sigmoid(output_activation);
// Calculate error (difference between expected and predicted).
double error = expected_outputs[i] - predicted;
total_error += error * error;
// Backpropagation
// Compute delta for the output neuron.
double delta_output = error * sigmoid_derivative(predicted);
// Compute deltas for the hidden neurons.
double delta_hidden[2];
for (int j = 0; j < hidden_nodes; j++) {
delta_hidden[j] = weight_ho[j] * delta_output * sigmoid_derivative(hidden[j]);
}
// Update weights for hidden-to-output connections.
for (int j = 0; j < hidden_nodes; j++) {
weight_ho[j] += learning_rate * delta_output * hidden[j];
}
bias_o += learning_rate * delta_output;
// Update weights for input-to-hidden connections.
for (int j = 0; j < hidden_nodes; j++) {
for (int k = 0; k < input_nodes; k++) {
weight_ih[k][j] += learning_rate * delta_hidden[j] * inputs[i][k];
}
bias_h[j] += learning_rate * delta_hidden[j];
}
}
// Print the error every 1000 epochs.
if (epoch % 1000 == 0) {
printf("Epoch %d, Total Error: %.4f\n", epoch, total_error);
}
}
// Testing the trained network on the XOR problem.
printf("\n--- Trained Neural Network Results for XOR ---\n");
for (int i = 0; i < 4; i++) {
double hidden[2];
// Forward pass to compute hidden layer activations.
for (int j = 0; j < hidden_nodes; j++) {
double activation = bias_h[j];
for (int k = 0; k < input_nodes; k++) {
activation += inputs[i][k] * weight_ih[k][j];
}
hidden[j] = sigmoid(activation);
}
// Compute the network's output.
double output_activation = bias_o;
for (int j = 0; j < hidden_nodes; j++) {
output_activation += hidden[j] * weight_ho[j];
}
double predicted = sigmoid(output_activation);
printf("Input: %.1f %.1f | Expected: %.1f | Predicted: %.4f\n",
inputs[i][0], inputs[i][1], expected_outputs[i], predicted);
}
return 0;
}
How the Code Works
-
Network Setup
- The network has 2 input neurons, 2 neurons in one hidden layer, and 1 output neuron.
- Weights and biases are initialized to random numbers between -1 and 1.
-
Forward Propagation
- For each input (each row of the XOR dataset), the code calculates the activation of the hidden layer neurons using the sigmoid function.
- Then it computes the output by combining the hidden layer outputs (again using the sigmoid function).
-
Backpropagation and Learning
- The error (difference between expected and predicted values) is calculated.
- The network computes the output layer’s delta (error adjustment) and then propagates this error back to the hidden layer.
- Weights for both layers, as well as biases, are updated based on the learning rate.
-
Training Loop and Output
- The network is trained for 10,000 epochs.
- Every 1000 epochs, the total error over all training inputs is printed.
- Finally, the trained network is used to predict the XOR outputs, which are printed alongside the expected values.
This program demonstrates a basic "training" routine in C—training a model to recognize the XOR pattern. Although this is a simple example, it illustrates the foundational ideas behind learning from data, which is a first step toward building systems that can capture aspects of human knowledge.
Feel free to modify the architecture, training parameters, or data to experiment with more complex behaviors.