【发布时间】:2020-11-29 03:47:33
【问题描述】:
我有一个 TensorFlow 层,我用它来创建一个名为“cost_volume”的 4d 张量。
我的代码完成了工作。但是,由于嵌套的 for 循环而不是使用 numpy 内置函数,它相当慢。我需要它至少快 300 倍。如何将其转换为使用 numpy 内置函数且没有 for 循环的更高效的代码?
max_disparity = 10
layer = np.random.rand(2, 188, 621, 32)
cost_volume = np.random.rand(layer.shape[0], layer.shape[1], layer.shape[2],\
max_disparity + 1, feature_size * 2)
for i in range(layer.shape[0]):
for y in range(layer.shape[1]):
for x in range(layer.shape[2]):
for d in range(max_disparity + 1):
if i == 0:
cost_volume[i][y][x][d] = np.concatenate((layer[0][y][x], \
layer[1][y][min(x + d, layer.shape[2] - 1)]))
else:
cost_volume[i][y][x][d] = np.concatenate((layer[0][y][max(0, x - d)], \
layer[1][y][x]))
【问题讨论】:
-
您需要提供更多信息,例如,
layer数组的形状是什么? -
(2, 188, 621, 32)
-
您能解释一下您要达到的目标吗?我很难弄清楚 np.concatenates 的目标是什么。
-
我们要连接两个数组,(特征):[1 2 3], [4 5 6] -> [1 2 3 4 5 6]
-
请参阅question,了解如何使用另一个数组/列表对数组进行切片
标签: python numpy tensorflow slice