python - tensorflow 计算 tf.nn.conv2d

标签 python tensorflow convolution

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

enter image description here

我想使用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 得到的输出是关闭的:

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

我做错了什么?

最佳答案

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

  1. 创建两个单独的权重
  2. 分别计算每个权重的卷积

代码示例:

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())

关于python - tensorflow 计算 tf.nn.conv2d,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52923062/

相关文章:

python - 如何在pyfiglet python3中获取所有可用的字体

python - 将整数解析为字符串的意外行为

python - 如何将列表中的两个相邻元素相乘?

javascript - 新形状和旧形状必须具有相同数量的元素

python - 在 Keras 中制作采样层

python - Tensorflow Dataset API shuffle 将性能降低 9 倍

c++ - 在 C++ 中执行 sobel 过滤器函数时我做错了什么

python - 如何读取tfrecord文件

python - 卷积模糊图像-python

java - 理解卷积矩阵