有没有办法在tensorflow的tensordot操作中广播张量?

is there a way to broadcast tensor in tensordot operation in tensorflow?

我想乘以张量形式表示的堆叠矩阵。

tensor.shape == [2,5,7,6]

其中 2 和 5 是批处理的大小,

tensor2.shape == [5,6,8]

其中 5 是批量大小。

在numpy中,tensor2自动广播到[2,5,7,6]张量

所以我可以轻松使用 np.matmul(tensor,tensor2)

但是在tensorflow中,出现错误。

我尝试了 tf.expand_dims(tensor2,0) 但这也行不通

在tensorflow中有什么方法可以广播tensor吗?

解决此类问题的最通用和最合适的方法是使用 tf.einsum. This function allows you to directly specify the multiplication rules using Einstein notation,它是为处理任意维度的张量而发明的。

您可以使用 tf.einsum:

tf.einsum('abij,bjk->abik', tensor, tensor2)

示例:

import tensorflow as tf
x = tf.zeros((2, 5, 7, 6))
y = tf.zeros((5, 6, 8))
z = tf.einsum('abij,bjk->abik', x, y)
z.shape.as_list()
# returns [2, 5, 7, 8]