I want to use np.linalg.norm to calculate the norm of a row vector, and then use this norm to normalize the row vector, as I wrote in the code. I give an initial value to the vector x, but after I run this code I always get:
AxisError: axis 1 is out of bounds for array of dimension 1
So I'm confused and don't know what's the problem. Here is my code:
import numpy as np
def normalizeRows(x):
x_norm = np.linalg.norm(x, axis=1, keepdims=True)
x_normalized = x / x_norm
return x_normalized
x = np.array([1, 2, 3])
print(normalizeRows(x))
And here is the error:
---------------------------------------------------------------------------
AxisError Traceback (most recent call last)
<ipython-input-16-155a4cdd9bf8> in <module>
10
11 x = np.array([1, 2, 3])
---> 12 print(normalizeRows(x))
13
14
<ipython-input-16-155a4cdd9bf8> in normalizeRows(x)
4
5 def normalizeRows(x):
----> 6 x_norm = np.linalg.norm(x, axis=1, keepdims=True)
7 x_normalized = x / x_norm
8
<__array_function__ internals> in norm(*args, **kwargs)
d:\programs\python39\lib\site-packages\numpy\linalg\linalg.py in norm(x, ord, axis, keepdims)
2558 # special case for speedup
2559 s = (x.conj() * x).real
-> 2560 return sqrt(add.reduce(s, axis=axis, keepdims=keepdims))
2561 # None of the str-type keywords for ord ('fro', 'nuc')
2562 # are valid for vectors
AxisError: axis 1 is out of bounds for array of dimension 1
Could somebody tell me why this is wrong and how to fix it? Thanks!
This gives you axis error because your array is a 1d array, and since :
"In a multi-dimensional NumPy array, axis 1 is the second axis. When we're talking about 2-d and multi-dimensional arrays, axis 1 is the axis that runs horizontally across the columns" quoted from link
All you have to do is change your axis to 0
import numpy as np
def normalizeRows(x):
x_norm = np.linalg.norm(x, axis=0, keepdims=True)
x_normalized = x / x_norm
return x_normalized
x = np.array([1, 2, 3])
print(normalizeRows(x))
[0.26726124 0.53452248 0.80178373]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.