当前位置:首页 > 编程笔记 > 正文
已解决

pytorch中的矩阵乘法

来自网友在路上 168868提问 提问时间:2023-11-07 07:22:54阅读次数: 68

最佳答案 问答题库688位专家为你答疑解惑

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
查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"pytorch中的矩阵乘法":http://eshow365.cn/6-34350-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!