TensorFlow – How to add padding to a tensor

TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks.

Padding means adding values before and after Tensor values.

Method Used:

  • tf.pad: This method accepts input tensor and padding tensor with other optional arguments and returns a Tensor with added padding and same type as input Tensor. Padding tensor is a Tensor with shape(n, 2).

Example 1: This example uses constant padding mode i.e. value at all the padded indices will be constant.

Python3



filter_none

edit
close

play_arrow

link
brightness_4
code

# importing the library
import tensorflow as tf
  
# Initializing the Input
input = tf.constant([[1, 2], [3, 4]])
padding = tf.constant([[2, 2], [2, 2]])
  
# Printing the Input
print("Input: ", input)
print("Padding: ", padding)
  
# Generating padded Tensor
res = tf.pad(input, padding, mode ='CONSTANT')
  
# Printing the resulting Tensors
print("Res: ", res )

chevron_right


Output:

Input:  tf.Tensor(
[[1 2]
 [3 4]], shape=(2, 2), dtype=int32)
Padding:  tf.Tensor(
[[2 2]
 [2 2]], shape=(2, 2), dtype=int32)
Res:  tf.Tensor(
[[0 0 0 0 0 0]
 [0 0 0 0 0 0]
 [0 0 1 2 0 0]
 [0 0 3 4 0 0]
 [0 0 0 0 0 0]
 [0 0 0 0 0 0]], shape=(6, 6), dtype=int32)

Example 2: This example uses REFLECT padding mode. For this mode to work paddings[D, 0] and paddings[D, 1] must be less than or equal to tensor.dim_size(D) – 1.

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing the library
import tensorflow as tf
  
# Initializing the Input
input = tf.constant([[1, 2, 5], [3, 4, 6]])
padding = tf.constant([[1, 1], [2, 2]])
  
# Printing the Input
print("Input: ", input)
print("Padding: ", padding)
  
# Generating padded Tensor
res = tf.pad(input, padding, mode ='REFLECT')
  
# Printing the resulting Tensors
print("Res: ", res )

chevron_right


Output:

Input:  tf.Tensor(
[[1 2 5]
 [3 4 6]], shape=(2, 3), dtype=int32)
Padding:  tf.Tensor(
[[1 1]
 [2 2]], shape=(2, 2), dtype=int32)
Res:  tf.Tensor(
[[6 4 3 4 6 4 3]
 [5 2 1 2 5 2 1]
 [6 4 3 4 6 4 3]
 [5 2 1 2 5 2 1]], shape=(4, 7), dtype=int32)

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.