Keras Conv2D padding

In TensorFlow Keras padding attribute of the Convolution layers can have only two values - “valid” and “same”. Is there any reason why not having different padding in X and Y? For my model I want to set padding “same” in Y but “valid” in X.

Hi @Anton_Milev you can check out Zero padding layer of tensorflow.

Here you can define the number of pixels of padding you want for each axis of the image.

So if you want ‘valid’ padding for x-axis just pass it as 0 and pass the decrement in pixel value for each layer as the value for y-axis to keep it ‘same’.

Thanks but ZeroPadding2D does not do what I need, after I posted here my question I found this:

I can’t understand from its description - is this request from more than an year already fulfilled in TensorFlow 2.10, and if so why Keras documentation is not updated? There are use cases when this feature is needed.

Hi @Anton_Milev, Could you please elaborate on your use case for implementing different padding for X and Y. Thank You.

Hello, Kiran.

Thanks for your reply,

I am experimenting with several models for image processing with convolution filters. For example - suppose that have input images that are the same size in Y but different in X. I may want to use first a filter in X direction only , for example a scale filter with interpolation. There are other ways to do it but is not convenient, while convolution layers are very fast and easy to use.

When I have time I will make post describing the use cases better, it is a large topic, meanwhile can I get a simple answer - is the custom padding supported in the latest TensorFlow? I think that in pytorch this feature is available and as described in the post above it should not be too big effort to add in TensorFlow too.

Hi @Anton_Milev, I think tf.keras.layers.ZeroPadding2D can achieve that,

  • If padding = int then the same symmetric padding is applied to height and width.
  • If padding = tuple of 2 ints then interpreted as two different symmetric padding values for height and width: (symmetric_height_pad, symmetric_width_pad).
  • If padding = tuple of 2 tuples of 2 ints then interpreted as ((top_pad, bottom_pad), (left_pad, right_pad))

Thank You.