關於tf.matmul() 和tf.multiply() 的區別說明
阿新 • • 發佈:2020-06-19
我就廢話不多說了,大家還是直接看程式碼吧~
flyfish
# a # [[1,2,3],# [4,5,6]] a = tf.constant([1,3,4,6],shape=[2,3]) # b1 # [[ 7,8],# [ 9,10],# [11,12]] b1 = tf.constant([7,8,9,10,11,12],shape=[3,2]) #b2 #[[ 7 8 9] # [10 11 12]] b2 = tf.constant([7,3]) # c矩陣相乘 第一個矩陣的列數(column)等於第二個矩陣的行數(row) # [[ 58,64],# [139,154]] c = tf.matmul(a,b1) # d`數元素各自相乘 #[[ 7 16 27] # [40 55 72]] d = tf.multiply(a,b2) #維度必須相等 with tf.Session(): print(d.eval())
關於其他計算
b3 = tf.constant([7,],shape=[1,3]) tf.multiply(a,b3) 結果是 [[ 7 16 27] [28 40 54]] b4 = tf.constant([7,1]) tf.multiply(a,b4) 結果是 [[ 7 14 21] [32 40 48]] b5 = tf.constant([7],b5) 結果是 [[ 7 14 21] [28 35 42]]
補充知識:tensor matmul的對3維張量的處理
torch.matmul(a,b)處理的一般是a和b的最後兩個維度,假設a的維度為B*F*M,b也為B*F*M,在對a,b做相乘操作的時候,需要完成對B的維度順序的變換,通過permute(0,1)變換為B*M*F。
通過變換後進行torch.matmul(a,b)得到結果為B*F*F,在除了最後兩個維度的的之前維度上都被認為是Batch。
示例1:
>>> import torch >>> a=torch.rand((1000,10)) >>> b=torch.rand((1000,12)) >>> c=torch.matmul(a,b) >>> c.shape torch.Size([1000,12])
在處理不同維度時,會通過廣播來合併除最後兩個維度外的其他維度,如對於A*B*F*M與B*M*F的matmul,結果為A*B*F*F
示例2:
>>> a=torch.rand((50,1000,b) >>> c.shape torch.Size([50,12])
以上這篇關於tf.matmul() 和tf.multiply() 的區別說明就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。