首页 > 解决方案 > Tensorflow - 具有多个通道的 2D 卷积

问题描述

我正在以这种方式定义我的输入和我的内核

import numpy as np
k = np.array([[
    [1, 0, 1],
    [2, 1, 0],
    [0, 0, 1]
],[
    [1, 0, 1],
    [2, 1, 0],
    [0, 0, 1]
]
], dtype=np.float32)
i = np.array([
    [4, 3, 1, 0],
    [2, 1, 0, 1],
    [1, 2, 4, 1],
    [3, 1, 0, 2]
], dtype=np.float32)

并将两者卷积使用

import tensorflow as tf
kernel = tf.reshape(k, [3, 3, 1, 2], name='kernel')
image  = tf.reshape(i, [1, 4, 4, 1], name='image')
res = tf.squeeze(tf.nn.conv2d(image, kernel, [1, 1, 1, 1], "VALID"))
with tf.Session() as sess:
   print sess.run(res)

产生的结果

[[[11. 12.]
  [ 8.  6.]]

 [[11. 11.]
  [ 8.  8.]]]

我想要做的是用一个“子过滤器”执行一个卷积

[
[1, 0, 1],
[2, 1, 0],
[0, 0, 1]
]

超过当时的输入。用笔和纸自己做,我得到

[[[14.  6.]
  [ 6. 12.]]

 [[14.  6.]
  [ 6. 12.]]]

“重塑参数”的所有其他排列都会产生错误,我在 TF 文档中找不到我做错了什么。有谁知道我做错了什么?

标签: pythonnumpytensorflowcomputer-vision

解决方案


您只需要tf.transpose在计算之前和之后使用:

import numpy as np
import tensorflow as tf

k = np.array([[
    [1, 0, 1],
    [2, 1, 0],
    [0, 0, 1]
],[
    [1, 0, 1],
    [2, 1, 0],
    [0, 0, 1]
]
], dtype=np.float32)
i = np.array([
    [4, 3, 1, 0],
    [2, 1, 0, 1],
    [1, 2, 4, 1],
    [3, 1, 0, 2]
], dtype=np.float32)

with tf.Graph().as_default(), tf.Session() as sess:
    kernel = tf.expand_dims(tf.transpose(k, (1, 2, 0)), 2, name='kernel')
    image  = tf.reshape(i, [1, 4, 4, 1], name='image')
    res = tf.squeeze(tf.nn.conv2d(image, kernel, [1, 1, 1, 1], "VALID"))
    res = tf.transpose(res, (2, 0, 1))
    print sess.run(res)

输出:

[[[ 14.   6.]
  [  6.  12.]]

 [[ 14.   6.]
  [  6.  12.]]]

推荐阅读