python - 提高性能的 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 会尝试广播而不是用公式中的值替换零。
谢谢你的帮助!
解决方案
您需要使用 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[:, :]
推荐阅读
- caching - 为什么 Concrete5 网站在运行 c5:clear-cache 后回答错误 500?
- java - 我需要有关阅读来自 SQLite 的登录电子邮件的帮助
- python - 在python中发送击键SHIFT + PRINTSCREEN
- azure-pipelines - 在 VSTS 管道上运行时在赛普拉斯中滚动
- dart - Flutter 使用具有作用域模型的多个模型
- javascript - 在数据表服务器端获取第 0 行的请求未知参数“0”错误
- angular - 当使用回调方法时,ngx-clipboard 不会复制到剪贴板
- laravel - Laravel where('user_id') 似乎完全被忽略了
- ionic-framework - IONIC- Dex:将字节码转换为 dex 时出错:- targetCompatibility = '1.7' sourceCompatibility = '1.7'
- python-3.x - 在 Python 中使图形更长