gpt4 book ai didi

python - 为什么 tf.matmul(a,b, transpose_b=True) 有效,但 tf.matmul(a, tf.transpose(b)) 无效?

转载 作者:太空宇宙 更新时间:2023-11-03 11:18:28 27 4
gpt4 key购买 nike

代码:

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) 中变成什么形状,这样我就可以弄清楚带有注意力的 LSTM。

最佳答案

对于秩 > 2 的张量,转置可以有不同的定义,这里的区别在于由 tf.transposetf.matmul(..., transpose_b=真)

默认情况下,tf.transpose这样做:

The returned tensor's dimension i will correspond to the input dimension perm[i]. If perm is not given, it is set to (n-1...0), where n is the rank of the input tensor. Hence by default, this operation performs a regular matrix transpose on 2-D input Tensors.

因此在您的情况下,它将把 y 转换为形状为 (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)。但这不是张量点积——它是一个批量操作(参见 this question )。

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

批处理可以是多维的,所以这也是有效的:

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

关于python - 为什么 tf.matmul(a,b, transpose_b=True) 有效,但 tf.matmul(a, tf.transpose(b)) 无效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48100954/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com