简体   繁体   中英

Numpy Vectorization to improve performance

I am currently trying to vectorize my code to decrease its processing time and while trying a broadcasting error occured.

I have two vectors, TDOA_values with a shape of (200,) and __frequency_bins__ with a shape of (257,).

Now I want to use the elements of these vectors to fill my "blank" matrix temp_gcc_results which is defined like: temp_gcc_results = np.zeros((len(TDOA_values), len(__frequency_bins__))) this array has the shape (200, 257).

Now I am trying to fill each cell of temp_gcc_results by calculating the following formula for each element of TDOA_values for each element of __frequency_bins__ :

temp_gcc_results[:, :] = (Rxx12/abs(Rxx12) * np.exp(-2j * np.pi * TDOA_values * __frequency_bins__)).real

Unfortunately executing this code results in this error:

operands could not be broadcast together with shapes (200,) (257,) 

My problem now is that I do not understand why Python tries to broadcast instead of replacing the zeros with values from the formula.

Thanks for you help!

You need to use np.newaxis:

# array(m x n) = array(m x 1) * array(1 x n)

import numpy as np
Rxx12 = 1 # TODO, not specified in the question
TDOA_values = np.random.random(200)
__frequency_bins__ = np.random.random(257)
temp_gcc_results = np.zeros((len(TDOA_values), len(__frequency_bins__)))
temp_gcc_results[:, :] = (Rxx12/abs(Rxx12) * np.exp(-2j * np.pi * TDOA_values[:, np.newaxis] * __frequency_bins__[np.newaxis, :])).real

# You actually don"t need to initialize *temp_gcc_results* in your case
temp_gcc_results = (Rxx12/abs(Rxx12) * np.exp(-2j * np.pi * TDOA_values[:, np.newaxis] * __frequency_bins__[np.newaxis, :])).real

Your error occurs here, at the multiplication of two arrays with non-matching shapes:

TDOA_values * __frequency_bins__

Not at the assignment of the result to:

temp_gcc_results[:, :] 

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