Python tensorflow计算tf.nn.conv2d

Python tensorflow计算tf.nn.conv2d,python,tensorflow,convolution,Python,Tensorflow,Convolution,我在Excel中手动计算了3x3图像和两个2x2过滤器之间的卷积: 我想使用tensorflowtf.nn.conv2d: x_raw = np.array([ [2,5,3], [3,4,2], [4,1,1] ]) f_raw = np.array( [[ [2,1], [3,4] ],[ [4,1], [1,2] ]]) f = tf.constant(f_raw, dtype=tf.float32) x = tf.con

我在Excel中手动计算了3x3图像和两个2x2过滤器之间的卷积:

我想使用tensorflow
tf.nn.conv2d:

x_raw = np.array([
    [2,5,3],
    [3,4,2],
    [4,1,1]
])

f_raw = np.array(
[[
    [2,1],
    [3,4]
],[
    [4,1],
    [1,2]   
]])

f = tf.constant(f_raw, dtype=tf.float32)
x = tf.constant(x_raw, dtype=tf.float32)

filter = tf.reshape(f, [2, 2, 1, 2])
image  = tf.reshape(x, [1, 3, 3, 1])

tf.nn.conv2d(image, filter, [1, 1, 1, 1], "VALID").eval()
但是tensorflow的输出是关闭的:

数组([[35,33.],[37,25.],[[35,25.],[19,15.]],dtype=float32)


我做错了什么?

要获得与excel示例相同的结果,您需要进行以下更改:

  • 创建两个独立的权重
  • 分别计算每个权重的卷积
  • 代码示例:

    x_raw = np.array([
        [2,5,3],
        [3,4,2],
        [4,1,1]
    ])
    #created two seperate weights 
    weight1 = np.array(
    [[
        [2,1],
        [3,4]
    ]])
    
    weight2 = np.array(
    [[
        [4,1],
        [1,2]
    ]]
    )
    weight1 = tf.constant(weight1, dtype=tf.float32)
    weight2 = tf.constant(weight2, dtype=tf.float32)
    x = tf.constant(x_raw, dtype=tf.float32)
    
    #change out_channels to 1 
    filter1 = tf.reshape(weight1, [2, 2, 1, 1])
    filter2 = tf.reshape(weight2, [2, 2, 1, 1])
    image = tf.reshape(x, [1, 3, 3, 1])
    
    with tf.Session() as sess:
      print(tf.nn.conv2d(image, filter1, [1, 1, 1, 1], "VALID").eval())
      print(tf.nn.conv2d(image, filter2, [1, 1, 1, 1], "VALID").eval())
    

    谢谢你,先生。但在我的例子中它在做什么呢?