【问题标题】:tensorflow: multiply certain rows of a matrix with certain columns in anothertensorflow:将矩阵的某些行与另一个矩阵的某些列相乘
【发布时间】:2017-08-18 05:29:12
【问题描述】:

假设我有一个矩阵A 和一个矩阵B。我知道tf.matmul(A,B) 可以计算两个矩阵的乘法。但我有一个任务只需要将A 的某些行与B 的某些列相乘。

例如,我有一个 ALs_A=[0,1,2] 的行 ID 列表和一个 BLs_B=[4,2,6] 的列 ID 列表。我想要一个列表的结果,表示为Ls,这样:

Ls[0] = A[0,:] * B[:,4]
Ls[1] = A[1,:] * B[:,2]
Ls[2] = A[2,:] * B[:,6]

我怎样才能做到这一点?

谢谢大家帮助我!

【问题讨论】:

    标签: python tensorflow matrix-multiplication


    【解决方案1】:

    您可以使用tf.gather 进行如下操作:

    import tensorflow as tf
    a=tf.constant([[1,2,3],[4,5,6],[7,8,9]])
    b=tf.constant([[1,0,1],[1,0,2],[3,3,-1]])
    
    #taking rows 0,1 from a, and columns 0,2 from b
    ind_a=tf.constant([0,1])
    ind_b=tf.constant([0,2])
    
    r_a=tf.gather(a,ind_a)
    
    #tf.gather access the rows, so we use it together with tf.transpose to access the columns
    r_b=tf.transpose(tf.gather(tf.transpose(b),ind_b))
    
    # the diagonal elements of the multiplication
    res=tf.diag_part(tf.matmul(r_a,r_b))
    sess=tf.InteractiveSession()
    print(r_a.eval())
    print(r_b.eval())
    print(res.eval())
    

    打印出来

    #r_a
    [[1 2 3]
     [4 5 6]]
    
    #r_b
    [[ 1  1]
     [ 1  2]
     [ 3 -1]]
    
    #result
    [12  8]
    

    【讨论】:

    • 谢谢。这非常接近我的预期。唯一的区别是,在您的示例中,我想要 a[0] * b[0] 和 a[1] * b[2]。也就是说,我只需要你的结果的对角线。但是鉴于您的解决方案,我认为很容易实现我的目标。我只需要执行 tf.multiply(r_a,tf.transpose(r_b)),然后沿轴 1 执行 reduce_sum。对吗?
    • 我错过了你只想要对角线的部分。您可以为此使用 tf.diag_part。查看我更新的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    • 2012-09-22
    相关资源
    最近更新 更多