从2D阵列到4D阵列

2024-03-29 06:11:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一定数量的Numpy数组

print(x.shape)
>>>(256,256)

我怎样才能把它们叠起来,使形状

print(y.shape)
>>>(certainnumber,256,256,1)

我一直在试着np.堆栈以及np.连接但我只会从轴错误或类似的东西

print(y.shape)
>>>(anothernumber,256) 

Tags: numpy数量堆栈错误np数组形状print
3条回答

方法#1

这是一个有^{}-

np.stack(list_of_arrays)[...,None]

方法#2

您可以为这些数组中的每一个预先设置一个带有None/np.newaxis的新轴,并沿第一个轴连接(certainnumber,256,256)形状,如下所示-

np.concatenate([i[None] for i in list_of_arrays],axis=0)

然后,添加新的轴作为最后一个(certainnumber,256,256,1)形状的尾随轴,如下所示-

np.concatenate([i[None] for i in list_of_arrays],axis=0)[...,None]

样本运行

In [32]: a = np.random.rand(3,4)

In [33]: b = np.random.rand(3,4)

In [34]: list_of_arrays = [a,b]

In [42]: np.stack(list_of_arrays)[...,None].shape
Out[42]: (2, 3, 4, 1)

In [35]: np.concatenate([i[None] for i in list_of_arrays],axis=0)[...,None].shape
Out[35]: (2, 3, 4, 1)

假设您将数组放在某种容器中(您可以始终将它们放在容器中):

>>> ax = [np.random.randint(0, 10, (3,3)) for _ in range(4)]
>>> ax
[array([[0, 3, 1],
       [4, 2, 4],
       [2, 2, 8]]), array([[8, 4, 6],
       [7, 1, 4],
       [8, 9, 8]]), array([[6, 3, 8],
       [4, 6, 8],
       [2, 2, 9]]), array([[1, 8, 1],
       [0, 9, 2],
       [9, 2, 3]])]

因此,您可以使用np.concatenate,但您也必须重塑:

>>> final = np.concatenate([arr.reshape(1, 3,3,1) for arr in ax], axis=0)

结果是:

>>> final.shape
(4, 3, 3, 1)
>>> final
array([[[[0],
         [3],
         [1]],

        [[4],
         [2],
         [4]],

        [[2],
         [2],
         [8]]],


       [[[8],
         [4],
         [6]],

        [[7],
         [1],
         [4]],

        [[8],
         [9],
         [8]]],


       [[[6],
         [3],
         [8]],

        [[4],
         [6],
         [8]],

        [[2],
         [2],
         [9]]],


       [[[1],
         [8],
         [1]],

        [[0],
         [9],
         [2]],

        [[9],
         [2],
         [3]]]])
>>>

编辑

灵感来源于@Divakar,更加通用:

np.concatenate([arr[None,..., None] for arr in ax], axis=0)

可以将axis参数添加到np.stack以指定要沿哪个轴堆叠:

arrs = [np.random.rand(256, 256) for i in range(11)]
out = np.stack(arrs, axis=0)
out.shape
# (11, 256, 256)

(请注意,轴默认为零)。你知道吗

如果需要在形状的末尾添加一个,那么使用newaxis

out[..., np.newaxis].shape
(11, 256, 256, 1)

相关问题 更多 >