如何为每个特征图单独执行卷积



我有NHWC:100 x 64 x 64 x 3格式的数据。我想将拉普拉斯滤波器分别应用于每个通道。我希望输出为100 x 64 x 64 x 3.

k = tf.reshape(tf.constant([[0, -1, 0], [-1, 4, -1], [0, -1, 0]], tf.float32), [3, 3, 1, 1])

我试过这个,但这抛出了尺寸错误。它需要 3 个通道作为输入。 output = tf.abs(tf.nn.conv2d(input, k, strides=[1, 1, 1, 1], padding='SAME'((

我修改了k = tf.reshape(tf.constant([[0, -1, 0], [-1, 4, -1], [0, 1, 0]]*3, tf.float32), [3, 3, 3, 1]),但这只输出了 1 个特征图100 x 64 x 64 x 1。 `

我尝试使用tf.nn.depthwise_conv2d但它抛出了相同的错误。我如何实际实现它?

output = tf.abs(tf.nn.depthwise_conv2d(input, k, strides=[1, 1, 1, 1], padding='SAME'))

这就是tf.nn.depthwise_conv2d所做的。但是,它比这更通用,实际上允许您为每个通道选择一个或多个卷积内核。

如果您希望所有通道都使用相同的内核,则需要复制内核以匹配通道数。

例如
# my 2D conv kernel
k = tf.constant([[0, -1, 0], [-1, 4, -1], [0, 1, 0]], tf.float32)
# duplicate my kernel channel_in times
k = tf.tile(k[...,tf.newaxis], [1, 1, channel_in])[...,tf.newaxis]
# apply conv
tf.nn.depthwise_conv2d(input, k, strides=[1, 1, 1, 1], padding='SAME')