簡體   English   中英

當使用*關於numpy.array和numpy.matrix時

[英]when use * about numpy.array and numpy.matrix

我有兩個numpy數組:

a = np.array([1, 2, 3]).reshape(3, 1)
b = np.array([4, 5]).reshape(2,1)

當我使用a*bT ,我在想一個錯誤的輸出,因為它們的形狀有所不同(使用*對數組執行逐元素乘法)。 但是結果返回矩陣乘法,如下所示:

[[ 4, 5],
 [ 8, 10],
 [12, 15]]

# this shape is (3, 2)

為什么會這樣工作?

您的a * bT是元素乘法,並且由於broadcasting而起作用。 加法和許多其他二進制操作都可以使用這對形狀。

a是(3,1)。 bT為(1,2)。 廣播將(3,1)與(1,2)組合在一起產生(3,2)。 調整大小為1的尺寸以匹配其他非零尺寸。

除非使用np.matrix制作數組, np.matrix *不會執行數學matrix multiplication np.dot用於執行該操作( @np.einsum也可以執行此操作)。

通過這種特殊的形狀組合, dot積是相同的。 np.outer(a,b)也會產生這個outer product數學outer product np.dota的最后一個維度與bT的第二個維度匹配到最后一個維度。 在這種情況下,它們都是1.共享維度具有多個項目時, dot會更有趣,從而產生熟悉的sum of products

In [5]: np.dot(a, b.T)
Out[5]: 
array([[ 4,  5],
       [ 8, 10],
       [12, 15]])

“外部”添加:

In [3]: a + b.T
Out[3]: 
array([[5, 6],
       [6, 7],
       [7, 8]])

像這樣查看ab可能會有所幫助:

In [7]: a
Out[7]: 
array([[1],
       [2],
       [3]])
In [8]: b
Out[8]: 
array([[4],
       [5]])
In [9]: b.T
Out[9]: array([[4, 5]])

我通常不使用matrix來談論numpy數組,除非它們是使用np.matrix創建的,或更常見的是scipy.sparse numpy數組可以為0d,1d,2d或更高。 我比名字更注重形狀。

暫無
暫無

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

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