[英]Numpy Vectorization to improve performance
我目前正在尝试对我的代码进行矢量化以减少其处理时间,并且在尝试广播时发生了错误。
我有两个向量, TDOA_values
用的(200)的形状和__frequency_bins__
用的(257)的形状。
现在我想使用这些向量的元素来填充我的“空白”矩阵temp_gcc_results
其定义如下: temp_gcc_results = np.zeros((len(TDOA_values), len(__frequency_bins__)))
这个数组的形状为 (200, 257 )。
现在,我试图通过为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
不幸的是,执行此代码会导致此错误:
operands could not be broadcast together with shapes (200,) (257,)
我现在的问题是我不明白为什么 Python 尝试广播而不是用公式中的值替换零。
谢谢你的帮助!
你需要使用 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
您的错误发生在这里,在两个具有不匹配形状的数组相乘时:
TDOA_values * __frequency_bins__
不是在将结果分配给:
temp_gcc_results[:, :]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.