tensorflow - 在张量流中生成与卷积核输入等效的索引
问题描述
我想在进入 tensorflow 中每个 2D 卷积核的数据中添加一些预处理。如果输入是大小为 (N, H, W, 5) 的 NHWC,卷积核的大小为 (3, 3),步幅为 (1, 1),填充“有效”(我将稍后应用卷积,如解释下面),我首先想获得大小为 (N, H-2, W-2, 5*9) 的张量,其中沿暗淡 1 和 2 的索引表示卷积核的空间位置,暗淡 3 的大小5 * 9 = 45,每个索引对应于将进入卷积的输入单元/通道,所有内核输入沿通道维度排列。获得这个张量后,我想沿着通道维度(dim 3)应用一些变换,然后使用大小为 (1, 1) 和步幅 (1, 1) 的内核调用卷积。本质上,我想首先收集将进入每个卷积核的所有输入,对它们进行处理,然后调用卷积(它将具有大小为 (1, 1) 的内核,因为我已经收集了所有内核输入沿通道轴)。如果 tensorflow 中有一个操作可以帮助我为这些窗口生成索引,我很感兴趣,我以后也许可以将其与 tf.gather_nd() 一起使用。欢迎任何其他想法/解决方案。谢谢!
解决方案
我在下面粘贴我的解决方案:
N = 32
H = 101
W = 101
C = 5
# input batch data
batch = tf.constant(
value=range(N*H*W*C),
shape=[N, H, W, C],
dtype=tf.float32)
print(f"Batch shape: {batch.shape}")
print(f"Batch tensor size: {tf.math.reduce_prod(batch.shape).numpy()}")
print()
def prepare_conv_input(batch):
i_to_stack = []
for i in range(0, H-2, 2):
j_to_stack = []
for j in range(0, W-2, 2):
inp = tf.slice(
batch,
begin=[0, i, j, 0],
size=[N, 3, 3, C])
j_to_stack.append(
tf.reshape(
inp,
(N, 3*3*C)))
i_to_stack.append(
tf.stack(j_to_stack, 1))
return tf.stack(i_to_stack, 1)
result = prepare_conv_input(batch)
print(f"Prepared shape: {result.shape}")
print(f"Prepared tensor size: {tf.math.reduce_prod(result.shape).numpy()}")
print()
结果是:
Batch shape: (32, 101, 101, 5)
Batch tensor size: 1632160
Prepared shape: (32, 50, 50, 45)
Prepared tensor size: 3600000
由于相邻卷积之间的重叠,数据大小增加。
推荐阅读
- python - 如何在 A40 GPU 上无错误地运行 PyTorch(也使用 DDP)?
- c - 取消引用指针 *p vs ("%s", p)
- firebase - Firebase 不会仅在一台设备上加载图像
- php - Laravel 缺少 [Route: login] 所需的参数
- graphql - 限制用户可以在 Amplify GraphQL API 中创建的记录数量的方法
- python-asyncio - ib_insync reqHistoricalDataAsync 如何与 Asyncio 一起工作?
- android - 我如何将数据从 RecyclerView 适配器发送到 viewmodel
- opencv - 使用 Gstreamer 同时在 2 个应用程序中使用视频设备
- sql - 如何使用 ORACLE SQL 对特定的行值进行操作?
- json - 为什么无法使用另一个文件中的 require_relative 找到我的 JSON 文件?