Thursday, October 16, 2025
HomeLanguagesJavascriptTensorflow.js tf.pad() Function

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:

  • tensor: It is a Tensor to pad.
  • paddings: It is an array of length R, the rank of the given tensor, where each element is of length 2 of ints ([pad_Before, pad_After]), specifies how much padding should be given along each dimension of the tensor.
  • constantValue: It is the padding value to be used.  The default value is 0.

Return Value: It returns tf.Tensor object.

Example 1:

Javascript




// 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:

Javascript




// 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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS