简体   繁体   中英

How to add specific padding in conv2d

I am trying to pass a tensor to a CNN in python. I am using tf.layers.conv2d for this. I want to get the output dimensions as half of the input. I understand that I can use a padding of 'same' followed by a max pooling layer to achieve this, but another way that I found out in a recent paper is to use a 3x3 kernel with a 2x2 stride in addition to a 1x1 padding

Now, as I understand, conv2d allows for a parameter called padding which can be either 'valid' or 'same', which does not allow for a padding of a specific length.

Is there any way that this can be achieved directly in the operation? I am asking since the idea is to use multiple convolution layers, each successively halving the dimensions both length and width-wise.

If someone can point out a similar topic or help with this, it would be great.

Edit:

I have been asked to include the code. But there is not much of a code since I am stuck at the very first point where the CNN needs to be designed. Nonetheless, here is the part that accepts the initial input and starts defining the CNN (here I have kept padding='same' since I was checking if that would work):

def conv2d(z):
    output = tf.layers.conv2d(z,strides=[2,2],filters=3,padding='same',kernel_size=3);

I am stuck at this point since going any further needs this initial layer to be correctly defined as successive layers will also work on the same principle.

Also, my initial input size is a 224x224 image with 1 channel (grayscale image)

So, I found an answer to this. There is an inbuilt function called pad in tensorflow, which can be used to solve it. What I am doing is this

output = tf.pad(output, paddings, "CONSTANT")
output = tf.layers.conv2d(output,strides=[2,2],kernel_size=3,filters=3)

This means I am using a tf.pad before every layer wherein the variable 'paddings' is defined as below

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

This ensures that each layer is padded before being passed on for convolution, thus giving the output as desired

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