如果有兩個(gè)三階張量,size分別為
a.shape = [100, 3, 4] b.shape = [100, 4, 5] c = tf.batch_matmul(a, b)
則c.shape = [100, 3, 5] //將每一對 3x4 的矩陣與 4x5 的矩陣分別相乘。batch_size不變
100為張量的batch_size。剩下的兩個(gè)維度為數(shù)據(jù)的維度。
不過新版的tensorflow已經(jīng)移除了上面的函數(shù),使用時(shí)換為tf.matmul就可以了。與上面注釋的方式是同樣的。
附: 如果是更高維度。例如(a, b, m, n) 與(a, b, n, k)之間做matmul運(yùn)算。則結(jié)果的維度為(a, b, m, k)。
我們知道,在tensorflow早期版本中有tf.batch_matmul()函數(shù),可以實(shí)現(xiàn)多維tensor和低維tensor的直接相乘,這在使用過程中非常便捷。
但是最新版本的tensorflow現(xiàn)在只有tf.matmul()函數(shù)可以使用,不過只能實(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。
對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)
對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])
利用tf.scan() 對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)
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è)參考,也希望大家多多支持腳本之家。
標(biāo)簽:定西 龍巖 江蘇 商丘 寧夏 云南 酒泉 金融催收
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《TensorFlow中tf.batch_matmul()的用法》,本文關(guān)鍵詞 TensorFlow,中,tf.batch,matmul,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。