Tensorflow将3D批次张量与2D权重相乘

Tensorflow将3D批次张量与2D权重相乘,tensorflow,matrix-multiplication,broadcast,Tensorflow,Matrix Multiplication,Broadcast,我有两个张量,形状如下所示 batch.shape=[?,5,4] weight.shape=[3,5] 通过将重量乘以批次中的每个元素,我想得到 result.shape=[?,3,4] 实现这一目标最有效的方法是什么?试试以下方法: newbatch = tf.transpose(batch,[1,0,2]) newbatch = tf.reshape(newbatch,[5,-1]) result = tf.matmul(weight,newbatch) result = tf.resha

我有两个张量,形状如下所示

batch.shape=[?,5,4]

weight.shape=[3,5]

通过将重量乘以批次中的每个元素,我想得到

result.shape=[?,3,4]

实现这一目标最有效的方法是什么?

试试以下方法:

newbatch = tf.transpose(batch,[1,0,2])
newbatch = tf.reshape(newbatch,[5,-1])
result = tf.matmul(weight,newbatch)
result = tf.reshape(result,[3,-1,4])
result = tf.transpose(result, [1,0,2])
tf.einsum("ijk,aj-> iak",batch,weight)
或者更紧凑地说:

newbatch = tf.reshape(tf.transpose(batch,[1,0,2]),[5,-1])
result = tf.transpose(tf.reshape(tf.matmul(weight,newbatch),[3,-1,4]), [1,0,2])
试试这个:

newbatch = tf.transpose(batch,[1,0,2])
newbatch = tf.reshape(newbatch,[5,-1])
result = tf.matmul(weight,newbatch)
result = tf.reshape(result,[3,-1,4])
result = tf.transpose(result, [1,0,2])
tf.einsum("ijk,aj-> iak",batch,weight)

任意维张量之间的广义收缩

他为什么要这样做?在3D和2D之间进行矩阵乘法,结果的预期形状应该是匹配的,如果他只需要乘法,那么他就在tf的帮助下进行广播。那么你为什么不这么说?