python中np.multiply()、np.dot()和星號(*)三種乘法運算的區(qū)別詳解
為了區(qū)分三種乘法運算的規(guī)則,具體分析如下:
import numpy as np1. 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的數組,執(zhí)行對應位置相乘,然后再相加;
對于秩不為1的二維數組,執(zhí)行矩陣乘法運算;超過二維的可以參考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) #對數組執(zhí)行矩陣相乘運算
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)) #執(zhí)行矩陣乘法運算
matrix([[ 4, 7],[ 8, 15]])
3. 星號(*)乘法運算作用
對數組執(zhí)行對應位置相乘
對矩陣執(zhí)行矩陣乘法運算
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)) #執(zhí)行矩陣運算
matrix([[ 4, 7],[ 8, 15]])
到此這篇關于python中np.multiply()、np.dot()和星號(*)三種乘法運算的區(qū)別詳解的文章就介紹到這了,更多相關python np.multiply()、np.dot()和星號內容請搜索好吧啦網以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: