首页 > 解决方案 > 提高性能的 Numpy 矢量化

问题描述

我目前正在尝试对我的代码进行矢量化以减少其处理时间,并且在尝试广播时发生错误。

我有两个向量,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__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 会尝试广播而不是用公式中的值替换零。

谢谢你的帮助!

标签: pythonnumpy

解决方案


您需要使用 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[:, :] 

推荐阅读