【问题标题】:Numpy: How to stack 3D arrays in rows iteratively?Numpy:如何迭代地将 3D 数组堆叠成行?
【发布时间】:2018-11-07 08:48:25
【问题描述】:

我正在尝试将导致 3D 数组的计算结果堆叠成行(轴 = 0)。我不提前知道结果。

import numpy as np

h = 10
w = 20
c = 30
result_4d = np.???   # empty

for i in range(5):
   result_3d = np.zeros((h, w, c))  #fake calculation
   result_4d = np.???  # stacked result_3ds on axis=0

return result_4d

我尝试了 numpy *stack 调用的各种排列,但我不可避免地遇到了形状不匹配错误。

【问题讨论】:

  • 一旦你很好地理解了数组的形状,你就可以定义正确的“空”起点。这是锻炼形状的好方法,但不是最快的方法。
  • 如需更详细的答案,请阅读stackoverflow.com/questions/53135673/…
  • 连接数组的基本工具是np.concatenate。这需要一个 n-d 数组的列表,并将它们连接到选定的轴上以创建一个新的 n-d 数组。这意味着,要获得 4d 数组,您需要从 4d 数组开始。如果您使用迭代方法,则初始“空”数组本身必须是 4d,但包含 0 个元素。

标签: python numpy


【解决方案1】:

先入列表,再入栈。

h = 10
w = 20
c = 30
l = []
for i in range(5):
    result_3d = np.zeros((h, w, c))  #fake calculation
    l.append(result_3d)
res = np.stack(l, axis=-1)

res.shape # (10, 20, 30, 5)

# move stacked axis around ...
np.transpose(res, (3,0,1,2)).shape # (5, 10, 20, 30) 

如果你想循环更新,你可以这样做:

res = ''
for i in range(5):
    result_3d = np.zeros((h, w, c))  #fake calculation
    if type(res) is str:
        res = np.array([result_3d]) # add dimension
        continue
    res = np.vstack((res, np.array([result_3d]))) # stack on that dimension

res.shape # (5, 10, 20, 30)

【讨论】:

  • 谢谢。我想到了这一点,但我想知道是否有没有中间变量的直接解决方案。
  • @KevinJohnsrude 找到了一种方法,您需要添加一个维度以便堆栈工作。
  • 谢谢。我还将范围更改为 range(5) 以消除形状的歧义。
  • 编辑以反映这一变化。
  • 在循环内部而不是在循环之后的一次调用中堆叠是一个非常糟糕的主意,因为数据复制量与循环长度的平方成正比,而不是与循环长度成正比.对于range(5),这可能无关紧要,但后来当 5 变成 500 万时,这可能是灾难性的。
猜你喜欢
  • 1970-01-01
  • 2019-09-27
  • 2014-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多