【发布时间】:2021-07-02 23:18:39
【问题描述】:
我想用 np.linalg.norm 来计算一个行向量的范数,然后用这个范数对行向量进行归一化,就像我在代码中写的那样。我给向量 x 一个初始值,但是在我运行这段代码之后,我总是得到:
AxisError: 轴 1 超出维度 1 数组的范围
所以我很困惑,不知道问题出在哪里。这是我的代码:
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))
这是错误:
---------------------------------------------------------------------------
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
谁能告诉我为什么这是错误的以及如何解决它?谢谢!
【问题讨论】:
-
您将
x作为一维 numpy 数组(只有一维)传递,而函数希望它至少具有二维。制作xnp.array([[1, 2, 3]])。