简体   繁体   中英

Adding 3D array to 4D array

My goal is to have a 4D array with each "value" k in the 4th dimension correspond to the kth 3D tensor. I've tried quite a few things, but always get "all the input arrays must have same number of dimensions".

There is a function that returns a new but different array (always of the same size, eg 3000x1000x500) and I would like the final output to be a 3000x1000x500xK*n array where n is the number of repetitions it takes to escape the while loop. This is what I have so far:

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])

Thanks in advance

Collecting arrays in a list:

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.]])]

If I follow your description right, you want to join the arrays on a new final axis:

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 behaves the same as np.array , joining them on a new initial axis. np.concatenate can be used to join on an existing axis. ( stack uses concatenate , just adding a new dimension to each array first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM