假设我有一个2D numpy
数组A
,形状为(m, n)
。我想创建一个形状为(m, n, k)
的3D数组B
,这样B[:, :, l]
是任何片l
的{
np.tile(A, (m, n, k))
或者
^{pr2}$第一种方法似乎更简单,但我在np.tile
的文档中提到:
Note: Although tile may be used for broadcasting, it is strongly
recommended to use numpy's broadcasting operations and functions.
为什么会这样,这也是np.repeat
的问题吗?在
我的另一个担心是,如果m == n == k
,那么{
总之,我有两个问题:
np.tile
不是首选,并且在某些情况下m == n == k
会导致意外行为?在
使用“重复”在末尾添加新尺寸:
^{pr2}$使用“平铺”和“重复”在开始处添加新尺寸:
如果我们用平铺在最后一个维度上指定2个重复,则会产生不同的形状
注意
tile
关于在维度前面加上repeats元组的内容比形状大。在但是,如果在计算中使用了扩展数组(如注释中所述),则不需要进行完全重复的复制。可以使用正确形状的临时视图,利用
broadcasting
。在使用
None
(np.newaxis
),数组视图是(3,4,1)和(1,4,2)形状的,它们一起广播为(3,4,2)。在第二种情况下,我可以不使用None
,因为广播会自动添加。但是后面的None
是必需的。在要添加一维数组(最后一个维度):
两个基本广播步骤:
[None,....]
)这组计算说明了这一点:
缺少中间维度
有一种更“先进”的替代方案(但不一定更快):
假设要将shape-
(m, n)
数组和shape-(n, k)
数组都展开为形状(m, n, k)
并将它们相加。在这种情况下,您根本不需要物理扩展阵列;对齐轴和广播可以很好地工作:这不需要复制
A
和B
中的数据,并且应该比任何涉及物理拷贝的操作都快得多。在相关问题 更多 >
编程相关推荐