How to apply numpy.linalg.norm to each row of a matrix?

后端 未结 4 565
鱼传尺愫
鱼传尺愫 2020-11-28 04:03

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

4条回答
  •  情歌与酒
    2020-11-28 04:48

    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)'
        )
    

提交回复
热议问题