如何将 TensorFlow 二维卷积 (tf.nn.conv2d) 应用于单个(非批处理)二维图像?
How can I apply a TensorFlow 2D Convolution (tf.nn.conv2d) to a single (non-batch) 2D image?
我想在 单个 图像示例上使用函数 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]
实现 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]
当我只对转换一个示例感兴趣时,这感觉像是一项不必要且昂贵的操作。
是否有 simple/standard 不涉及整形的方法?
据我所知,没有办法解决它。似乎(here and here) that the first operation creates a copy (someone correct me if I'm wrong). You may use tf.expand_dims
相反,由于冗长,它在 IMO 中更具可读性。
另一方面,从张量中获取 0
元素在这种情况下不应该执行复制并且几乎是免费的。
最重要的是,除了语法上的一些不便(例如[0]
),这些操作肯定并不昂贵,特别是在执行卷积的情况下。
顺便说一句。其他现成的替代层,如 tf.keras
中的层,也需要批处理作为第一维。
我想在 单个 图像示例上使用函数 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]
实现 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]
当我只对转换一个示例感兴趣时,这感觉像是一项不必要且昂贵的操作。
是否有 simple/standard 不涉及整形的方法?
据我所知,没有办法解决它。似乎(here and here) that the first operation creates a copy (someone correct me if I'm wrong). You may use tf.expand_dims
相反,由于冗长,它在 IMO 中更具可读性。
另一方面,从张量中获取 0
元素在这种情况下不应该执行复制并且几乎是免费的。
最重要的是,除了语法上的一些不便(例如[0]
),这些操作肯定并不昂贵,特别是在执行卷积的情况下。
顺便说一句。其他现成的替代层,如 tf.keras
中的层,也需要批处理作为第一维。