没有内存分配的 numpy tile

numpy tile without memory allocation

我正在考虑使用 np.tile 但不为新矩阵分配内存的方法。有可能实现这一目标的方法吗?

有点啰嗦,求的功能如下:

a = np.random.rand(4,)
b = np.random.rand(8,)
c = np.tile(a,2) + b # this generate a memory copy anyhow

我想避免np.tile的内存拷贝。

感谢任何帮助。

c = (b.reshape(2,4)+a).ravel()

reshape 和 ravel 都是视图,所以(我认为)唯一的新数组是由求和产生的。实际上,我正在将 b 更改为可以使用 a.

广播的形状

即使在这个小问题中,这也明显更快。


broadcast_array让您分步进行广播

In [506]: b1,a1 = np.broadcast_arrays(b.reshape(2,4),a)  

a1是一个视图,如图数据缓冲区指针

In [507]: a1.__array_interface__['data']
Out[507]: (164774704, False)
In [508]: a.__array_interface__['data']
Out[508]: (164774704, False)

总和

In [509]: a1+b1
Out[509]: 
array([[ 2.04663934,  1.02951915,  1.30616273,  1.75154236],
       [ 1.79237632,  1.08252741,  1.17031265,  1.2675438 ]])

a1 实际上已平铺而无需复制

In [511]: a1.shape
Out[511]: (2, 4)
In [512]: a1.strides
Out[512]: (0, 8)

查看 np.lib.stride_tricks.py 文件以了解有关此类广播的更多详细信息。 np.lib.stride_tricks.as_strided 是基础函数,可让您构建具有新形状和步幅的视图。它在 SO 上最常用于构造滑动 windows.