【发布时间】:2013-07-21 10:53:21
【问题描述】:
我对 Python 比较陌生,而且我有一个嵌套的 for 循环。由于 for 循环需要一段时间才能运行,我正在尝试找出一种方法来矢量化此代码,以便它可以更快地运行。
在这种情况下,coord 是一个 3 维数组,其中 coord[x, 0, 0] 和 coord[x, 0, 1] 是整数,而 coord[x, 0, 2] 是 0 或 1。 H是 SciPy 稀疏矩阵,x_dist、y_dist、z_dist 和 a 都是浮点数。
# x_dist, y_dist, and z_dist are floats
# coord is a num x 1 x 3 numpy array where num can go into the hundreds of thousands
num = coord.shape[0]
H = sparse.lil_matrix((num, num))
for i in xrange(num):
for j in xrange(num):
if (np.absolute(coord[i, 0, 0] - coord[j, 0, 0]) <= 2 and
(np.absolute(coord[i, 0, 1] - coord[j, 0, 1]) <= 1)):
x = ((coord[i, 0, 0] * x_dist + coord[i, 0, 2] * z_dist) -
(coord[j, 0, 0] * x_dist + coord[j, 0, 2] * z_dist))
y = (coord[i, 0, 1] * y_dist) - (coord[j, 0, 1] * y_dist)
if a - 0.5 <= np.sqrt(x ** 2 + y ** 2) <= a + 0.5:
H[i, j] = -2.7
我还了解到,使用 NumPy 进行广播虽然速度更快,但会导致临时数组使用大量内存。走矢量化路线还是尝试使用 Cython 之类的东西会更好吗?
【问题讨论】:
标签: python numpy scipy vectorization cython