TensorFlow中tf.batch_matmul()用法
如果有兩個(gè)三階張量,size分別為
a.shape = [100, 3, 4]
b.shape = [100, 4, 5]
c = tf.batch_matmul(a, b)
則c.shape = [100, 3, 5] //將每一對(duì) 3x4 的矩陣與 4x5 的矩陣分別相乘。batch_size不變
100為張量的batch_size。剩下的兩個(gè)維度為數(shù)據(jù)的維度。
不過(guò)新版的tensorflow已經(jīng)移除了上面的函數(shù),使用時(shí)換為tf.matmul就可以了。與上面注釋的方式是同樣的。
附: 如果是更高維度。例如(a, b, m, n) 與(a, b, n, k)之間做matmul運(yùn)算。則結(jié)果的維度為(a, b, m, k)。
TensorFlow如何實(shí)現(xiàn)batch_matmul
我們知道,在tensorflow早期版本中有tf.batch_matmul()函數(shù),可以實(shí)現(xiàn)多維tensor和低維tensor的直接相乘,這在使用過(guò)程中非常便捷。
但是最新版本的tensorflow現(xiàn)在只有tf.matmul()函數(shù)可以使用,不過(guò)只能實(shí)現(xiàn)同維度的tensor相乘, 下面的幾種方法可以實(shí)現(xiàn)batch matmul的可能。
例如: tensor A(batch_size,m,n), tensor B(n,k),實(shí)現(xiàn)batch matmul 使得A * B。
方法1: 利用tf.matmul()
對(duì)tensor B 進(jìn)行增維和擴(kuò)展
A = tf.Variable(tf.random_normal(shape=(batch_size, 2, 3)))
B = tf.Variable(tf.random_normal(shape=(3, 5)))
B_exp = tf.tile(tf.expand_dims(B,0),[batch_size, 1, 1]) #先進(jìn)行增維再擴(kuò)展
C = tf.matmul(A, B_exp)
方法2: 利用tf.reshape()
對(duì)tensor A 進(jìn)行reshape操作,然后利用tf.matmul()
A = tf.Variable(tf.random_normal(shape=(batch_size, 2, 3)))
B = tf.Variable(tf.random_normal(shape=(3, 5)))
A = tf.reshape(A, [-1, 3])
C = tf.reshape(tf.matmul(A, B), [-1, 2, 5])
方法3: 利用tf.scan()
利用tf.scan() 對(duì)tensor按第0維進(jìn)行展開(kāi)的特性
A = tf.Variable(tf.random_normal(shape=(batch_size, 2, 3)))
B = tf.Variable(tf.random_normal(shape=(3, 5)))
initializer = tf.Variable(tf.random_normal(shape=(2,5)))
C = tf.scan(lambda a,x: tf.matmul(x, B), A, initializer)
方法4: 利用tf.einsum()
A = tf.Variable(tf.random_normal(shape=(batch_size, 2, 3)))
B = tf.Variable(tf.random_normal(shape=(3, 5)))
C = tf.einsum('ijk,kl->ijl',A,B)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
您可能感興趣的文章:- 教你使用TensorFlow2識(shí)別驗(yàn)證碼
- pytorch_pretrained_bert如何將tensorflow模型轉(zhuǎn)化為pytorch模型
- Tensorflow與RNN、雙向LSTM等的踩坑記錄及解決
- tensorflow中的數(shù)據(jù)類(lèi)型dtype用法說(shuō)明
- tensorflow基本操作小白快速構(gòu)建線(xiàn)性回歸和分類(lèi)模型