[英]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,).我有两个向量, TDOA_values
用的(200)的形状和__frequency_bins__
用的(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).现在我想使用这些向量的元素来填充我的“空白”矩阵temp_gcc_results
其定义如下: temp_gcc_results = np.zeros((len(TDOA_values), len(__frequency_bins__)))
这个数组的形状为 (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
的每个元素计算TDOA_values
的每个元素的以下公式来填充TDOA_values
的每个单元__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.我现在的问题是我不明白为什么 Python 尝试广播而不是用公式中的值替换零。
Thanks for you help!谢谢你的帮助!
You need to use np.newaxis:你需要使用 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[:, :]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.