张量流批处理外积



我有以下两个张量:

x, with shape [U, N]
y, with shape [N, V]
我想

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

在TensorFlow中有什么简单的方法可以实现这一点吗?我试图使用batch_matmul()但没有成功。

使用 tf.batch_matmul() 以下方法会起作用吗?

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]

也许,使用tf.einsum有一个更优雅的解决方案:

result = tf.einsum("un,nv->nuv", x, y)

最新更新