簡體   English   中英

Numpy:具有各種形狀的1D陣列

[英]Numpy: 1D array with various shape

我嘗試了解如何使用NumPy處理一1D數組(線性代數中的向量)。

在下面的示例中,我生成了兩個numpy.array ab

>>> import numpy as np
>>> a = np.array([1,2,3])
>>> b = np.array([[1],[2],[3]]).reshape(1,3)
>>> a.shape
(3,)
>>> b.shape
(1, 3)

對我來說,根據線性代數定義, ab具有相同的形狀:1行3列,但不適用於NumPy

現在, NumPy dot產品:

>>> np.dot(a,a)
14
>>> np.dot(b,a)
array([14])
>>> np.dot(b,b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: objects are not aligned

我有三種不同的輸出。

dot(a,a)dot(b,a)之間有什么區別? 為什么dot (b,b)不起作用?

我對這些點產品也有一些不同之處:

>>> c = np.ones(9).reshape(3,3)
>>> np.dot(a,c)
array([ 6.,  6.,  6.])
>>> np.dot(b,c)
array([[ 6.,  6.,  6.]])

請注意,您不僅使用1D數組:

In [6]: a.ndim
Out[6]: 1

In [7]: b.ndim
Out[7]: 2

所以, b是一個2D數組。 您還可以在b.shape的輸出中看到這b.shape :(1,3)表示兩個維度為(3,)是一個維度。

對於1D和2D數組(來自文檔 ), np.dot的行為是不同的:

對於二維陣列,它相當於矩陣乘法,而對於一維陣列則相當於向量的內積

這就是你得到不同結果的原因,因為你正在混合1D和2D數組。 由於b是2D數組, np.dot(b, b)在兩個1x3矩陣上嘗試矩陣乘法,這會失敗。


對於1D數組,np.dot執行向量的內積:

In [44]: a = np.array([1,2,3])

In [45]: b = np.array([1,2,3])

In [46]: np.dot(a, b)
Out[46]: 14

In [47]: np.inner(a, b)
Out[47]: 14

對於2D陣列,它是矩陣乘法(因此1x3 x 3x1 = 1x1,或3x1 x 1x3 = 3x3):

In [49]: a = a.reshape(1,3)

In [50]: b = b.reshape(3,1)

In [51]: a
Out[51]: array([[1, 2, 3]])

In [52]: b
Out[52]:
array([[1],
       [2],
       [3]])

In [53]: np.dot(a,b)
Out[53]: array([[14]])

In [54]: np.dot(b,a)
Out[54]:
array([[1, 2, 3],
       [2, 4, 6],
       [3, 6, 9]])

In [55]: np.dot(a,a)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-55-32e36f9db916> in <module>()
----> 1 np.dot(a,a)

ValueError: objects are not aligned

暫無
暫無

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

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