繁体   English   中英

为什么tf.matmul(a,b,transpose_b = True)有效,但不是tf.matmul(a,tf.transpose(b))?

[英]Why does tf.matmul(a,b, transpose_b=True) work, but not tf.matmul(a, tf.transpose(b))?

码:

x = tf.constant([1.,2.,3.], shape = (3,2,4))
y = tf.constant([1.,2.,3.], shape = (3,21,4))
tf.matmul(x,y)                     # Doesn't work. 
tf.matmul(x,y,transpose_b = True)  # This works. Shape is (3,2,21)
tf.matmul(x,tf.transpose(y))       # Doesn't work.

我想知道ytf.matmul(x,y,transpose_b = True)里面变成了什么样的形状tf.matmul(x,y,transpose_b = True)所以我可以注意到LSTM里面真正发生的事情。

对于秩> 2的张量,可以不同地定义转置,并且这里的差异在于由tf.transposetf.matmul(..., transpose_b=True)转置的轴。

默认情况下, tf.transpose执行此操作:

返回的张量的维度i将对应于输入维度perm[i] 如果没有给出perm,则将其设置为(n-1...0) ,其中n是输入张量的等级。 因此,默认情况下,此操作在2-D输入张量上执行常规矩阵转置。

所以在你的情况下,它会将y转换为一个形状的张量(4, 21, 3) 4,21,3 (4, 21, 3) ,这与x 不兼容 (见下文)。

但是如果设置perm=[0, 2, 1] ,结果是兼容的

# Works! (3, 2, 4) * (3, 4, 21) -> (3, 2, 21).
tf.matmul(x, tf.transpose(y, [0, 2, 1]))

关于tf.matmul

您可以计算点积: (a, b, c) * (a, c, d) -> (a, b, d) 但它不是张量点产品 - 它是批量操作 (见这个问题 )。

在这种情况下, a被认为是批量大小,因此tf.matmul计算矩阵(b, c) * (c, d) a点积。

批处理可以是多个维度,因此这也是有效的:

(a, b, c, d) * (a, b, d, e) -> (a, b, c, e)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM