张量流:3d 张量和矩阵之间的乘法



我正在尝试计算 3d 张量和 2d 张量之间的点积。我不确定这是否是正确的方法。具体来说,我想将矩阵 [10, 512] 与向量 [1, 512] 相乘,但在拥有 3d 张量和矩阵时寻找一种有效地做到这一点的方法。

f = tf.placeholder(shape = [5, 10, 512], dtype = tf.float32)
g = tf.placeholder(shape = [5, 512], dtype = tf.float32)
g = tf.expand_dims(g, 1)
m = tf.reduce_sum( tf.multiply( f, g ), 2 , keep_dims = False )

您可以直接使用矩阵乘法,因为您可以在转置其中一个向量后将点积表示为矩阵乘法。所以,在你的情况下,它会是这样的

f = tf.placeholder(shape = [5, 10, 512], dtype = tf.float32)
g = tf.placeholder(shape = [5, 512], dtype = tf.float32)
new_g = tf.expand_dims(g, 2)
m = tf.matmul(f, g)

你可以为此使用 einsum。参考资料是:

https://www.tensorflow.org/api_docs/python/tf/einsum

您可以准确指定要乘以的元素方程式,它适用于任意数量的维度。

f = tf.placeholder(shape = [5, 10, 512], dtype=tf.float32)
g = tf.placeholder(shape = [5,512], type = tf.float32)
m = tf.einsum('aij,aj->ai', f, g)

这里 a = 5, I = 10, j = 512

最新更新