TensorFlow Batch 外积 [英] TensorFlow Batch Outer Product
本文介绍了TensorFlow Batch 外积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下两个张量:
x, with shape [U, N]
y, with shape [N, V]
我想执行批量外积:我想将 x
第一列中的每个元素乘以 y
第一行中的每个元素得到形状为 [U, V]
的张量,然后是 x
的第二列和 y
的第二行,依此类推.最终张量的形状应该是 [N, U, V]
,其中 N
是批量大小.
I want to perform a batch outer product: I'd like to multiply each element in the first column of x
by each element in the first row of y
to get a tensor of shape [U, V]
, then the second column of x
by the second row of y
, and so on. The shape of the final tensor should be [N, U, V]
, where N
is the batch size.
有什么简单的方法可以在 TensorFlow 中实现这一点?我尝试使用 batch_matmul()
没有成功.
Is there any simple way to achieve this in TensorFlow? I've tried to use batch_matmul()
without success.
推荐答案
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]
这篇关于TensorFlow Batch 外积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文