【问题标题】:Is there a vectorized way to create a matrix in which each element is the the row-wise dot product of a matrix?有没有一种矢量化的方法来创建一个矩阵,其中每个元素都是矩阵的逐行点积?
【发布时间】:2021-08-09 03:36:16
【问题描述】:

抱歉标题含糊不清,我花了一些时间重新措辞但不能很好地理解它。

比如我在 Pytorch 张量中有一个 2*3 的矩阵

test = torch.tensor([[1, 10, 100],
                    [2, 20, 200]])

我想要一个最终的矩阵是

torch.tensor([10101, 20202],
             [20202, 40404])

我们可以看到,(0,0)位置是第一行与自身的点积,(0,1)(1,0)是第一行和第二行的点积,(1,1 ) 第二行与自身的点积。

谢谢!

【问题讨论】:

    标签: numpy matrix pytorch vectorization


    【解决方案1】:

    你可以做矩阵乘法:

    test @ test.T
    

    torch.einsum

    torch.einsum('ij,kj->ik', test, test)
    

    【讨论】:

      【解决方案2】:

      您是否正在寻找矩阵的点积及其转置?

      test.matmul(test.transpose(0,1))
      print(test)
      >>> tensor([[10101, 20202],
                  [20202, 40404]])
      

      【讨论】:

        猜你喜欢
        • 2017-07-24
        • 1970-01-01
        • 1970-01-01
        • 2020-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-10
        相关资源
        最近更新 更多