• Last Updated : 01 Aug, 2020

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

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

 `# 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 )`

Output:

```Input:  tf.Tensor(
[[1 2]
[3 4]], shape=(2, 2), dtype=int32)
[[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

 `# 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 )`

Output:

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