pytorch中的矩阵乘法

1. 运算符介绍

关于@运算,*运算,torch.mul(), torch.mm(), torch.mv(), tensor.t()

@ 和 *代表矩阵的两种相乘方式:

@表示常规的数学上定义的矩阵相乘;
*表示两个矩阵对应位置处的两个元素相乘。

1.1 矩阵点乘

*和torch.mul()等同:表示相同shape矩阵点乘,即对应位置相乘,得到矩阵有相同的shape。

一,对应点相乘,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.]])

1.2 矩阵乘法

@和torch.mm(a, b)等同:正常矩阵相乘,要求a的列数与b的行数相同。

torch.mv(X, w0):是矩阵和向量相乘.第一个参数是矩阵,第二个参数只能是一维向量,等价于X乘以w0的转置

二,矩阵相乘,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

1.3 向量乘积

x.dot(y): 向量乘积,x,y均为一维向量。

Y.t():矩阵Y的转置。

ref

  1. https://blog.csdn.net/jizhidexiaoming/article/details/82502724
  2. https://blog.csdn.net/beauthy/article/details/121103704

猜你喜欢

转载自blog.csdn.net/chumingqian/article/details/134226938
今日推荐