Implementing a simple neural network from scratch to solve the XOR problem in JavaScript can be a bit complex due to the need to understand neural network principles, but I'll try to keep it as simple and clear as possible.
We're going to create a small neural network with one hidden layer that can solve the XOR problem. We'll use the sigmoid activation function for our neurons and a simple gradient descent for training.
// Activation function: Sigmoid
function sigmoid(x, deriv = false) {
if (deriv) {
// Derivative of the sigmoid
return x * (1 - x);
}
return 1 / (1 + Math.exp(-x));
}
// Initialize weights randomly with mean 0
let inputLayerSize = 2;
let hiddenLayerSize = 4;
let outputLayerSize = 1;
let inputHiddenWeights = Array.from({length: hiddenLayerSize}, () =>
Array.from({length: inputLayerSize}, () => 2 * Math.random() - 1));
let hiddenOutputWeights = Array.from({length: outputLayerSize}, () =>
Array.from({length: hiddenLayerSize}, () => 2 * Math.random() - 1));
// XOR input and output data
let trainingData = [
{input: [0, 0], output: [0]},
{input: [0, 1], output: [1]},
{input: [1, 0], output: [1]},
{input: [1, 1], output: [0]}
];
// Training function
function train(epochs, learningRate) {
for (let i = 0; i < epochs; i++) {
trainingData.forEach(data => {
// Forward propagation
let inputLayer = [...data.input];
let hiddenLayer = inputHiddenWeights.map(weights =>
sigmoid(weights.reduce((sum, weight, index) => sum + weight * inputLayer[index], 0)));
let outputLayer = hiddenOutputWeights.map(weights =>
sigmoid(weights.reduce((sum, weight, index) => sum + weight * hiddenLayer[index], 0)));
// Calculate the error for the output layer (difference between desired output and predicted output)
let outputError = data.output.map((value, index) => value - outputLayer[index]);
// Backpropagation
// Calculate how much the output layer should change
let outputDelta = outputError.map((error, index) => error * sigmoid(outputLayer[index], true));
// Calculate the error for the hidden layer (by looking at output layer changes)
let hiddenError = hiddenOutputWeights.map((weights, index) =>
outputDelta.reduce((sum, delta, deltaIndex) => sum + delta * weights[deltaIndex], 0));
// Calculate how much the hidden layer should change
let hiddenDelta = hiddenError.map((error, index) => error * sigmoid(hiddenLayer[index], true));
// Apply changes to weights (Gradient Descent)
hiddenOutputWeights = hiddenOutputWeights.map((weights, index) =>
weights.map((weight, weightIndex) =>
weight + learningRate * outputDelta[index] * hiddenLayer[weightIndex]));
inputHiddenWeights = inputHiddenWeights.map((weights, index) =>
weights.map((weight, weightIndex) =>
weight + learningRate * hiddenDelta[index] * inputLayer[weightIndex]));
});
}
}
// Training the network
train(10000, 0.1);
// Predict function
function predict(input) {
let hiddenLayer = inputHiddenWeights.map(weights =>
sigmoid(weights.reduce((sum, weight, index) => sum + weight * input[index], 0)));
let outputLayer = hiddenOutputWeights.map(weights =>
sigmoid(weights.reduce((sum, weight, index) => sum + weight * hiddenLayer[index], 0)));
return outputLayer;
}
// Test the network
console.log("XOR predictions:");
console.log(`0 XOR 0: ${predict([0, 0])}`);
console.log(`0 XOR 1: ${predict([0, 1])}`);
console.log(`1 XOR 0: ${predict([1, 0])}`);
console.log(`1 XOR 1: ${predict([1, 1])}`);
This code defines a simple two-layer perceptron (1 input layer, 1 hidden layer, and 1 output layer). We initialize the network with random weights and define a training function that implements the forward and backward propagation for the XOR problem. We then train the network for 10000 epochs with a learning rate of 0.1. Finally, we test the network with the predict function and log the XOR outputs.
Keep in mind that this is a very basic implementation for educational purposes. In real-world applications, you'd likely use libraries like TensorFlow.js, which provide optimized functions and structures for building and training neural networks.