将 3D 数组添加到 4D 数组

Adding 3D array to 4D array

我的目标是让第 4 维中的每个 "value" k 对应于第 k 个 3D 张量的 4D 数组。我已经尝试了很多东西,但总是得到 "all the input arrays must have same number of dimensions".

有一个函数 returns 一个新的但不同的数组(总是大小相同,例如 3000x1000x500),我希望最终输出是一个 3000x1000x500xK*n 数组,其中 n 是数组的数量跳出 while 循环所需的重复次数。这是我目前所拥有的:

tensors = []
K = 20 #arbitrary value
while error > threshold: #arbitrary constraint 
    for _ in range(K): 
        new_tensor = function(var)
        stack = [tensors, new_tensor]
        tensors = np.concatenate([t[np.newaxis] for t in stack])

提前致谢

正在列表中收集数组:

In [54]: tensors = []
In [55]: for i in range(3):
    ...:     arr = np.ones((2,4))*i
    ...:     tensors.append(arr)
    ...: tensors

Out[55]: 
[array([[0., 0., 0., 0.],
        [0., 0., 0., 0.]]), array([[1., 1., 1., 1.],
        [1., 1., 1., 1.]]), array([[2., 2., 2., 2.],
        [2., 2., 2., 2.]])]

如果我按照你的描述正确,你想在新的最终轴上连接数组:

In [56]: np.stack(tensors, axis=2)
Out[56]: 
array([[[0., 1., 2.],
        [0., 1., 2.],
        [0., 1., 2.],
        [0., 1., 2.]],

       [[0., 1., 2.],
        [0., 1., 2.],
        [0., 1., 2.],
        [0., 1., 2.]]])
In [57]: _.shape
Out[57]: (2, 4, 3)

np.stack with axis=0 的行为与 np.array 相同,将它们连接到新的初始轴上。 np.concatenate 可用于连接现有轴。 (stack 使用 concatenate,只是先为每个数组添加一个新维度。