How to do zero padding in keras conv layer?

Take a look at spatial_2d_padding function. It pads a tensor with zeroes.


When you use padding='valid', there's no padding.

When you use padding='same' with strides=1, the input are zero-padded so that width and height of output is the same as the input. As described in the document, "same" is slightly inconsistent across backends with strides != 1.

If you want to manually set the padding value, maybe the simplest way is to add a ZeroPadding2D layer before Conv2D.

For example, ZeroPadding2D(padding=((1,2),(3,4))) will add 1 dimension on the left, 2 on the right, 3 on the top and 4 on the bottom. ZeroPadding2D(5) will add 5 dimension on all 4 borders.

(btw, It's a wrap layer of backend function spatial_2d_padding)


"same" means zero padding. It is currently not possible to pad with other constants in an efficient way.