一,对应点相乘,x.mul(y) ,即点乘操作,点乘不求和操作,又可以叫作Hadamard product;点乘再求和,即为卷积

>>> a = torch.Tensor([[1,2], [3,4], [5, 6]])
>>> a
tensor([[1., 2.],
        [3., 4.],
        [5., 6.]])
>>> a.mul(a)
tensor([[ 1.,  4.],
        [ 9., 16.],
        [25., 36.]])

>>> a * a
tensor([[ 1.,  4.],
        [ 9., 16.],
        [25., 36.]])

二,矩阵相乘,x.mm(y)或者x.matmul(b), 矩阵大小需满足: (i, n)x(n, j)

>>> a
tensor([[1., 2.],
        [3., 4.],
        [5., 6.]])
>>> b = a.t()  # 转置
>>> b
tensor([[1., 3., 5.],
        [2., 4., 6.]])

>>> a.mm(b)
tensor([[ 5., 11., 17.],
        [11., 25., 39.],
        [17., 39., 61.]])

>>> a.matmul(b)
tensor([[ 5., 11., 17.],
        [11., 25., 39.],
        [17., 39., 61.]])

三、多维矩阵相乘

3维矩阵相乘

>>> a = torch.randn(64, 128, 56)
>>> b = torch.randn(64, 56, 72)

>>> a.shape
torch.Size([64, 128, 56])
>>> b.shape
torch.Size([64, 56, 72])

>>> d = a.matmul(b)  # 多出的一维作为batch提出来,其他部分做矩阵乘法。

>>> d.shape
torch.Size([64, 128, 72])  

# a.mm(b) 这个不行会报错:untimeError: self must be a matrix

4维矩阵相乘

>>> a = torch.randn(64, 3, 128, 56)
>>> b = torch.randn(64, 3, 56, 72)

>>> d = a.matmul(b)  # 多出的维数作为batch提出来,其他部分做矩阵乘法。

>>> d.shape
torch.Size([64, 3, 128, 72])  

# a.mm(b) 这个不行会报错:untimeError: self must be a matrix

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐