Open In App

Tensorflow.js tf.layers.zeroPadding2d() 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.

The tf.layers.zeroPadding2d( ) function is used for adding rows and columns for zeros at the top, bottom, left, and right side of and image tensor.



Syntax: 

tf.layers.zeroPadding2d(args);

 Parameters: This method accepts the args as a parameter which has the following properties:



Returns: It returns ZeroPadding2D object.

Example 1: In this example, we add a zero-padding layer with default values.




// Importing tensorflow
const tf = require("@tensorflow/tfjs")
 
// Input 4d Tensor    
const img4d = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);
 
// Adding padding in Tensor
const pad = tf.layers.zeroPadding2d();
const imgpad = pad.apply(img4d);
 
// Printing 4d Tensor with padding</div>
imgpad.print()

 
 

Output:

 

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

Example 2: In this example, we add zero paddings in tensor of specific data type and with define data-Format.

 




// Importing tensorflow
const tf = require("@tensorflow/tfjs")
 
// Input 4d Tensor    
const img4d = tf.tensor4d([1, 2, 3, 4], [1, 2, 2, 1]);
 
// Adding padding in Tensor
const pad = tf.layers.zeroPadding2d({
    padding: 2,
    dataFormat: 'channelsFirst', dtype: 'int32'
});
 
const imgpad = pad.apply(img4d);
 
// Printing 4d Tensor with padding
imgpad.print()

 
 

Output: 

 

Tensor
    [[[[0, 0, 0, 0, 0],
       [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, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 3, 0, 0],
       [0, 0, 4, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]]]]

 Reference: https://js.tensorflow.org/api/latest/#layers.zeroPadding2d

 


Article Tags :