TensorFlow中tf.batch_matmul()的用法
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)行展開的特性
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è)參考,也希望大家多多支持本站。
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信