Tensorflow:对于小批量中的每个样本,使用不同的滤波器进行卷积


问题内容

我想使用一个二维卷积滤波器,该滤波器取决于张量流中迷你批处理中的样本。有什么想法可以做到的,特别是如果每​​个小批量的样品数量未知时?

具体来说,我有inp表单的输入数据MB x H x W x Channels,并且有F表单的过滤器MB x fh x fw x Channels x OutChannels

假设

inp = tf.placeholder('float', [None, H, W, channels_img], name='img_input')

我想这样做tf.nn.conv2d(inp, F, strides = [1,1,1,1]),但这是不允许的,因为F不能具有最小批量尺寸。任何想法如何解决这个问题?


问题答案:

我认为建议的技巧实际上是不正确的。tf.conv3d()图层发生的事情是将输入卷积到深度(=实际批处理)维度上,然后沿着结果要素图求和。随着padding='SAME'所产生的产出数量则恰好是同批大小,这样一个被愚弄!

编辑:我认为对不同的迷你批处理元素使用不同的滤镜进行卷积的一种可能方法涉及“破解”深度卷积。假设批量大小MB已知:

inp = tf.placeholder(tf.float32, [MB, H, W, channels_img])

# F has shape (MB, fh, fw, channels, out_channels)
# REM: with the notation in the question, we need: channels_img==channels

F = tf.transpose(F, [1, 2, 0, 3, 4])
F = tf.reshape(F, [fh, fw, channels*MB, out_channels)

inp_r = tf.transpose(inp, [1, 2, 0, 3]) # shape (H, W, MB, channels_img)
inp_r = tf.reshape(inp, [1, H, W, MB*channels_img])

out = tf.nn.depthwise_conv2d(
          inp_r,
          filter=F,
          strides=[1, 1, 1, 1],
          padding='VALID') # here no requirement about padding being 'VALID', use whatever you want. 
# Now out shape is (1, H, W, MB*channels*out_channels)

out = tf.reshape(out, [H, W, MB, channels, out_channels) # careful about the order of depthwise conv out_channels!
out = tf.transpose(out, [2, 0, 1, 3, 4])
out = tf.reduce_sum(out, axis=3)

# out shape is now (MB, H, W, out_channels)

如果MB未知,应该可以使用tf.shape()(我认为)动态确定