【问题标题】:How can I apply a TensorFlow 2D Convolution (tf.nn.conv2d) to a single (non-batch) 2D image?如何将 TensorFlow 2D 卷积 (tf.nn.conv2d) 应用于单个(非批处理)2D 图像?
【发布时间】:2019-09-18 10:07:47
【问题描述】:

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

文档中提到输入图像的形状必须为[batch, in_height, in_width, in_channels],并且内核的形状必须为[filter_height, filter_width, in_channels, out_channels]。但是,用输入形状[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]

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

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

【问题讨论】:

    标签: python tensorflow conv-neural-network convolution


    【解决方案1】:

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

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

    最重要的是,除了语法上的一点不便(例如[0]),这些操作绝对成本不高,尤其是在执行卷积的情况下。 p>

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-26
      • 2019-06-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多