累计加成(单位:numpy)

2024-10-01 07:42:42 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使循环更快?你知道吗

import numpy as np

# naively small input data
image = np.array( [[2,2],[2,2]] )
polarImage = np.array( [[0,0],[0,0]] )
a = np.array( [[0,0],[0,1]] )
r = np.array( [[0,0],[0,1]] )

# TODO - this loop is too slow
it = np.nditer(image, flags=['multi_index'])
while not it.finished:
  polarImage[ a[it.multi_index],r[it.multi_index] ] += it[0]
  it.iternext()

print polarImage

# this is fast but doesn't cumulate the results!
polarImage = np.array( [[0,0],[0,0]] )
polarImage[a,r]+= image

print polarImage

第一次打印返回:

[[6 0]
 [0 2]]

第二条:

[[2 0]
 [0 2]]

通过累积加法,我的意思是有时两个或多个来自图像的值必须加到极化的一个单元格中


Tags: imageimportnumpyindexisasnpit
1条回答
网友
1楼 · 发布于 2024-10-01 07:42:42

在这种情况下,nditer的使用模糊了过程,而没有提高速度。我们更习惯于看到双循环:

In [670]: polarImage=np.zeros_like(image)
In [671]: for i in range(2):
    for j in range(2):
        polarImage[a[i,j],r[i,j]] += image[i,j]

In [672]: polarImage
Out[672]: 
array([[6, 0],
       [0, 2]])

polarImage[a,r]+= image由于缓冲问题而无法工作。(0,0)索引对使用了3次。有一种ufunc方法专门用于这种情况,at。它执行无缓冲操作;很可能使用与第一个示例相同的nditer,但在编译代码中。你知道吗

In [676]: polarImage=np.zeros_like(image)
In [677]: np.add.at(polarImage, (a,r), image)
In [678]: polarImage
Out[678]: 
array([[6, 0],
       [0, 2]])

相关问题 更多 >