Create a Neural Network with Tensorflow.JS

Build your own Neural Network with Tensorflow.js and node.js! Step by Step.

The neural network consists of an input layer with two nodes, a hidden layer with four nodes and an output layer with three nodes.

 

Install Tensorflow.js with npm

npm install @tensorflow/tfjs

Create a JavaScript-File

touch tensorLayerAPI.js

 How to build a neural network with Tensorflow.js

Build the Model

Step 1

Require tensorflow and initialize the model

var tf = require("@tensorflow/tfjs");
const model = tf.sequential();

Step 2

Create a HiddenLayer

const hidden = tf.layers.dense({
    units: 4,           // Number of nodes in the hidden Layer
    inputShape: [2],    // Input Layer with 2 nodes
    activation: "sigmoid"
});

Step 3

Add a HiddenLayer to Model

model.add(hidden);

Step 4

Create a OutputLayer

const output = tf.layers.dense({
    units: 3,
    activation: "sigmoid"
});

Step 5

Add OutputLayer to Model

model.add(output);

Step 6

Generates the module

model.compile({
    optimizer: tf.train.sgd(0.1),
    loss: tf.losses.cosineDistance
});

Now we have built a model and we can test it with test data. 

Train and Test the Model

Input data for the Input layer !

const xs = tf.tensor2d([
    [0.1, 0.1],
    [0.9, 0.9],
    [0.5, 0.5]
]);

Output data

const ys = tf.tensor2d([
    [0.9, 0.9, 0.9],
    [0.1, 0.1, 0.1],
    [0.5, 0.5, 0.5]
]);

Train the model

train().then(function () {
    console.log("training complete");
    let outputPredict = model.predict(xs);
    outputPredict.print();
});

 

The train function

async function train() {
    for (var i = 0; i < 1000; i++) {
        const response = await model.fit(xs, ys, {
            shuffle: true,
            epochs: 20
        });
        // see the lostfunktion
        console.log(response.history.loss[0]);
    }
}

 

Start the script

$ node tensorLayerAPI.js

 The result should look like this in the end ;)

document is not defined
training complete
Tensor
    [[0.8993989, 0.9028315, 0.9050405],
     [0.1067901, 0.1081404, 0.1082372],
     [0.4984535, 0.4966488, 0.4958749]]

 

The numbers should be similar to the numbers from the OutputLayer (ys). The smaller the difference, the better the model.

 

Andrej Schefer 2018-06-03

On github

https://github.com/AndrejSchefer/Create-a-Neural-Network-with-Tensorflow.JS