首页 > 解决方案 > 如何将 TensorFlow 2D 卷积 (tf.nn.conv2d) 应用于单个(非批处理)2D 图像?

问题描述

我想tf.nn.conv2d()单个图像示例上使用该函数,但 TensorFlow 文档似乎只提到将此转换应用于一批图像。

文档提到输入图像必须是 shape[batch, in_height, in_width, in_channels]并且内核必须是 shape [filter_height, filter_width, in_channels, out_channels]。但是,用输入形状实现 2D 卷积的最直接方法是什么[in_height, in_width, in_channels]

这是当前方法的示例,其中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]

当我只对转换一个示例感兴趣时,这感觉像是一项不必要且昂贵的操作。

有没有不涉及重塑的简单/标准方法?

标签: pythontensorflowconv-neural-networkconvolution

解决方案


AFAIK 没有办法解决它。似乎(此处此处)第一个操作创建了一个副本(如果我错了,请有人纠正我)。不过,您可以改用tf.expand_dims它,因为它很冗长,所以 IMO 更具可读性。

另一方面,0在这种情况下,从张量中获取元素不应该执行复制,并且几乎是免费的。

最重要的是,除了语法上的一些不便(例如[0])之外,这些操作绝对不昂贵,尤其是在执行卷积的情况下。

顺便提一句。其他现成的替代层,如 中的那些tf.keras,也需要批处理作为第一维。


推荐阅读