【问题标题】:is there any difference between matmul and usual multiplication of tensorsmatmul和张量的通常乘法之间有什么区别吗
【发布时间】:2019-04-11 15:34:12
【问题描述】:

我对使用 * 和 matmul 的两个张量之间的乘法感到困惑。 下面是我的代码

import torch
torch.manual_seed(7)
features = torch.randn((2, 5))
weights = torch.randn_like(features)

在这里,我想将权重和特征相乘。所以,一种方法如下

print(torch.sum(features * weights))

输出:

tensor(-2.6123)

另一种方法是使用 matmul

print(torch.mm(features,weights.view((5,2))))

但是,这里的输出是

tensor([[ 2.8089,  4.6439],
        [-2.3988, -1.9238]])

我在这里不明白的是,为什么matmul 和通常的乘法在两者相同时会给出不同的输出。我在这里做错了吗?

编辑:当我使用形状 (1,5) 的特征时,* 和 matmul 输出是相同的。 但是,形状为(2,5)时就不一样了。

【问题讨论】:

    标签: python numpy pytorch tensor


    【解决方案1】:

    当你使用*时,乘法是逐元素的,当你使用torch.mm时,它是矩阵乘法。

    例子:

    a = torch.rand(2,5)
    b = torch.rand(2,5)
    result = a*b 
    

    result 的形状与ab 相同,即(2,5) 而考虑操作

    result = torch.mm(a,b)
    

    它会产生大小不匹配错误,因为这是正确的矩阵乘法(正如我们在线性代数中研究的那样)和a.shape[1] != b.shape[0]。当您在torch.mm 中应用视图操作时,您正在尝试匹配尺寸。

    在某个特定维度的形状为 1 的特殊情况下,它变成一个点积,因此 sum (a*b)mm(a, b.view(5,1)) 相同

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-13
      • 2017-04-05
      • 2014-09-18
      • 2015-06-14
      • 2011-05-23
      • 2011-02-15
      • 2011-11-27
      相关资源
      最近更新 更多