TensorFlow.js

  • Last Updated : 16 Jan, 2022

TensorFlow.js is a JavaScript library for training and deploying machine learning models on web applications and in Node.js. You can develop the machine learning models from scratch using tensorflow.js or can use the APIs provided to train your existing models in the browser or on your Node.js server.

TensorFlow.js Tutorial

Why TenserFlow.js?

TensorFlow has a lot of machine learning libraries and is well-documented. It provides a few key functions and ways for doing so. TensorFlow is sometimes referred to as a “Google” product. A wide range of machine learning and deep learning algorithms are included. For handwritten digit classification, image recognition, word embedding, and the generation of other sequence models, TensorFlow can train and run deep neural networks.

Installing TenserFlow.js: There are following two methods by which we can install and use TenserFlow.js.

 

Method 1: We can use CDN link to run Tensorflow.js code without installing it.  Add the following CDN link into the script tag to the head section of the HTML file.

<script src=”https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js”></script>

Method 2: We can install it using npm. Before installing TensorFlow.js through npm, first, make sure you have installed Node.js and npm.

npm install @tensorflow/tfjs

Let’s understand the working of TenserFlow.js using an example.

Example: In this example, we create an input tensor and weight tensor and pass it to the bincount function and see how bincount calculates the value for the output tensor using Tensorflow.js tf.bincount() Function.

Javascript

// Importing tensorflow.js library
import * as tf from "@tensorflow/tfjs"

// Initializing the input
const geek_input = tf.tensor([1, 2, 9, 6, 5,
    4, 7, 4, 7, 4, 3], [1, 11], 'int32');

// Printing Input tensor
console.log('Input tensor: ',geek_input)

// Weight and size for the bincount
const geek_Weight = tf.tensor(
    [0, 2, 5, 8, 9, 3, 5, 5, 3, 8, 2]);

const geek_size = 8;

// Applying bincount to input tensor
const r = tf.bincount(geek_input, geek_Weight, geek_size)

// Printing result
console.log("Output tensor: ", r)

Output:

Input tensor:  Tensor
    [[1, 2, 9, 6, 5, 4, 7, 4, 7, 4, 3],]
Output tensor:  Tensor
   [0, 0, 2, 2, 16, 9, 8, 8]

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

My Personal Notes arrow_drop_up


Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.