TensorFlow批量外产品

njk*_*njk 4 tensorflow

我有以下两个张量:

x, with shape [U, N]
y, with shape [N, V]
Run Code Online (Sandbox Code Playgroud)

我想执行批量外部产品:我想将x第一行中每个元素的第一列中的每个元素相乘y以获得形状的张量[U, V],然后是第二行中x的第二列y,等等上.最终张量的形状应[N, U, V],其中N为将批量大小.

在TensorFlow中有没有简单的方法来实现这一目标?我试图使用batch_matmul()但没有成功.

mrr*_*rry 6

以下工作,使用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]
Run Code Online (Sandbox Code Playgroud)