TensorFlow批量外积

TensorFlow批量外积,tensorflow,Tensorflow,我有以下两个张量: x, with shape [U, N] y, with shape [N, V] 我想执行一个批外积:我想将x第一列中的每个元素乘以y第一行中的每个元素,得到形状的张量[U,V],然后将x的第二列乘以y的第二行,依此类推。最终张量的形状应为[N,U,V],其中N是批次大小 在TensorFlow中有没有简单的方法来实现这一点?我尝试使用batch\u matmul()但没有成功 以下工作是否可以使用 也许有一种更优雅的解决方案,使用: result=tf.einsum(“

我有以下两个张量:

x, with shape [U, N]
y, with shape [N, V]
我想执行一个批外积:我想将
x
第一列中的每个元素乘以
y
第一行中的每个元素,得到形状的张量
[U,V]
,然后将
x
的第二列乘以
y
的第二行,依此类推。最终张量的形状应为
[N,U,V]
,其中
N
是批次大小


在TensorFlow中有没有简单的方法来实现这一点?我尝试使用
batch\u matmul()
但没有成功

以下工作是否可以使用


也许有一种更优雅的解决方案,使用:

result=tf.einsum(“un,nv->nuv”,x,y)
print x.get_shape()  # ==> [U, N]
print y.get_shape()  # ==> [N, V]

x_transposed = tf.transpose(x)
print x_transposed.get_shape()  # ==> [N, U]

x_transposed_as_matrix_batch = tf.expand_dims(x_transposed, 2)
print x_transposed_as_matrix_batch.get_shape()  # ==> [N, U, 1]

y_as_matrix_batch = tf.expand_dims(y, 1)
print y_as_matrix_batch.get_shape()  # ==> [N, 1, V]

result = tf.batch_matmul(x_transposed_as_matrix_batch, y_as_matrix_batch)
print result.get_shape()  # ==> [N, U, V]