TensorFlow JS a Hello World!


Hello Everyone,

I hope you all are safe and doing well. Today we will have a look at TensorFlow js basic example. So let’s dive into this.

In this example, we will take the x value from the user and get the y value as an output. The calculation will be when x is 1 y is 2, when x is 2 y is 4 when x is 3 y is 5, and so on… So you may get the idea that it will simply add 2 in the x value.

First, we will include TensorFlow js CDN in script-src.

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.11.2"></script>

Now we need to get get the input from the user so we will add an input box in our code.

<input type="number" id="x_val" placeholder="Enter X value">

After getting the value we need to get the value, so we will add a button to get the y value which will call the function, and in that, we will add our TensorFlow js code to train the model and predict the value.

<button type="button" onclick="GetYVal();">Get Y value</button>

Now the script,

<script>
    async function GetYVal(){
        let x_val = document.getElementById('x_val').value;
        const model = tf.sequential();

        model.add(tf.layers.dense({units: 1, inputShape: [1]}));

        model.compile({
            loss: 'meanSquaredError',
            optimizer: 'sgd'
        });

        const xs = tf.tensor2d([1, 2, 3, 4, 5, 6], [6, 1]);
        const ys = tf.tensor2d([3, 4, 5, 6, 7, 8], [6, 1]);

        await model.fit(xs, ys, {epochs: 500});

        document.getElementById('output').innerText = model.predict(tf.tensor2d([x_val], [1, 1]));
    }
</script>

And finally, the p tag where we will display y value,

<p>Y is </p> &nbsp; &nbsp;<p id="output"> </p>

You can also checkout my GitHub repo for this example.

Thank you for reading 🙂

Happy coding 🙂

Comments are closed.

Create a website or blog at WordPress.com

Up ↑

Design a site like this with WordPress.com
Get started