Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linalg.norm not taking axis argument

Tags:

python

numpy

norm

I am using Python 3 within Pyzo. Please could you tell me why the linalg.norm function does not recognise the axis argument.

This code:

c = np.array([[ 1, 2, 3],[-1, 1, 4]])
d=linalg.norm(c, axis=1)

returns the error:

TypeError: norm() got an unexpected keyword argument 'axis'

like image 591
Thomas Hopkins Avatar asked Nov 23 '13 22:11

Thomas Hopkins


People also ask

What is the default axis norm in Matplotlib?

If axis is a 2-tuple, it specifies the axes that hold 2-D matrices, and the matrix norms of these matrices are computed. If axis is None then either a vector norm (when x is 1-D) or a matrix norm (when x is 2-D) is returned. The default is None.

What is the Order of the norm of the Axis?

If axis is None, x must be 1-D or 2-D. Order of the norm (see table under Notes ). inf means numpy’s inf object. If axis is an integer, it specifies the axis of x along which to compute the vector norms. If axis is a 2-tuple, it specifies the axes that hold 2-D matrices, and the matrix norms of these matrices are computed.

What is the difference between torch's linalg norm () and vector_norm () functions?

The above functions are often clearer and more flexible than using torch.linalg.norm () . For example, torch.linalg.norm (A, ord=1, dim= (0, 1)) always computes a matrix norm, but with torch.linalg.vector_norm (A, ord=1, dim= (0, 1)) it is possible to compute a vector norm over the two dimensions.

What is L2 norm in NumPy linalg?

When np.linalg.norm () is called on an array-like input without any additional arguments, the default behavior is to compute the L2 norm on a flattened view of the array. This is the square root of the sum of squared elements and can be interpreted as the length of the vector in Euclidean space.


2 Answers

linalg.norm does not accept an axis argument. You can get around that with:

np.apply_along_axis(np.linalg.norm, 1, c)
# array([ 3.74165739,  4.24264069])

Or to be faster, implement it yourself with:

np.sqrt(np.einsum('ij,ij->i',c,c))
# array([ 3.74165739,  4.24264069])

For timing:

timeit np.apply_along_axis(np.linalg.norm, 1, c)
10000 loops, best of 3: 170 µs per loop

timeit np.sqrt(np.einsum('ij,ij->i',c,c))
100000 loops, best of 3: 10.7 µs per loop
like image 82
askewchan Avatar answered Sep 30 '22 11:09

askewchan


On numpy versions below 1.8 linalg.norm does not take axis argument, you can use np.apply_along_axis to get your desired outcome, as pointed out by Warren Weckesser in the comment to the question.

import numpy as np
from numpy import linalg

c = np.array([[ 1, 2, 3],[-1, 1, 4]])

d = np.apply_along_axis(linalg.norm, 1, c)

Result:

>>> d
array([ 3.74165739,  4.24264069])
like image 39
Akavall Avatar answered Sep 30 '22 13:09

Akavall