Home > OS >  More Numpy Vectorization instead of using nested loops
More Numpy Vectorization instead of using nested loops

Time:12-01

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

CodePudding user response:

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.

  • Related