简体   繁体   English

Numpy:最后一维的堆栈数组

[英]Numpy: stack array by the last dimension

Suppose I have 3 numpy arrays a , b , c , of the same shape, say假设我有 3 个相同形状的 numpy 数组a , b , c ,比如说

a.shape == b.shape == c.shape == (7,9)

Now I'd like to create a 3-dimensional array of size (7,9,3) , say x , such that现在我想创建一个大小为(7,9,3)的 3 维数组,比如x ,这样

x[:,:,0] == a
x[:,:,1] == b
x[:,:,2] == c

What is the "pythonic" way of doing it (perhaps in one line)?这样做的“pythonic”方式是什么(也许在一行中)?

Thanks in advance!提前致谢!

There's a function that does exactly that: numpy.dstack ("d" for "depth").有一个函数可以做到这一点: numpy.dstack (“d”代表“深度”)。 For example:例如:

In [10]: import numpy as np

In [11]: a = np.ones((7, 9))

In [12]: b = a * 2

In [13]: c = a * 3

In [15]: x = np.dstack((a, b, c))

In [16]: x.shape
Out[16]: (7, 9, 3)

In [17]: (x[:, :, 0] == a).all()
Out[17]: True

In [18]: (x[:, :, 1] == b).all()
Out[18]: True

In [19]: (x[:, :, 2] == c).all()
Out[19]: True

TL;DR:特尔;博士:

Use numpy.stack ( docs ), which joins a sequence of arrays along a new axis of your choice.使用numpy.stack ( docs ),它沿着您选择的新轴连接一系列数组。


Although @NPE answer is very good and cover many cases, there are some scenarios in which numpy.dstack isn't the right choice (I've just found that out while trying to use it).尽管@NPE 的回答非常好并且涵盖了很多情况,但在某些情况下numpy.dstack不是正确的选择(我刚刚在尝试使用它时发现了这一点)。 That's because numpy.dstack , according to the docs :这是因为numpy.dstack ,根据文档

Stacks arrays in sequence depth wise (along third axis).按顺序深度堆叠数组(沿第三轴)。

This is equivalent to concatenation along the third axis after 2-D arrays of shape (M,N) have been reshaped to (M,N,1) and 1-D arrays of shape (N,) have been reshaped to (1,N,1).这等效于在形状 (M,N) 的二维阵列被重新整形为 (M,N,1) 并且形状 (N,) 的一维阵列被重新整形为 (1, N,1)。

Let's walk through an example in which this function isn't desirable.让我们来看一个不希望使用此函数的示例。 Suppose you have a list with 512 numpy arrays of shape (3, 3, 3) and want to stack them in order to get a new array of shape (3, 3, 3, 512) .假设您有一个包含 512 个形状为(3, 3, 3) numpy 数组的列表,并且想要将它们堆叠起来以获得形状为(3, 3, 3, 512)的新数组。 In my case, those 512 arrays were filters of a 2D-convolutional layer.就我而言,这 512 个阵列是 2D 卷积层的过滤器。 If you use numpy.dstack :如果您使用numpy.dstack

>>> len(arrays_list)
512
>>> arrays_list[0].shape
(3, 3, 3)
>>> numpy.dstack(arrays_list).shape
(3, 3, 1536)

That's because numpy.dstack always stacks the arrays along the third axis!那是因为numpy.dstack总是沿着第三个轴堆叠数组! Alternatively, you should use numpy.stack ( docs ), which joins a sequence of arrays along a new axis of your choice:或者,您应该使用numpy.stack ( docs ),它沿着您选择的新轴连接一系列数组:

>>> numpy.stack(arrays_list, axis=-1).shape
(3, 3, 3, 512)

In my case, I passed -1 to the axis parameter because I wanted the arrays stacked along the last axis.就我而言,我将 -1 传递给axis参数,因为我希望数组沿最后一个轴堆叠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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