gpt4 book ai didi

python - 在 tensorflow 中对两个矩阵进行卷积的最佳方法是什么?

转载 作者:行者123 更新时间:2023-11-30 09:28:53 24 4
gpt4 key购买 nike

假设

    A = [[1,2,3],[4,5,6],[7,8,9]]
B = [[1,2,1],[2,1,1],[1,1,2]]

与 kernel_size=2*2 和 stride=1 进行卷积后,输出应为

[[18,18],[28,37]]

我们需要在每个2*2部分之间应用卷积运算 A 到 B 的每 2*2 部分。 如何使用 tensorflow 有效地执行此操作? tensorflow 有什么方法可以直接做到这一点吗?

最佳答案

这是使用 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)

我使用了交互式 session 来评估这些张量,但即使您定义了计算图,然后使用显式 session 运行它,这也应该可以完美地工作。

编辑

此外,需要澄清的是,此方法适用于任何 (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)

关于python - 在 tensorflow 中对两个矩阵进行卷积的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47991379/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com