日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Numpy中np.dot與np.matmul的區別詳解_python

作者:ACTerminate ? 更新時間: 2023-05-10 編程語言

作用相同的情況

在若兩個array的維度均為兩維的情況下,兩個函數的結果是相同的,例如:

a = np.array([i for i in range(6)]).reshape([2,3])
b = np.array([i for i in range(6)]).reshape([3,2])
"""
a
[[0 1 2]
 [3 4 5]]
b
[[0 1]
 [2 3]
 [4 5]] 
"""
>>> np.dot(a,b)
array([[10, 13],
       [28, 40]])
>>> np.matmul(a,b)
array([[10, 13],
       [28, 40]])

作用不同的情況

在三維的情況下,假設

a = np.array([i for i in range(12)]).reshape([2,2,3])
b = np.array([i for i in range(12)]).reshape([2,3,2])
"""
a
[[[ 0 ?1 ?2]
? [ 3 ?4 ?5]]

?[[ 6 ?7 ?8]
? [ 9 10 11]]]
b
[[[ 0 ?1]
? [ 2 ?3]
? [ 4 ?5]]

?[[ 6 ?7]
? [ 8 ?9]
? [10 11]]]
"""
>>> np.matmul(a,b)
array([[[ 10, ?13],
? ? ? ? [ 28, ?40]],

? ? ? ?[[172, 193],
? ? ? ? [244, 274]]])
>>> np.matmul(a,b).shape
(2, 2, 2)

這是因為matmul將最后兩維作為矩陣的兩維,相當于有2個2 ? 2 2*22?2的矩陣,因此通過對應位置矩陣進行矩陣乘法,會得到2個2 ? 2 2*22?2的結果

>>> np.dot(a,b)
array([[[[ 10, ?13],
? ? ? ? ?[ 28, ?31]],

? ? ? ? [[ 28, ?40],
? ? ? ? ?[100, 112]]],


? ? ? ?[[[ 46, ?67],
? ? ? ? ?[172, 193]],

? ? ? ? [[ 64, ?94],
? ? ? ? ?[244, 274]]]])
>>> np.dot(a,b).shape
(2, 2, 2, 2)

可以看到其結果與matmul不同并且結果是四維的,這是因為dot將a數組的最后一維作為向量,并將b數組的倒數第二維作為了另一個向量,因此a中可以看成有2 ? 2 2*22?2個向量,b中有2 ? 2 2*22?2個向量,dot會將a的向量與b的向量全部組合在一起,因此會有( 2 ? 2 ) ? ( 2 ? 2 ) (2*2)*(2*2)(2?2)?(2?2)種結果。

原文鏈接:https://blog.csdn.net/ACTerminate/article/details/96151132

欄目分類
最近更新