在4D 3D张量的tensorflow中不广播tf.matmul

在4D 3D张量的tensorflow中不广播tf.matmul,tensorflow,Tensorflow,首先,我在这里发现另一个问题 但这个问题并不能解决我的问题 我的问题是一批矩阵乘以另一批向量 x=tf.placeholder(tf.float32,shape=[10,1000,3,4]) y=tf.placeholder(tf.float32,shape=[1000,4]) x是一批矩阵。有10*1000个矩阵。每个矩阵的形状为[3,4] y是一批向量。有1000个向量。每个向量的形状为[4] x的尺寸1和y的尺寸0是相同的。(这里是1000) 如果tf.matmul支持广播,我就可以写了

首先,我在这里发现另一个问题
但这个问题并不能解决我的问题

我的问题是一批矩阵乘以另一批向量

x=tf.placeholder(tf.float32,shape=[10,1000,3,4])
y=tf.placeholder(tf.float32,shape=[1000,4])
x是一批矩阵。有10*1000个矩阵。每个矩阵的形状为[3,4]
y是一批向量。有1000个向量。每个向量的形状为[4]
x的尺寸1和y的尺寸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])
结果的形状为[101000,31000],而不是[101000,3]。
我不知道如何删除多余的1000个
如何获得与支持广播的tf.matmul相同的结果?

我自己解决

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]
如图所示,您可以使用函数解决以下问题:

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)

遗憾的是,即使使用
tf.tensordot
,也没有更好的方法。