【问题标题】:Alternative to numpy roll without copying array无需复制数组即可替代 numpy roll
【发布时间】:2016-06-25 06:43:53
【问题描述】:

我正在执行类似以下代码的操作,但我对 np.roll() 函数的性能不满意。我将 baseArray 和 otherArray 相加,其中 baseArray 在每次迭代中滚动一个元素。但是当我滚动它时我不需要 baseArray 的副本,我更喜欢这样的视图,例如,当我将 baseArray 与其他数组相加时,如果 baseArray 滚动两次,那么 basearray 的第 2 个元素与第 0 个元素相加otherArray,baseArray 的第 3 个元素与 otherArray 的第一个元素等相加。

I.E.达到与 np.roll() 相同的结果,但不复制数组。

import numpy as np
from numpy import random
import cProfile

def profile():
    baseArray = np.zeros(1000000)
    for i in range(1000):
        baseArray= np.roll(baseArray,1)
        otherArray= np.random.rand(1000000)
        baseArray=baseArray+otherArray

cProfile.run('profile()')

输出(注意第 3 行 - 滚动功能):

         9005 function calls in 26.741 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    5.123    5.123   26.740   26.740 <ipython-input-101-9006a6c0d2e3>:5(profile)
        1    0.001    0.001   26.741   26.741 <string>:1(<module>)
     1000    0.237    0.000    8.966    0.009 numeric.py:1327(roll)
     1000    0.004    0.000    0.005    0.000 numeric.py:476(asanyarray)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
     1000   12.650    0.013   12.650    0.013 {method 'rand' of 'mtrand.RandomState' objects}
     1000    0.005    0.000    0.005    0.000 {method 'reshape' of 'numpy.ndarray' objects}
     1000    6.390    0.006    6.390    0.006 {method 'take' of 'numpy.ndarray' objects}
     2000    1.345    0.001    1.345    0.001 {numpy.core.multiarray.arange}
     1000    0.001    0.000    0.001    0.000 {numpy.core.multiarray.array}
     1000    0.985    0.001    0.985    0.001 {numpy.core.multiarray.concatenate}
        1    0.000    0.000    0.000    0.000 {numpy.core.multiarray.zeros}
        1    0.000    0.000    0.000    0.000 {range}

【问题讨论】:

    标签: python performance numpy


    【解决方案1】:

    我的函数profile3() 快了四倍。在累积期间,它使用带递增移位的切片索引而不是任何滚动。在循环之后,单次滚动 1000 个元素会产生与其他函数相同的对齐方式。

    import numpy as np
    from timeit import timeit
    
    def profile1(seed=0):
        gen = np.random.RandomState(seed)
        otherArray= gen.rand(1000000)           # outside the loop after Marcel's comment above
        baseArray = np.zeros(1000000)
        for i in range(1000):
            baseArray= np.roll(baseArray,1)
            baseArray=baseArray+otherArray
        return baseArray
    
    def profile2(seed=0):
        gen = np.random.RandomState(seed)
        otherArray= gen.rand(1000000)
        baseArray = np.zeros(1000000)
        for i in range(1000):
            tmp1 = baseArray[:-1]               # view of the first n-1 elements
            tmp2 = baseArray[-1]                # copy of the last element
            baseArray[1:]=tmp1+otherArray[1:]   # write the last n-1 elements
            baseArray[0]=tmp2+otherArray[0]     # write the first element
        return baseArray
    
    def profile3(seed=0):
        gen = np.random.RandomState(seed)
        otherArray= gen.rand(1000000)
        baseArray = np.zeros(1000000)
        for i in range(1,1001): # use % or itertools.cycle if range > shape
            baseArray[:-i] += otherArray[i:]
            baseArray[-i:] += otherArray[:i]
        return np.roll(baseArray,1000)
    
    print(timeit(profile1,number=1))  # 7.0
    print(timeit(profile2,number=1))  # 4.7
    print(timeit(profile3,number=1))  # 1.2
    
    x2 = profile2()
    x3 = profile3()
    print(np.allclose(x2, x3))  # True
    

    【讨论】:

      【解决方案2】:

      我很确定避免复制 due to the way in which numpy arrays are represented internally 是不可能的。一个数组由一个连续的内存地址块加上一些元数据组成,这些元数据包括数组维度、项目大小以及每个维度的元素之间的分隔(“步幅”)。向前或向后“滚动”每个元素需要沿同一维度具有不同长度的步幅,这是不可能的。


      也就是说,您可以避免使用切片索引复制baseArray 中除一个以外的所有元素:

      import numpy as np
      
      def profile1(seed=0):
          gen = np.random.RandomState(seed)
          baseArray = np.zeros(1000000)
          for i in range(1000):
              baseArray= np.roll(baseArray,1)
              otherArray= gen.rand(1000000)
              baseArray=baseArray+otherArray
          return baseArray
      
      def profile2(seed=0):
          gen = np.random.RandomState(seed)
          baseArray = np.zeros(1000000)
          for i in range(1000):
              otherArray = gen.rand(1000000)
              tmp1 = baseArray[:-1]               # view of the first n-1 elements
              tmp2 = baseArray[-1]                # copy of the last element
              baseArray[1:]=tmp1+otherArray[1:]   # write the last n-1 elements
              baseArray[0]=tmp2+otherArray[0]     # write the first element
          return baseArray
      

      这些将给出相同的结果:

      In [1]: x1 = profile1()
      
      In [2]: x2 = profile2()
      
      In [3]: np.allclose(x1, x2)
      Out[3]: True
      

      实际上,性能并没有太大差异:

      In [4]: %timeit profile1()
      1 loop, best of 3: 23.4 s per loop
      
      In [5]: %timeit profile2()
      1 loop, best of 3: 17.3 s per loop
      

      【讨论】:

      • 谢谢。只是评论:实际上性能存在差异,因为您测量的 23.4 和 17.3 秒包括生成随机数(我在现实世界的算法中并没有真正这样做),如果您只是比较 np.roll() 性能,例如通过在 for 循环之前创建 otherArray,那么对我来说时间是 14 秒对 4 秒。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-25
      • 2013-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多