目錄
- 1. np.multiply()函數
- 2. np.dot()函數
- 3. 星號(*)乘法運算
為了區分三種乘法運算的規則,具體分析如下:
1. np.multiply()函數
函數作用
數組和矩陣對應位置相乘,輸出與相乘數組/矩陣的大小一致
1.1數組場景
A = np.arange(1,5).reshape(2,2)
A
array([[1, 2],
[3, 4]])
B = np.arange(0,4).reshape(2,2)
B
array([[0, 1],
[2, 3]])
np.multiply(A,B) #數組對應元素位置相乘
array([[ 0, 2],
[ 6, 12]])
1.2 矩陣場景
np.multiply(np.mat(A),np.mat(B)) #矩陣對應元素位置相乘,利用np.mat()將數組轉換為矩陣
matrix([[ 0, 2],
[ 6, 12]])
np.sum(np.multiply(np.mat(A),np.mat(B))) #輸出為標量
20
2. np.dot()函數
函數作用
對于秩為1的數組,執行對應位置相乘,然后再相加;
對于秩不為1的二維數組,執行矩陣乘法運算;超過二維的可以參考numpy庫介紹。
2.1 數組場景
2.1.1 數組秩不為1的場景
A = np.arange(1,5).reshape(2,2)
A
array([[1, 2],
[3, 4]])
B = np.arange(0,4).reshape(2,2)
B
array([[0, 1],
[2, 3]])
array([[ 4, 7],
[ 8, 15]])
2.1.2 數組秩為1的場景
array([1, 2, 3])
array([0, 1, 2])
8
2.2 矩陣場景
np.dot(np.mat(A),np.mat(B)) #執行矩陣乘法運算
matrix([[ 4, 7],
[ 8, 15]])
3. 星號(*)乘法運算
作用
對數組執行對應位置相乘
對矩陣執行矩陣乘法運算
3.1 數組場景
A = np.arange(1,5).reshape(2,2)
A
array([[1, 2],
[3, 4]])
B = np.arange(0,4).reshape(2,2)
B
array([[0, 1],
[2, 3]])
array([[ 0, 2],
[ 6, 12]])
3.2矩陣場景
(np.mat(A))*(np.mat(B)) #執行矩陣運算
matrix([[ 4, 7],
[ 8, 15]])
到此這篇關于python中np.multiply()、np.dot()和星號(*)三種乘法運算的區別詳解的文章就介紹到這了,更多相關python np.multiply()、np.dot()和星號內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- 關于tf.matmul() 和tf.multiply() 的區別說明
- 對python中的乘法dot和對應分量相乘multiply詳解