爲了區分三種乘法運算的規則,具體分析如下:
import numpy as np
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]])
np.dot(A,B) #對數組執行矩陣相乘運算
array([[ 4, 7],
[ 8, 15]])
2.1.2 數組秩爲1的場景
C = np.arange(1,4)
C
array([1, 2, 3])
D = np.arange(0,3)
D
array([0, 1, 2])
np.dot(C,D) #對應位置相乘,再求和
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]])
A*B #對應位置點乘
array([[ 0, 2],
[ 6, 12]])
3.2矩陣場景
(np.mat(A))*(np.mat(B)) #執行矩陣運算
matrix([[ 4, 7],
[ 8, 15]])
版權聲明:轉載說明:https://blog.csdn.net/zenghaitao0128/article/details/78715140