gpt4 book ai didi

python - 如何加速Python中的数组赋值?

转载 作者:行者123 更新时间:2023-12-01 04:14:15 25 4
gpt4 key购买 nike

我正在尝试在python中进行数组赋值,但是速度很慢,有什么办法可以加速吗?

simi_matrix_img = np.zeros((len(annot), len(annot)), dtype='float16')
for i in range(len(annot)):
for j in range(i + 1):
score = 0
times = 0
if i != j:
x_idx = [p1 for (p1, q1) in enumerate(annot[i]) if np.abs(q1 - 1) < 1e-5]
y_idx = [p2 for (p2, q2) in enumerate(annot[j]) if np.abs(q2 - 1) < 1e-5]

for idx in itertools.product(x_idx, y_idx):
score += simi_matrix_word[idx]
times += 1
simi_matrix_img[i, j] = score/times
else:
simi_matrix_img[i, j] = 1.0

“annot”是一个 numpy 数组。有什么办法可以加速吗?

最佳答案

我认为这一行的缩进是错误的:

            simi_matrix_img[i, j] = score/times

您希望在所有 product 迭代之后执行该分配。但由于这是最后一次执行的作业,因此结果将是相同的。

这是对代码的部分修改

def foo1(annot, simi_matrix_word):
N = annot.shape[0]
simi_matrix_img = np.zeros((N,N))
for i in range(N):
for j in range(i + 1):
if i != j:
x_idx = np.nonzero(annot[i])[0]
y_idx = np.nonzero(annot[j])[0]
idx = np.ix_(x_idx, y_idx)
# print(idx, simi_matrix_word[idx])
score = simi_matrix_word[idx].mean()
simi_matrix_img[i, j] = score
else:
simi_matrix_img[i, j] = 1.0
return simi_matrix_img

对于一个小测试用例,它返回相同的内容:

annot=np.array([[1,0,1],[0,1,1]])
simi_matrix_word = np.arange(12, dtype=float).reshape(3,4)
[[ 1. 0.]
[ 7. 1.]]

这消除了所有内部迭代。下一步将是减少外部迭代。例如,从 np.eye(N) 开始,然后迭代较低的三索引:

In [169]: np.eye(2)
Out[169]:
array([[ 1., 0.],
[ 0., 1.]])

In [170]: np.tril_indices(2,-1)
Out[170]: (array([1]), array([0]))

请注意,对于 2 行 annot,我们仅在 [1,0] 处计算一个分数

<小时/>

用 bool 索引替换非零:

def foo3(annot, simi_matrix_word):
N = annot.shape[0]
A = annot.astype(bool)
simi_matrix_img = np.eye(N,dtype=float)
for i,j in zip(*np.tril_indices(N,-1)):
score = simi_matrix_word[A[i],:][:,A[j]]
simi_matrix_img[i, j] = score.mean()
return simi_matrix_img

或者这可能会稍微加快索引速度:

def foo4(annot, simi_matrix_word):
N = annot.shape[0]
A = annot.astype(bool)
simi_matrix_img = np.eye(N,dtype=float)
for i in range(1,N):
x = simi_matrix_word[A[i],:]
for j in range(i):
score = x[:,A[j]]
simi_matrix_img[i, j] = score.mean()
return simi_matrix_img

由于 annot 每行的非零值数量可能不同,因此每个 score 求和的项数也不同。这强烈表明进一步的矢量化是不可能的。

关于python - 如何加速Python中的数组赋值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34522484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com