TensorFlow – How to add padding to a tensor
Last Updated :
01 Aug, 2020
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
import tensorflow as tf
input = tf.constant([[ 1 , 2 ], [ 3 , 4 ]])
padding = tf.constant([[ 2 , 2 ], [ 2 , 2 ]])
print ( "Input: " , input )
print ( "Padding: " , padding)
res = tf.pad( input , padding, mode = 'CONSTANT' )
print ( "Res: " , res )
|
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
import tensorflow as tf
input = tf.constant([[ 1 , 2 , 5 ], [ 3 , 4 , 6 ]])
padding = tf.constant([[ 1 , 1 ], [ 2 , 2 ]])
print ( "Input: " , input )
print ( "Padding: " , padding)
res = tf.pad( input , padding, mode = 'REFLECT' )
print ( "Res: " , res )
|
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)
Share your thoughts in the comments
Please Login to comment...