简体   繁体   中英

How to use tf.pad without batch size axis?

I'm trying to use tf.pad for image of shape (?, M, N) , here ? is the batch size (not fixed) and M , N are image height, width, respectively. My tensorflow version is 1.14 .

For example, if the input x (with dtype=tf.float32 ) is from MNIST , then M=N=28 with unknown batch size ? : (?, M, N) ? : (?, M, N) .

To pad (zero) this image with padding size : (1,1,1,1) so the output size (?, 30,30) , I used the following code:

paddings = tf.constant([[1,1], [1,1]])

output = tf.pad(x[1:], paddings, "CONSTANT", constant_values = 0)

But it doesn't work. I think it's because x[1:] is not the each image (M,N) . How can i use tf.pad to tensor (?, M, N) with (1,1,1,1) so the size of output image (?,M + 2,N + 2) in tensorflow version 1.14 ?

Thank you.

In the tf.pad paddings is an integer tensor with shape [n, 2] , where n is the rank of tensor. https://www.tensorflow.org/api_docs/python/tf/pad

So you need to change the padding tensor like following:

img = tf.random.uniform((1,28,28))
print(img.shape)

>>> (1, 28, 28)

paddings = tf.constant([[0, 0,], [1, 1], [1, 1]])
img_padded = tf.pad(img, paddings)

print(img_padded.shape)

>>> (1, 30, 30)

I tested the code on tf 2.x but the same should also work with tf 1.x.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM