这是使用tf.nn.conv2D 的一种直接方法:
In [1055]: A = np.array([[1,2,3],[4,5,6],[7,8,9]])
...: B = np.array([[1,1,1],[1,1,1],[1,1,1]])
...:
# define input tensor
In [1056]: tfA = tf.constant(A, dtype=tf.float32)
# reshape it to 4D tensor (as needed by tf.nn.conv2d)
In [1057]: tfA = tfA[tf.newaxis, :, :, tf.newaxis]
# define kernel tensor
In [1058]: tfK = tf.constant(B, dtype=tf.float32)
# again reshape it to 4D tensor (also, we use 2x2 convolution)
In [1059]: tfK = tfK[:-1, :-1, tf.newaxis, tf.newaxis]
# convolving the input tensor with kernel
In [1060]: convolved = tf.nn.conv2d(tfA, tfK, strides=[1, 1, 1, 1], padding="VALID")
In [1061]: convolved.eval()
Out[1061]:
array([[[[ 12.],
[ 16.]],
[[ 24.],
[ 28.]]]], dtype=float32)
我使用 交互式会话 来评估这些张量,但即使您定义了计算图,然后稍后使用显式会话运行它,它也应该可以正常工作。
编辑
另外,澄清一下,这种方法适用于任何(2x2) 内核张量B。考虑以下示例,其中内核张量中的条目加倍。不出所料,最终结果也将比上例中获得的结果翻倍。
另一个例子:
In [110]: A = np.array([[1,2,3],[4,5,6],[7,8,9]])
In [111]: B = np.array([[2,2,2],[2,2,2],[2,2,2]])
In [112]: tfA = tf.constant(A, dtype=tf.float32)
In [113]: tfA = tfA[tf.newaxis, :, :, tf.newaxis]
In [114]: tfK = tf.constant(B, dtype=tf.float32)
In [115]: tfK = tfK[:-1, :-1, tf.newaxis, tf.newaxis]
In [116]: convolved = tf.nn.conv2d(tfA, tfK, strides=[1, 1, 1, 1], padding="VALID")
In [117]: convolved.eval()
Out[117]:
array([[[[ 24.],
[ 32.]],
[[ 48.],
[ 56.]]]], dtype=float32)