首页 > 解决方案 > python 3 如何使用带有 numpy linalg norm 的多线程

问题描述

我正在使用带有np.linalg.norm的 python3来计算矩阵中行的范数 (norm(axis=1)),有没有一种简单的方法,只使用 np 使其使用多线程或多核运行?

标签: pythonpython-3.xmultithreadingnumpylinear-algebra

解决方案


我们可以使用支持多核处理的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])

推荐阅读