【发布时间】:2017-02-25 10:10:30
【问题描述】:
我现在要做的是:
x = x[:, None, None, None, None, None, None, None, None, None]
基本上,我想将我的 Numpy 数组扩展 9 个维度。或者一些 N 维数,其中 N 可能事先不知道!
有没有更好的方法来做到这一点?
【问题讨论】:
标签: python arrays numpy multidimensional-array
我现在要做的是:
x = x[:, None, None, None, None, None, None, None, None, None]
基本上,我想将我的 Numpy 数组扩展 9 个维度。或者一些 N 维数,其中 N 可能事先不知道!
有没有更好的方法来做到这一点?
【问题讨论】:
标签: python arrays numpy multidimensional-array
另一种方法是reshaping -
x.reshape((-1,) + (1,)*N) # N is no. of dims to be appended
所以,基本上对于对应于单件维度的None's,我们沿这些暗角使用长度为1 的形状。对于第一个轴,我们使用-1 的形状来将所有元素推入。
示例运行 -
In [119]: x = np.array([2,5,6,4])
In [120]: x.reshape((-1,) + (1,)*9).shape
Out[120]: (4, 1, 1, 1, 1, 1, 1, 1, 1, 1)
【讨论】:
x.reshape((1,) + x.shape + (1,)*(N-1)) 我在向我的图像添加通道时需要这个作为最后一个维度,并通过添加第一个维度使其成为一批图像。
要缩写表达式(并使其适用于在运行时选择的任意维度),您可以即时生成索引:
x = x[(slice(None),)+(None,)*9]
如果你想把你的切片放到不同的位置,可以相应地调整索引元组。
请注意,在性能方面不会有任何好处。这只是更简洁的写作,可能比写出Nones 更难读
此外,重塑解决方案具有相似的性能。
【讨论】: