代码之家  ›  专栏  ›  技术社区  ›  rawwar

matmul和通常的张量乘法有什么区别吗

  •  1
  • rawwar  · 技术社区  · 8 年前

    下面是我的代码

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

    print(torch.sum(features * weights))
    

    输出:

    tensor(-2.6123)
    

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

    但是,这里的输出是

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

    我不明白这是为什么 matmul

    (1,5) *和 输出相同。 (2,5) .

    1 回复  |  直到 8 年前
        1
  •  8
  •   Umang Gupta    8 年前

    当你使用 * torch.mm

    例子:

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

    result a b 即 (2,5) 鉴于考虑运营

    result = torch.mm(a,b)
    

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

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