簡體   English   中英

np.linalg.norm AxisError:軸 1 超出維度 1 數組的范圍

[英]np.linalg.norm AxisError: axis 1 is out of bounds for array of dimension 1

我想用 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

有人能告訴我為什么這是錯誤的以及如何解決嗎? 謝謝!

這會給您帶來軸錯誤,因為您的數組是一維數組,並且因為:
“在多維 NumPy 數組中,軸 1 是第二個軸。當我們談論二維和多維數組時,軸 1 是水平跨列的軸”引用自鏈接

您所要做的就是將軸更改為 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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM