2017-04-17 96 views
1

首先我在這裏找到另一個問題No broadcasting for tf.matmul in TensorFlow
但是這個問題並沒有解決我的問題。在tensorflow中沒有廣播tf.matmul用於4D 3D張量

我的問題是一批矩陣乘以另一批向量。

x=tf.placeholder(tf.float32,shape=[10,1000,3,4]) 
y=tf.placeholder(tf.float32,shape=[1000,4]) 

x是一個批次matrices.There的是10 * 1000 matrices.Each矩陣是形狀的[3,4]
y是一個批次vectors.There都1000 vectors.Each矢量是形狀的[4]
x的dim 1和y的dim 0是相同的。(這裏是1000)
如果tf.matmul曾支持廣播​​,我可以寫

y=tf.reshape(y,[1,1000,4,1]) 
result=tf.matmul(x,y) 
result=tf.reshape(result,[10,1000,3]) 

但tf.matmul不支持廣播
如果我用我上面

引用問題的方法
x=tf.reshape(x,[10*1000*3,4]) 
y=tf.transpose(y,perm=[1,0]) #[4,1000] 
result=tf.matmul(x,y) 
result=tf.reshape(result,[10,1000,3,1000]) 

結果是形狀[10,1000,3,1000],而不是[10,1000,3]。
我不知道如何刪除多餘的1000
如何獲得相同的結果,它支持廣播tf.matmul?

回答

1

我自己解決。

x=tf.transpose(x,perm=[1,0,2,3]) #[1000,10,3,4] 
x=tf.reshape(x,[1000,30,4]) 
y=tf.reshape(y,[1000,4,1]) 
result=tf.matmul(x,y) #[1000,30,1] 
result=tf.reshape(result,[1000,10,3]) 
result=tf.transpose(result,perm=[1,0,2]) #[10,1000,3]