【问题标题】:Vectorizing for loop with repeated indices in python在python中使用重复索引矢量化for循环
【发布时间】:2016-04-26 01:20:35
【问题描述】:

我正在尝试优化一个被多次调用(数百万次)的 sn-p,因此任何类型的速度改进(希望删除 for 循环)都会很棒。

我正在计算第 j 个粒子与所有其他粒子的相关函数

C_j(|r-r'|) = sqrt(E((s_j(r')-s_k(r))^2)) 在 k 上平均。

我的想法是有一个变量 corrfun 将数据分箱到一些箱中(r,在其他地方定义)。我找到每个 s_k 属于 r 的哪个 bin,并将其存储在 ind 中。所以 ind[0] 是 j=0 点对应的 r 的索引(因此也是 corrfun)。多个点可以落入同一个 bin(实际上我希望 bin 足够大以包含多个点)所以我将所有 (s_j(r')-s_k(r))^2 加在一起,然后除以该 bin 中的点(存储在变量 rw 中)。我最终为此编写的代码如下(np 用于 numpy):

for k, v in enumerate(ind):
        if j==k:
            continue
        corrfun[v] += (s[k]-s[j])**2
        rw[v] += 1
rw2 = rw
rw2[rw < 1] = 1
corrfun = np.sqrt(np.divide(corrfun, rw2))

注意,rw2 业务是因为我想避免除以 0 的问题,但我确实返回了 rw 数组,并且我希望能够区分 rw=0 和 rw=1 元素。也许还有一个更优雅的解决方案。

有没有办法让 for 循环更快?虽然我不想添加自我交互 (j==k),但我什至可以进行自我交互,如果这意味着我可以获得更快的计算速度(ind 的长度 ~ 1E6 所以自我交互可能无论如何都无关紧要)。

谢谢!

伊利亚

编辑:

这是完整的代码。请注意,在完整代码中,我也对 j 进行平均。

import numpy as np

def twopointcorr(x,y,s,dr):

    width = np.max(x)-np.min(x)
    height = np.max(y)-np.min(y)

    n = len(x)

    maxR = np.sqrt((width/2)**2 + (height/2)**2)

    r = np.arange(0, maxR, dr)
    print(r)
    corrfun = r*0
    rw = r*0
    print(maxR)
    ''' go through all points'''
    for j in range(0, n-1):
        hypot = np.sqrt((x[j]-x)**2+(y[j]-y)**2)
        ind = [np.abs(r-h).argmin() for h in hypot]

        for k, v in enumerate(ind):
            if j==k:
                continue
            corrfun[v] += (s[k]-s[j])**2
            rw[v] += 1

    rw2 = rw
    rw2[rw < 1] = 1
    corrfun = np.sqrt(np.divide(corrfun, rw2))
    return r, corrfun, rw

我通过以下方式调试测试

from twopointcorr import twopointcorr
import numpy as np
import matplotlib.pyplot as plt
import time

n=1000
x = np.random.rand(n)
y = np.random.rand(n)
s = np.random.rand(n)

print('running two point corr functinon')

start_time = time.time()
r,corrfun,rw = twopointcorr(x,y,s,0.1)
print("--- Execution time is %s seconds ---" % (time.time() - start_time))

fig1=plt.figure()
plt.plot(r, corrfun,'-x')

fig2=plt.figure()
plt.plot(r, rw,'-x')
plt.show()

同样,主要问题是在真实数据集 n~1E6 中。当然,我可以重新采样以使其更小,但我很想真正浏览数据集。

【问题讨论】:

  • 你能提供一个完整的程序,包括设置步骤吗?
  • 当然,我现在将编辑完整的帖子。好的,代码现在已经启动了
  • 谢谢。顺便说一句,为什么是range(0, n-1) 而不是range(0, n)?
  • 这可能用于add.at - 通常添加的无缓冲版本。 docs.scipy.org/doc/numpy-1.10.1/reference/generated/…

标签: python for-loop numpy enumerate


【解决方案1】:

下面是使用广播、hypot、round、bincount 去除所有循环的代码:

def twopointcorr2(x, y, s, dr):
    width = np.max(x)-np.min(x)
    height = np.max(y)-np.min(y)
    n = len(x)
    maxR = np.sqrt((width/2)**2 + (height/2)**2)
    r = np.arange(0, maxR, dr)    
    osub = lambda x:np.subtract.outer(x, x)

    ind = np.clip(np.round(np.hypot(osub(x), osub(y)) / dr), 0, len(r)-1).astype(int)
    rw = np.bincount(ind.ravel())
    rw[0] -= len(x)
    corrfun = np.bincount(ind.ravel(), (osub(s)**2).ravel())
    return r, corrfun, rw

为了比较,我将您的代码修改如下:

def twopointcorr(x,y,s,dr):
    width = np.max(x)-np.min(x)
    height = np.max(y)-np.min(y)

    n = len(x)

    maxR = np.sqrt((width/2)**2 + (height/2)**2)

    r = np.arange(0, maxR, dr)
    corrfun = r*0
    rw = r*0
    for j in range(0, n):
        hypot = np.sqrt((x[j]-x)**2+(y[j]-y)**2)
        ind = [np.abs(r-h).argmin() for h in hypot]
        for k, v in enumerate(ind):
            if j==k:
                continue
            corrfun[v] += (s[k]-s[j])**2
            rw[v] += 1

    return r, corrfun, rw        

这是检查结果的代码:

import numpy as np

n=1000
x = np.random.rand(n)
y = np.random.rand(n)
s = np.random.rand(n)

r1, corrfun1, rw1 = twopointcorr(x,y,s,0.1)
r2, corrfun2, rw2 = twopointcorr2(x,y,s,0.1)

assert np.allclose(r1, r2)
assert np.allclose(corrfun1, corrfun2)
assert np.allclose(rw1, rw2)        

以及 %timeit 结果:

%timeit twopointcorr(x,y,s,0.1)
%timeit twopointcorr2(x,y,s,0.1)    

输出:

1 loop, best of 3: 5.16 s per loop
10 loops, best of 3: 134 ms per loop

【讨论】:

  • 非常感谢,这个工作完美,速度最快
  • 不错——尤其是使用np.hypot() 和ravel() 是对我的回答的改进。
【解决方案2】:

您在我的系统上运行的原始代码大约需要 5.7 秒。我完全矢量化了内部循环并让它在 0.39 秒内运行。只需将您的“遍历所有点”循环替换为:

    points = np.column_stack((x,y))
    hypots = scipy.spatial.distance.cdist(points, points)
    inds = np.rint(hypots.clip(max=maxR) / dr).astype(np.int)

    # go through all points            
    for j in range(n): # n.b. previously n-1, not sure why
        ind = inds[j]

        np.add.at(corrfun, ind, (s - s[j])**2)

        np.add.at(rw, ind, 1)
        rw[ind[j]] -= 1 # subtract self                                                                                 

第一个观察结果是您的 hypot 代码正在计算 2D 距离,因此我将其替换为来自 SciPy 的 cdist 以在一次调用中完成所有操作。第二个是内部for 循环很慢,感谢@hpaulj 的富有洞察力的评论,我也使用np.add.at() 对其进行了矢量化。


因为你也问过如何向量化内循环,所以我后来做了。现在运行需要 0.25 秒,总加速超过 20 倍。这是最终代码:

    points = np.column_stack((x,y))
    hypots = scipy.spatial.distance.cdist(points, points)
    inds = np.rint(hypots.clip(max=maxR) / dr).astype(np.int)

    sn = np.tile(s, (n,1)) # n copies of s                                                                              
    diffs = (sn - sn.T)**2 # squares of pairwise differences
    np.add.at(corrfun, inds, diffs)

    rw = np.bincount(inds.flatten(), minlength=len(r))
    np.subtract.at(rw, inds.diagonal(), 1) # subtract self

与上面的单循环版本相比,这使用了更多内存,但确实产生了显着的加速。

【讨论】:

  • 谢谢,我试试这个。另外,如果不是太难,你能展示如何消除外循环吗?问题是 n^2,所以可能真正的问题比测试耗时许多数量级。
  • @Ilya:我现在已经将它完全矢量化了——请参阅更新的答案。这并不容易。请让我知道它在全尺寸的真实数据上给你带来了多大的加速——我很想知道!
  • John Zwinck:感谢您的帮助,您的版本大约需要 240 毫秒,@HYRY 版本大约需要 100 毫秒!我还没有准备好处理所有数据(而且我可能仍然需要二次抽样,因为对于 1E6 数据集和更精细的博士,这个概率意味着几天的计算......),但我会发布一些东西当我做!再次感谢您的帮助!
【解决方案3】:

好的,事实证明,外部产品的内存非常昂贵,但是,使用@HYRY 和@JohnZwinck 的答案,我能够编写在内存中仍然大致线性的代码并且计算速度很快(0.5 秒为测试用例)

import numpy as np

def twopointcorr(x,y,s,dr,maxR=-1):

    width = np.max(x)-np.min(x)
    height = np.max(y)-np.min(y)

    n = len(x)

    if maxR < dr:
        maxR = np.sqrt((width/2)**2 + (height/2)**2)

    r = np.arange(0, maxR+dr, dr)

    corrfun = r*0
    rw = r*0


    for j in range(0, n):

        ind = np.clip(np.round(np.hypot(x[j]-x,y[j]-y) / dr), 0, len(r)-1).astype(int)
        np.add.at(corrfun, ind, (s - s[j])**2)
        np.add.at(rw, ind, 1)

    rw[0] -= n

    corrfun = np.sqrt(np.divide(corrfun, np.maximum(rw,1)))
    r=np.delete(r,-1)
    rw=np.delete(rw,-1)
    corrfun=np.delete(corrfun,-1)
    return r, corrfun, rw

【讨论】:

    猜你喜欢
    • 2017-07-22
    • 2017-11-15
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-01
    • 2019-12-02
    • 1970-01-01
    相关资源
    最近更新 更多