python - 矢量化以实现性能

标签 python arrays numpy scipy vectorization

我想避免在以下代码中使用 for 循环来实现性能。矢量化适合这种问题吗?

a = np.array([[0,1,2,3,4],
              [5,6,7,8,9],
              [0,1,2,3,4],
              [5,6,7,8,9],
              [0,1,2,3,4]],dtype= np.float32)

temp_a = np.copy(a)

for i in range(1,a.shape[0]-1):
    for j in range(1,a.shape[1]-1):
        if a[i,j] > 3:
            temp_a[i+1,j] += a[i,j] / 5.
            temp_a[i-1,j] += a[i,j] / 5.
            temp_a[i,j+1] += a[i,j] / 5.
            temp_a[i,j-1] += a[i,j] / 5.
            temp_a[i,j]   -= a[i,j] * 4. / 5.
a = np.copy(temp_a)   

最佳答案

你基本上是在做卷积,对边界进行一些特殊处理。

请尝试以下操作:

from scipy.signal import convolve2d


# define your filter
f = np.array([[0.0, 0.2, 0.0],
              [0.2,-0.8, 0.2],
              [0.0, 0.2, 0.0]])

# select parts of 'a' to be used for convolution
b = (a * (a > 3))[1:-1, 1:-1]

# convolve, padding with zeros ('same' mode)
c = convolve2d(b, f, mode='same')

# add the convolved result to 'a', excluding borders
a[1:-1, 1:-1] += c

# treat the special cases of the borders
a[0, 1:-1] += .2 * b[0, :]
a[-1, 1:-1] += .2 * b[-1, :]
a[1:-1, 0] += .2 * b[:, 0]
a[1:-1, -1] += .2 * b[:, -1]

它给出了以下结果,这与嵌套循环相同。
[[  0.    2.2   3.4   4.6   4. ]
 [  6.2   2.6   4.2   3.   10.6]
 [  0.    3.4   4.8   6.2   4. ]
 [  6.2   2.6   4.2   3.   10.6]
 [  0.    2.2   3.4   4.6   4. ]]

关于python - 矢量化以实现性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48055971/

相关文章:

c - 如何从带有指针的函数返回数组

python - 将指定文本从索引替换为数组python中的另一个索引

python - Float16 在 numpy 中比 Float32 和 Float64 慢很多

python - 简单向量运算的优化 (python)

python - "Lambda function for the route not found"使用SAM在本地运行Golang函数出错?

python - 使用python分析抛硬币统计

python - Dropna 没有下降,fillna 没有填充,我的列表理解无法理解如何摆脱 nans (python)

javascript - 创建用于 ajax 函数的 ColdFusion 查询的 javascript 数组

javascript - 如何在基于 JS 的应用程序中使用 python

python - 加速有限差分模型