[英]How can I apply a TensorFlow 2D Convolution (tf.nn.conv2d) to a single (non-batch) 2D image?
我想在单个图像示例上使用函数tf.nn.conv2d()
,但是TensorFlow文档似乎只提到将这种转换应用于一批图像。
文档提到输入图像必须为[batch, in_height, in_width, in_channels]
形状,内核必须为[filter_height, filter_width, in_channels, out_channels]
形状。 但是,用输入形状[in_height, in_width, in_channels]
实现2D卷积的最直接方法是什么?
这是当前方法的示例,其中img
具有形状(高度,宽度,通道):
img = tf.random_uniform((10,10,3)) # a single image
img = tf.nn.conv2d([img], kernel)[0] # creating a batch of 1, then indexing the single example
我正在重塑输入,如下所示:
[in_height, in_width, in_channels]->[1, in_height, in_width, in_channels]->[in_height, in_width, in_channels]
当我仅对转换一个示例感兴趣时,这感觉像是不必要且昂贵的操作。
有没有简单/标准的方法可以完成此操作,而无需进行整形?
AFAIK无法解决。 似乎( 在这里和这里 )第一个操作创建了一个副本(如果我错了,请纠正我)。 但是,您可以改用tf.expand_dims
,因为它的冗长性使IMO更具可读性。
另一方面,从张量取0
元素在这种情况下不应该执行复制,并且几乎是免费的。
最重要的是 ,除了语法上的一些不便(例如[0]
),这些操作绝对不会花费很多 ,尤其是在执行卷积的情况下。
顺便说一句。 其他可用的替代层(例如tf.keras
层)也需要批量作为第一维。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.