Skip to main content
 首页 » 编程设计

python之如何对每个特征图单独执行卷积

2024年10月01日8myhome

我有 NHWC 格式的数据:100 x 64 x 64 x 3。我想分别将拉普拉斯滤波器应用于每个 channel 。我希望输出为 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 个 channel 作为输入。 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 所做的。然而,它比这更通用,实际上让您每个 channel 选择一个或多个卷积核。

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

# 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')