Tensorflow.js tf.LayersModel class .predictOnBatch() Method

Tensorflow.js is an open-source library that is developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment.

The .predictOnBatch() function is used to return expectancies for an individual group of instances.

Syntax:  

predictOnBatch(x)

Parameters:  

  • x: It is the stated input instances, like a Tensor i.e. the models that has precisely one input or else an array of Tensors i.e. models that has more than one input. It can be of type tf.Tensor, or tf.Tensor[].

Return Value: It returns the tf.Tensor object or tf.Tensor[].

Example 1:  

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Defining model
const Mod = tf.sequential({
   layers: [tf.layers.dense({units: 2, inputShape: [30]})]
});
  
// Calling predictOnBatch() method and
// Printing output
Mod.predictOnBatch(tf.randomNormal([6, 30])).print();


Output:

Tensor
    [[-1.4716092, -1.8019401],
     [-1.0033149, -0.2789704],
     [-0.4451316, 0.2422157 ],
     [-0.1512984, -0.0726933],
     [2.1483333 , 2.4668102 ],
     [0.4091003 , 0.8335327 ]]

Example 2:

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Calling predictOnBatch() method and
// Printing output
tf.sequential({
   layers: [tf.layers.dense({units: 3, inputShape: [40]})]
}).predictOnBatch(tf.truncatedNormal([5, 40])).print();


Output:

Tensor
    [[-1.5034456, -0.3429004, -0.2388536],
     [0.0083699 , -0.3176711, 2.1414554 ],
     [1.1850954 , -0.4481514, 1.1278313 ],
     [-0.1004405, 1.420954  , 0.4890856 ],
     [0.4184967 , 0.1191952 , -0.0936601]]

Reference: https://js.tensorflow.org/api/latest/#tf.LayersModel.predictOnBatch