【问题标题】:numpy tile without memory allocation没有内存分配的numpy tile
【发布时间】:2015-10-01 21:15:52
【问题描述】:

我正在考虑一种使用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的内存副本。

感谢任何帮助。

【问题讨论】:

    标签: python numpy memory matrix tile


    【解决方案1】:
    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 上最常用于构建滑动窗口。

    【讨论】:

      猜你喜欢
      • 2011-09-26
      • 2013-02-24
      • 2018-04-02
      • 1970-01-01
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多