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.
I can take
Much faster than the accepted answer is
numpy.sqrt(numpy.einsum('ij,ij->i', a, a))
Note the log-scale:
Code to reproduce the plot:
import numpy
import perfplot
def sum_sqrt(a):
return numpy.sqrt(numpy.sum(numpy.abs(a)**2, axis=-1))
def apply_norm_along_axis(a):
return numpy.apply_along_axis(numpy.linalg.norm, 1, a)
def norm_axis(a):
return numpy.linalg.norm(a, axis=1)
def einsum_sqrt(a):
return numpy.sqrt(numpy.einsum('ij,ij->i', a, a))
perfplot.show(
setup=lambda n: numpy.random.rand(n, 3),
kernels=[sum_sqrt, apply_norm_along_axis, norm_axis, einsum_sqrt],
n_range=[2**k for k in range(20)],
logx=True,
logy=True,
xlabel='len(a)'
)