Shape alignment
Prepare tensors with uniform spatial or sequence dimensions before batching or further computation.
TensorFlow · Function
tf.pad adds values before and after each tensor dimension according to [before, after] pairs. It supports CONSTANT, REFLECT, and SYMMETRIC modes and returns a tensor with the input's type.
tf.pad adds values before and after every tensor dimension according to a two-column padding specification. The selected mode controls whether padding uses a constant, reflected values, or symmetric values; the output keeps the input type while its dimensions grow by the requested amounts.
tf.pad(tensor, paddings, mode='CONSTANT', constant_values=0, name=None)| Name | Type | Description |
|---|---|---|
tensor | Tensor | Input tensor to pad. |
paddings | Tensor of int32 | Integer padding counts with shape [n, 2], where n is the tensor rank. |
mode | str | Padding strategy: CONSTANT, REFLECT, or SYMMETRIC; case-insensitive. |
constant_values | scalar | Scalar value used for added elements in CONSTANT mode; must match tensor's type. |
name | str | Optional operation name. |
A Tensor with the same type as tensor.
import tensorflow as tf
t = tf.constant([[1, 2, 3], [4, 5, 6]])
padded = tf.pad(t, [[1, 1], [2, 2]], mode="CONSTANT", constant_values=0)
print(padded.numpy())Adds one row before and after, and two columns before and after, using zero padding.
Prepare tensors with uniform spatial or sequence dimensions before batching or further computation.
Add a controlled border around arrays, such as zero borders for numerical or image operations.
Extend tensor edges using neighboring values instead of a fixed fill value.
tf.pad pads each tensor dimension using a [before, after] pair. For rank n, paddings has shape [n, 2], and the output dimension is the original size plus both requested amounts.
Follow-up: What happens if the padding rank does not match the tensor rank? The padding specification is invalid because one pair is required for every tensor dimension.
CONSTANT fills added elements with constant_values, while REFLECT and SYMMETRIC derive padding from tensor values. The mode argument accepts those three names without regard to case.
Follow-up: How would you choose between REFLECT and SYMMETRIC? Compare whether the boundary value itself is repeated when constructing the reflected extension.
The result is a Tensor with the same type as tensor. In CONSTANT mode, constant_values must also have that type.
Follow-up: What should be checked when padding integer and floating-point tensors? Ensure the supplied constant is representable with, and matches, the tensor's dtype.
tf.constanttf.image.resize_with_padtf.keras.utils.pad_sequences