pytorch 的matmult()函数详解

torch.matmul()也是一种类似于矩阵相乘操作的tensor连乘操作。但是它可以利用python中的广播机制,处理一些维度不同的tensor结构进行相乘操作。

matmul 就是矩阵求 叉乘  如果是二维矩阵,两个矩阵的大小应该为m*n ,n*m。

 

一维向量的乘积:对应位置上的数相乘 求和,就是求内积

>>> y = torch.tensor([3,6,7])
>>> x = torch.tensor([1,12,11])
>>> z =torch.matmul(x,y)
>>> z
tensor(152) # 1*3+12*6+11*7 = 152

 二维向量的乘积:错误示范

>>> x1 = torch.tensor([[1,12,11],[9,0,13]])
>>> x1.size()
torch.Size([2, 3])
>>> y1 = torch.tensor([[10,2,7],[5,4,21]])
>>> z1 =torch.matmul(x1,y1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: mat1 and mat2 shapes cannot be multiplied (2x3 and 2x3)
>>>

RuntimeError: mat1 and mat2 shapes cannot be multiplied (2x3 and 2x3)

 二维向量的乘积:正确示范,修改x1矩阵

>>> x1 = torch.tensor([[1,12],[9,0]])
>>> x1.size()
torch.Size([2, 2])
>>> z1 =torch.matmul(x1,y1)
>>> z1
tensor([[ 70,  50, 259],
        [ 90,  18,  63]])
>>>

猜你喜欢

转载自blog.csdn.net/Vertira/article/details/131458877
今日推荐