简体   繁体   中英

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:

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. The performance is drastically better.

Your solution can be written as:

result = Z.dot(R) + Z.dot(AL) * X

Output:

array([[ 18.,  36.,  60.],
       [ 95., 156., 231.],
       [232., 360., 510.],
       [429., 648., 897.]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM