A Feed Forward Neural Network, in the following simply referred to as ANN, is the most basic form of an Artificial Neural Network, which propagates values through layers of neurons and is being trained by propagating an error value back through the network using a method called back-propagation.


You can access the ANN using tf.FeedForwardNeuralNetwork. To create a new ANN, you have to specify these specific options:

Most of the times, you have to experiment a lot to find the right parameters for the network.

Now, we can create a new instance of an ANN with the following code snippet:

let ann = new tf.FeedForwardNeuralNetwork({
    layers: [2, 3, 1],
    learningRate: 1,
    momentum: 0,
    activationFunction: tf.Activations.SIGMOID,
    errorFunction: tf.Errors.CROSS_ENTROPY,
});

Train it with the method ann.fit(input: number[], targetValues: number[]) and calculate the error with ann.error(input: number[], targetValues: number[]).

// Train network on XOR
let data = [
    {
        input: [0, 0],
        output: [0]
    },
    {
        input: [1, 0],
        output: [1]
    },
    {
        input: [0, 1],
        output: [1]
    },
    {
        input: [1, 1],
        output: [0]
    },
];

// Simple training with fixed training iterations which may not work at every execution but is enough for simple testing purposes.
for(let i = 0; i < 1000; i++){
    for(let example of data){
        ann.fit(example.input, example.output);
        // Log current error
        console.log(ann.error(example.input, example.output));
    }
}

To predict outputs for new inputs, use the method ann.predict(input: number[])

// Get network's prediction for training XOR data
for(let example of data){
    let prediction = ann.predict(example.input);
    console.log(`Input: ${example.input}, network output: ${prediction}, expected: ${example.output}`)
}

Please note that we were using ES6 standards in the examples given above. To use the code provided you need to bundle and transpile it.