简体   繁体   English

没有为4D 3D张量的张量流中的tf.matmul广播

[英]no broadcasting for tf.matmul in tensorflow for 4D 3D tensors

First I find another question here No broadcasting for tf.matmul in TensorFlow 首先我在这里找到另一个问题TensorFlow中没有广播tf.matmul
But that question does not solve my problem. 但这个问题并没有解决我的问题。

My problem is a batch of matrices multiply another batch of vectors. 我的问题是一批矩阵乘以另一批向量。

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

x is a batch of matrices.There are 10*1000 matrices.Each matrix is of shape [3,4] x是一批矩阵。有10 * 1000个矩阵。每个矩阵都是有形的[3,4]
y is a batch of vectors.There are 1000 vectors.Each vector is of shape[4] y是一批向量。有1000个向量。每个向量都是形状[4]
Dim 1 of x and dim 0 of y are the same. x的暗淡1和y的暗淡0是相同的。 (Here is 1000) (这是1000)
If tf.matmul had supported broadcasting,I could write 如果tf.matmul支持广播,我可以写

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

But tf.matmul does not support broadcasting 但是tf.matmul不支持广播
If I use the approach of the question I referenced above 如果我使用上面引用的问题的方法

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])

The result is of shape [10,1000,3,1000],not [10,1000,3]. 结果是形状[10,1000,3,1000],而不是[10,1000,3]。
I don't know how to remove the redundant 1000 我不知道如何删除多余的1000
How to get the same result as the tf.matmul which supports broadcasting? 如何获得与支持广播的tf.matmul相同的结果?

I solve it myself. 我自己解决了。

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]

As indicated here , you can use a function to work around: 如图所示在这里 ,你可以用一个函数来解决:

def broadcast_matmul(A, B):
  "Compute A @ B, broadcasting over the first `N-2` ranks"
  with tf.variable_scope("broadcast_matmul"):
    return tf.reduce_sum(A[..., tf.newaxis] * B[..., tf.newaxis, :, :],
                         axis=-2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM