如何将 numpy.linalg.norm 应用于矩阵的每一行? [英] How to apply numpy.linalg.norm to each row of a matrix?
问题描述
我有一个二维矩阵,我想取每一行的范数.但是当我直接使用 numpy.linalg.norm(X)
时,它需要整个矩阵的范数.
I have a 2D matrix and I want to take norm of each row. But when I use numpy.linalg.norm(X)
directly, it takes the norm of the whole matrix.
我可以通过使用 for 循环获取每行的范数,然后获取每个 X[i]
的范数,但是因为我有 30k 行,所以需要很长时间.
I can take norm of each row by using a for loop and then taking norm of each X[i]
, but it takes a huge time since I have 30k rows.
有什么建议可以找到更快的方法吗?或者是否可以将 np.linalg.norm
应用于矩阵的每一行?
Any suggestions to find a quicker way? Or is it possible to apply np.linalg.norm
to each row of a matrix?
推荐答案
对于 numpy 1.9+
请注意,正如 perimosocordiae 所示,从 NumPy 1.9 版开始,np.linalg.norm(x,axis=1)
是计算 L2 范数的最快方法.
For numpy 1.9+
Note that, as perimosocordiae shows, as of NumPy version 1.9, np.linalg.norm(x, axis=1)
is the fastest way to compute the L2-norm.
如果您正在计算 L2 范数,您可以直接计算它(使用 axis=-1
参数沿行求和):
If you are computing an L2-norm, you could compute it directly (using the axis=-1
argument to sum along rows):
np.sum(np.abs(x)**2,axis=-1)**(1./2)
Lp 范数当然可以类似地计算.
Lp-norms can be computed similarly of course.
它比 np.apply_along_axis
快得多,但可能不那么方便:
It is considerably faster than np.apply_along_axis
, though perhaps not as convenient:
In [48]: %timeit np.apply_along_axis(np.linalg.norm, 1, x)
1000 loops, best of 3: 208 us per loop
In [49]: %timeit np.sum(np.abs(x)**2,axis=-1)**(1./2)
100000 loops, best of 3: 18.3 us per loop
其他 ord
形式的 norm
也可以直接计算(具有类似的加速):
Other ord
forms of norm
can be computed directly too (with similar speedups):
In [55]: %timeit np.apply_along_axis(lambda row:np.linalg.norm(row,ord=1), 1, x)
1000 loops, best of 3: 203 us per loop
In [54]: %timeit np.sum(abs(x), axis=-1)
100000 loops, best of 3: 10.9 us per loop
这篇关于如何将 numpy.linalg.norm 应用于矩阵的每一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!