[英]Get diagonal elements from tf.matmul(tf.transpose(A), A) in Tensorflow
[英]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.
我想知道y
在tf.matmul(x,y,transpose_b = True)
里面变成了什么样的形状tf.matmul(x,y,transpose_b = True)
所以我可以注意到LSTM里面真正发生的事情。
对于秩> 2的张量,可以不同地定义转置,并且这里的差异在于由tf.transpose
和tf.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.