python - 如何将 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]
当我只对转换一个示例感兴趣时,这感觉像是一项不必要且昂贵的操作。
有没有不涉及重塑的简单/标准方法?
解决方案
AFAIK 没有办法解决它。似乎(此处和此处)第一个操作创建了一个副本(如果我错了,请有人纠正我)。不过,您可以改用tf.expand_dims
它,因为它很冗长,所以 IMO 更具可读性。
另一方面,0
在这种情况下,从张量中获取元素不应该执行复制,并且几乎是免费的。
最重要的是,除了语法上的一些不便(例如[0]
)之外,这些操作绝对不昂贵,尤其是在执行卷积的情况下。
顺便提一句。其他现成的替代层,如 中的那些tf.keras
,也需要批处理作为第一维。
推荐阅读
- amazon-web-services - 如何根据 AWS API Gateway 中的请求标头动态设置集成端点?
- tableau-api - 根据值更改文本框中的文本
- google-bigquery - Bigquery - 选择最后 # 个不同的值
- ansible - 运行 ansible-playbook 时获取主机名
- ruby-on-rails - 设计 JWT “您需要先登录或注册才能继续”
- html - 如何在三角形 div 中使 CSS 渐变过低
- java - 初始化引导层 (IntelliJ) 期间发生 JavaFX 错误
- python - Python - 将同一文件夹中的特定文件附加到一个 *.csv
- sql - How to repeat previous row values until another field changes
- c++ - 包含带有 fetchcontent 的 opencv 不起作用