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

后端 未结 4 556
鱼传尺愫
鱼传尺愫 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:53

    Try the following:

    In [16]: numpy.apply_along_axis(numpy.linalg.norm, 1, a)
    Out[16]: array([ 5.38516481,  1.41421356,  5.38516481])
    

    where a is your 2D array.

    The above computes the L2 norm. For a different norm, you could use something like:

    In [22]: numpy.apply_along_axis(lambda row:numpy.linalg.norm(row,ord=1), 1, a)
    Out[22]: array([9, 2, 9])
    

提交回复
热议问题