Open In App

Tensorflow.js tf.pad() Function

Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. It also helps the developers to develop ML models in JavaScript language and can use ML directly in the browser or in Node.js.

The tf.pad() function is used to Pad a tf.Tensor with a given value along with paddings.



Syntax:

tf.pad(tensor, paddings, constantValue)

Parameters: This function accepts the following three parameters:



Return Value: It returns tf.Tensor object.

Example 1:




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
 
// Initializing 3d tensor and then using
// .pad() function to print the result
tf.tensor3d([1, 2, 3, 4], [2, 2, 1])
  .pad([[0, 0], [1, 1], [2, 2]])
      .print();

 Output:

Tensor
    [[[0, 0, 0, 0, 0],
      [0, 0, 1, 0, 0],
      [0, 0, 2, 0, 0],
      [0, 0, 0, 0, 0]],

     [[0, 0, 0, 0, 0],
      [0, 0, 3, 0, 0],
      [0, 0, 4, 0, 0],
      [0, 0, 0, 0, 0]]]

Example 2:




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
 
// Initializing 2d tensor
let geek1 = tf.tensor2d([[1, 2], [3, 4]]);
 
// Using .pad() function.
let geek2 = geek1.pad([[0, 1], [2, 1]]);
 
// Printing the result.
geek2.print();

 Output:

Tensor
    [[0, 0, 1, 2, 0],
     [0, 0, 3, 4, 0],
     [0, 0, 0, 0, 0]]

Reference: https://js.tensorflow.org/api/3.6.0/#pad

Article Tags :