我正在关注this StackOverflow 问题与解答。
但是,在进行以下测试后,我仍然对 tf.nn.conv2d
的起始索引和填充策略感到困惑,希望,有人可以在这里给我一个线索,特别是在奇数和偶数步幅上。
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]]
在“相同”类型的卷积中,为什么 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
这解释了为什么您在左侧看不到任何填充。
关于python - TensorFlow conv2d的填充策略是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50545506/