tensorflow conv2d的padding策略是什么?

What is the padding strategy of tensorflow conv2d?

我按照

的问答

但是我仍然对 tf.nn.conv2d 的 start indexpadding strategy 感到困惑 在我进行了以下测试后,希望有人能给我一个线索,尤其是 oddeven strides

array height(h),kernel size(f), stride number(s)

h,f,s = 4,3,2 

padding number on left column (pl) padding on right column (pr) of matrix x

pl = int((f-1)/2)                           
pr = int(np.ceil((f-1)/2))                  

tf.reset_default_graph()
x = np.arange(1*h*h*1).reshape(1,h,h,1)
w = np.ones((f,f,1,1))
xc = tf.constant(x,np.float32)
wc = tf.constant(w,np.float32)
xp = np.pad(x,((0,0),(pl,pr),(pl,pr),(0,0)),'constant',constant_values = 0)
xcp = tf.constant(xp,np.float32)
zs = tf.nn.conv2d(xc,wc,strides=[1,s,s,1],padding='SAME')
zv = tf.nn.conv2d(xc,wc,strides=[1,s,s,1],padding='VALID')
zp = tf.nn.conv2d(xcp,wc,strides=[1,s,s,1],padding='VALID')

with tf.Session() as sess:
    os = sess.run(zs)
    ov = sess.run(zv)
    op = sess.run(zp)

print('x shape: ', x.shape,' kernel: ',f,' stride: ',s,'\n',x[0,:,:,0])
print(' 'SAME' os shape: ', os.shape,'\n',os[0,:,:,0])
print(' 'VALID' ov shape: ', ov.shape,'\n',ov[0,:,:,0])
print(' 'VALID' op shape: ', op.shape,' pl: ',pl,' pr: ', pr,'\n',op[0,:,:,0])

在卷积池化的情况下,零填充应该像我定义的那样在数组 x 周围填充 xp ,但是,我无法弄清楚 conv2d 的起始索引它

原点矩阵 x

x shape:  (1, 4, 4, 1)  kernel:  3  stride:  2 
[[ 0  1  2  3]
[ 4  5  6  7]
[ 8  9 10 11]
[12 13 14 15]]

在'same'类型的卷积中,为什么tf.nn.conv2d在这种情况下不在左边补零?

'SAME' os shape:  (1, 2, 2, 1) 
[[45. 39.]
[66. 50.]]

矩阵 x 上的有效卷积

'VALID' ov shape:  (1, 1, 1, 1) 
[[45.]]

xp 零填充后的有效类型卷积(如我预期的结果)

'VALID' op shape:  (1, 2, 2, 1)  pl:  1  pr:  1 
[[10. 24.]
[51. 90.]]

解释了(总)填充的公式here

在你的情况下,n mod s = 4 mod 2 = 0 所以

p = max(3 - 2, 0) = 1

所以

p_left = p // 2 = 0
p_right = 1 - p_left = 1

这就解释了为什么您在左侧看不到任何填充。