【问题标题】:Matrix multiplication with transpose with Tensorflow使用 Tensorflow 进行转置的矩阵乘法
【发布时间】:2021-04-30 06:50:45
【问题描述】:

尝试在TF中做MatrixMultiplication

import tensorflow as tf
a1 = tf.constant(tf.random.normal(shape=(5,4,64)))
tf.matmul(a1,a1,transpose_b=True)

这工作得很好,但是如果我像下面这样手动transpose 输入a1,我会得到一个错误:

tf.matmul(a1,tf.transpose(a1))

错误:

InvalidArgumentError: In[0] and In[1] must have compatible batch dimensions: [5,4,64] vs. [64,4,5] [Op:BatchMatMulV2]

文档:

transpose_b: If True, b is transposed before multiplication.

所以我不明白其中的区别,任何建议都会有所帮助。

【问题讨论】:

    标签: tensorflow matrix keras tensorflow2.0 matrix-multiplication


    【解决方案1】:

    要计算批量矩阵乘法,您需要确保 3D 张量的格式如下。检查3-D张量矩阵乘法。

    [batchs, h`, w`] @ [batchs, w``, h``]
    

    所以,在上述情况下,它应该是

    import tensorflow as tf
    
    a1 = tf.constant(tf.random.normal(shape=(5,4,64)))
    
    a1.shape, tf.transpose(a1, perm=[0, 2, 1]).shape
    (TensorShape([5, 4, 64]), TensorShape([5, 64, 4]))
    
    # swape the height and width - not batch axis 
    tf.matmul(a1, tf.transpose(a1, perm=[0, 2, 1])).shape
    TensorShape([5, 4, 4])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-11
      • 2018-06-16
      • 1970-01-01
      • 2013-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多