代码之家  ›  专栏  ›  技术社区  ›  TC. Yu

tensorflow conv2d的填充策略是什么?

  •  1
  • TC. Yu  · 技术社区  · 6 年前

    我跟着你的问题和答案走 stackoverflow

    然而,我仍然对这个问题感到困惑 起始索引 填充策略 属于 tf。nn。conv2d 在我做了以下测试之后,希望有人能给我一个线索,尤其是关于 古怪的 即使 跨步

    数组高度(h)、内核大小(f)、步幅数(s)

    h,f,s = 4,3,2 
    

    矩阵左栏(pl)上的填充数字右栏(pr)上的填充 十、

    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 然而,我不知道它的起始索引是如何定义的

    原点矩阵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.]]
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   P-Gn    6 年前

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

    enter image description 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
    

    这就解释了为什么你在左边看不到任何填充物。