python - 嵌套循环中的向量化操作 : Python

标签 python numpy vectorization nested-loops compiler-optimization

我有 2D numpy 数组,我需要两个嵌套循环来迭代它的每个元素。我想对嵌套循环进行一些矢量化,但我不断收到错误消息,

j= np.arange (0,x.shape [1])
IndexError: tuple index out of range

这些是原始的嵌套循环:

for k in range(A.shape[0]):
        for j in range(A.shape[1]):
            A[k,j] = method1(x[k],x[j],a,c0,c1)

这就是我尝试根据这个答案进行矢量化的方式,https://codereview.stackexchange.com/questions/17702/python-numpy-running-15x-slower-than-matlab-am-i-using-numpy-effeciently ,

j= np.arange (0, A.shape [1])
    for k in range(A.shape[0]):

            A[k,j] = method1(x[k],x[j],a,c0,c1)

我尝试更改 np.arange 中的索引,但没有成功。

谁能告诉我如何解决这个问题?

谢谢。

编辑:通过@ajcr评论,我的错误在这一行,j= np.arange (0,x.shape [1]),我应该使用二维数组“A”的列数作为j = np.arange(0,A.shape[1]),但我错误地使用了一维数组x,因此出现错误。现在一切正常。

最佳答案

由于您不提供该功能本身,所以很难给您答案。如果可以对计算进行矢量化,那么这将是正确的选择。否则,您可以使用np.vectorize:

import numpy as np

def my_fun(x,y,a,b):
    if x > y:
        return a*x**2 + y
    else:
        return b*x**2 + a*y

vec_fun = np.vectorize(my_fun)
x = np.random.rand(100000)
y = np.random.rand(100000)

%%timeit
for xx,yy in zip(x,y):
    my_fun(xx,yy,1,2)

10 个循环,3 个循环中最好的:每个循环 138 毫秒

%%timeit
    vec_fun(x,y,1,2)

10 个循环,3 个循环中最好的:每个循环 65.4 毫秒

如果您只是循环输入参数列表,则可以使用 multiprocessing.Pool 来利用所有核心。

编辑:正如 BlackCat 指出的那样,np.vectorize 函数可能不会加快速度。如果是这种情况,我能想到的唯一解决方案是使用所有核心或切换到 Cython。

关于python - 嵌套循环中的向量化操作 : Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31113538/

相关文章:

python - Numpy 性能差异取决于数值

Python 检查数组中元素的值

matlab - 创建水平拉伸(stretch)的上三角矩阵

python - 数组数组(Python/NumPy)

python - 使用sklearn时Python出现内存错误

python - 大距离矩阵的内存高效存储

python - 如何有效地获取 DataFrame 行的索引,这些行满足特定的累积条件?

arrays - 如何在不使用循环的情况下按每个组的结束索引拆分向量?

python - 如何应用以调用者作为参数的函数

python - 如何在Python中创建包和模块?