在 Matlab 中,我可以执行以下操作:
X = randn(25,25,25);
size(X(:,:))
ans =
25 625
我经常发现自己想要快速折叠数组的尾部维度,但不知道如何在 numpy 中执行此操作。
我知道我可以做到:
In [22]: x = np.random.randn(25,25,25)
In [23]: x = x.reshape(x.shape[:-2] + (-1,))
In [24]: x.shape
Out[24]: (25, 625)
但是x.reshape(x.shape[:-2] + (-1,))
很多不如简单地做 x
简洁(并且需要更多关于 x(:,:)
的信息) .
我显然已经尝试过类似的 numpy 索引,但效果不理想:
In [25]: x = np.random.randn(25,25,25)
In [26]: x[:,:].shape
Out[26]: (25, 25, 25)
关于如何以简洁的方式折叠数组的尾部维度有什么提示吗?
编辑:请注意,我关注的是生成的数组本身,而不仅仅是它的形状。我只使用 size()
和 x.shape
在上面的示例中指示数组是什么样的。
最佳答案
4d 或更高版本会发生什么情况?
octave:7> x=randn(25,25,25,25);
octave:8> size(x(:,:))
ans =
25 15625
您的 (:,:)
将其缩减为 2 个维度,并合并最后一个维度。最后一个维度是 MATLAB 自动添加和折叠维度的位置。
In [605]: x=np.ones((25,25,25,25))
In [606]: x.reshape(x.shape[0],-1).shape # like Joe's
Out[606]: (25, 15625)
In [607]: x.reshape(x.shape[:-2]+(-1,)).shape
Out[607]: (25, 25, 625)
您的 reshape
示例做了一些与 MATLAB 不同的事情,它只是折叠最后 2 个维度。像 MATLAB 一样将它折叠到 2 个维度是一个更简单的表达式。
MATLAB 之所以简洁,是因为您的需求符合它的假设。 numpy
等价物不是那么简洁,但给了你更多的控制权
例如,保留最后一个维度,或将维度 2 乘 2 合并:
In [608]: x.reshape(-1,x.shape[-1]).shape
Out[608]: (15625, 25)
In [610]: x.reshape(-1,np.prod(x.shape[-2:])).shape
Out[610]: (625, 625)
等效的 MATLAB 是什么?
octave:24> size(reshape(x,[],size(x)(2:end)))
ans =
15625 25
octave:31> size(reshape(x,[],prod(size(x)(3:end))))
关于python - 折叠 numpy 数组尾随维度的简单方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30780047/