python - python 3 如何使用带有 numpy linalg norm 的多线程
问题描述
我正在使用带有np.linalg.norm的 python3来计算矩阵中行的范数 (norm(axis=1)),有没有一种简单的方法,只使用 np 使其使用多线程或多核运行?
解决方案
我们可以使用支持多核处理的numexpr
模块,像这样 -
import numexpr as ne
def linalg_norm(a):
sq_norm = ne.evaluate('sum(a**2,1)')
return ne.evaluate('sqrt(sq_norm)')
要沿任何其他轴执行范数减少,1
请在评估表达式中替换为该轴编号 - 'sum(a**2,1)'
。
样品运行 -
In [34]: np.random.seed(0)
...: a = np.random.rand(4,5)
In [35]: np.linalg.norm(a,axis=1)
Out[35]: array([1.28545589, 1.57467272, 1.4460319 , 1.43656019])
In [36]: linalg_norm(a)
Out[36]: array([1.28545589, 1.57467272, 1.4460319 , 1.43656019])
Related post
关于如何控制多核功能。
为了完整起见,可以提出很少的替代方案。
一个有效的解决方案是np.einsum
-
In [39]: np.sqrt(np.einsum('ij,ij->i',a, a))
Out[39]: array([1.28545589, 1.57467272, 1.4460319 , 1.43656019])
与np.matmul/@ operator on Python 3.x
-
In [6]: np.sqrt(np.matmul(a[:,None],a[:,:,None])[:,0,0])
Out[6]: array([1.28545589, 1.57467272, 1.4460319 , 1.43656019])
In [7]: np.sqrt((a[:,None] @ a[:,:,None])[:,0,0])
Out[7]: array([1.28545589, 1.57467272, 1.4460319 , 1.43656019])
推荐阅读
- docker - 使用 Mocha 和 Node 在 Docker 中进行 VSCode 调试
- websocket - 使用 Apache Camel AHC-WS Websocket 组件进行 JWT 不记名令牌身份验证
- google-apps-script - 脚本无法正确打开另一个电子表格
- c# - 通过 Winform 应用程序访问浏览器 LocalStorage
- android-studio - Android 虚拟设备组件
- java - 如何从 ArrayAdapter 列表开始新的片段?
- xslt - 如何使用“func:padStr 添加前导空格
- html - 如果 URL 以 / 结尾,则 .htaccess 中的 UTF-8 无效
- wordpress - 安装了 root/sage,但在执行 npm run start 后出现警告
- gnu - 使用usrp b2130和Gnu radio设计网络分析仪