【问题标题】:np.linalg.norm AxisError: axis 1 is out of bounds for array of dimension 1np.linalg.norm AxisError:轴 1 超出维度 1 数组的范围
【发布时间】: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]])

标签: python numpy


【解决方案1】:

这会给您带来轴错误,因为您的数组是一维数组,并且因为:
“在多维 NumPy 数组中,轴 1 是第二个轴。当我们谈论二维和多维数组时,轴 1 是水平穿过列的轴”引用自 link

您所要做的就是将轴更改为 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]

【讨论】:

  • 感谢您的回答和链接,它们非常有帮助。
  • yw :) 乐于助人
  • 嗨@CatLover,我在尝试为我的文本分类模型生成 AUROC 分数时遇到了类似的错误。我无法找到解决方案。你能帮忙吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-31
  • 2022-07-03
  • 2020-10-30
  • 1970-01-01
  • 2018-07-07
  • 1970-01-01
  • 2018-05-22
相关资源
最近更新 更多