如何优化以下循环代码? [英] How to optimise the following for loop code?
本文介绍了如何优化以下循环代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个非常大的数据集,并且正在使用以下代码. 计算花费了太多时间,我想减少迭代次数.
I have a very large dataset and I am using following code. It's taking too much time for computation and I want to reduce number of iterations.
如何提高代码的性能?
import numpy as np
Z=np.asarray([[1,2],
[3,4],
[5,6],
[7,8]])
R=np.asarray([[1,2,3],
[4,5,6]])
AL=np.asarray([[1,2,3],
[4,5,6]])
X=np.asarray([[1,2,3],
[4,5,6],
[7,8,9],
[10,11,12]])
N = 4
M = 2
D = 3
result = np.ones([N, D])
for i in range(N):
for l in range(D):
temp=[]
for j in range(M):
temp.append(Z[i][j]*(R[j][l]+AL[j][l]*X[i][l]))
result[i][l] = np.sum(temp)
print(result)
输出为:
array([[ 18., 36., 60.],
[ 95., 156., 231.],
[232., 360., 510.],
[429., 648., 897.]])
推荐答案
使用numpy
时,更喜欢使用矩阵和数组运算,而不是for
迭代.性能大大提高.
When using numpy
, prefer using matrix and array operations instead of for
iterations. The performance is drastically better.
您的解决方案可以写为:
Your solution can be written as:
result = Z.dot(R) + Z.dot(AL) * X
输出:
array([[ 18., 36., 60.],
[ 95., 156., 231.],
[232., 360., 510.],
[429., 648., 897.]])
这篇关于如何优化以下循环代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文