简体   繁体   中英

More Numpy Vectorization instead of using nested loops

I have all_data as a numpy array with the size of (2,601) , NUM_SAMPLES = 601 and NUM_CLUSTERS = 3 . Is there any vector form to build f (a (601,9) numpy array) than what using nested for-loops as follows?

f = np.empty((0,9), float)
for n in range(NUM_SAMPLES):
    f_n = np.array([[]])
    for m in range(NUM_CLUSTERS):
        f_n = np.hstack( (f_n , z_i(alldata[:,n], m).T))
    f = np.concatenate((f, f_n) , axis=0)

NOTE : when recalling function z_i(alldata[:,n], m) , it returns a (3,1) numpy array.

f is supposed to be 'F' in the following formula: formula of f

Because you have some function z_i in the middle of your loops, you're more or less stuck with loops. You don't need to do a bunch of really inefficient concats like you're doing, but your array size is so small it probably doesn't matter.

f = np.vstack((np.hstack((z_i(alldata[:,n], m).T for m in range(NUM_CLUSTERS)))
               for n in range(NUM_SAMPLES)))

If you really want this to run faster you have to look into z_i and change how that's working.

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