python - Numpy 矢量化以提高性能

标签 python numpy

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

我有两个向量,形状为 (200,) 的 TDOA_values 和形状为 (257,) 的 __Frequency_bins__

现在我想使用这些向量的元素来填充我的“空白”矩阵temp_gcc_results 其定义如下: temp_gcc_results = np.zeros((len(TDOA_values), len(__Frequency_bins__))) 该数组的形状为 (200, 257)。

现在,我尝试通过为 __Frequency_bins__ 的每个元素计算 TDOA_values 的每个元素来填充 temp_gcc_results 的每个单元格:

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[:, :] 

关于python - Numpy 矢量化以提高性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59566618/

相关文章:

python - Numpy:为矩阵的每一列选择特定行的值

python - 使用 beautifulsoup 将 td 标签内的文本与粗体标签分离

python - Pandas 数据框错误 'StringArray requires a sequence of strings or pandas.NA'

python - Numpy:数组项的测试高于某个值,连续 x 次?

python - 如何计算多项式线性回归中的误差?

python - 如何将 numpy 数组转换为标准 TensorFlow 格式?

Python 3.4 asyncio 任务没有完全执行

python - Pandas 按字符串过滤

python - 速度较慢的 numpy.argmax/argmin 的更快替代品

python - 无法设置 Flask_sqlalchemy 的池大小