[英]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.计算花费了太多时间,我想减少迭代次数。
How can I improve the code's performance?如何提高代码的性能?
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)
Output is: Output 是:
array([[ 18., 36., 60.],
[ 95., 156., 231.],
[232., 360., 510.],
[429., 648., 897.]])
When using numpy
, prefer using matrix and array operations instead of for
iterations.使用numpy
时,更喜欢使用矩阵和数组运算for
不是迭代。 The performance is drastically better.性能要好得多。
Your solution can be written as:您的解决方案可以写成:
result = Z.dot(R) + Z.dot(AL) * X
Output: Output:
array([[ 18., 36., 60.],
[ 95., 156., 231.],
[232., 360., 510.],
[429., 648., 897.]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.