TensorFlow中tf.batch_matmul()的用法
TensorFlow中tf.batch_matmul()用法
如果有兩個三階張量,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。剩下的兩個維度為數(shù)據(jù)的維度。
不過新版的tensorflow已經(jīng)移除了上面的函數(shù),使用時換為tf.matmul就可以了。與上面注釋的方式是同樣的。
附: 如果是更高維度。例如(a, b, m, n) 與(a, b, n, k)之間做matmul運算。則結果的維度為(a, b, m, k)。
TensorFlow如何實現(xiàn)batch_matmul
我們知道,在tensorflow早期版本中有tf.batch_matmul()函數(shù),可以實現(xiàn)多維tensor和低維tensor的直接相乘,這在使用過程中非常便捷。
但是最新版本的tensorflow現(xiàn)在只有tf.matmul()函數(shù)可以使用,不過只能實現(xiàn)同維度的tensor相乘, 下面的幾種方法可以實現(xiàn)batch matmul的可能。
例如: tensor A(batch_size,m,n), tensor B(n,k),實現(xiàn)batch matmul 使得A * B。
方法1: 利用tf.matmul()
對tensor B 進行增維和擴展
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]) #先進行增維再擴展 C = tf.matmul(A, B_exp)
方法2: 利用tf.reshape()
對tensor A 進行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() 對tensor按第0維進行展開的特性
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)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
使用Python通過win32 COM打開Excel并添加Sheet的方法
今天小編就為大家分享一篇使用Python通過win32 COM打開Excel并添加Sheet的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05
Python使用ThreadPoolExecutor一次開啟多個線程
通過使用ThreadPoolExecutor,您可以同時開啟多個線程,從而提高程序的并發(fā)性能,本文就來介紹一下Python使用ThreadPoolExecutor一次開啟多個線程,感興趣的可以了解一下2023-11-11
詳解python讀取matlab數(shù)據(jù)(.mat文件)
本文主要介紹了python讀取matlab數(shù)據(jù),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-12-12
Python Flask 請求數(shù)據(jù)獲取響應詳解
這篇文章主要介紹了Python Flask請求數(shù)據(jù)獲取響應的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-10-10

