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'
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.
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.
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.
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.
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
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With