验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

PyTorch中torch.matmul()函数怎么使用

阅读:630 来源:乙速云 作者:代码code

PyTorch中torch.matmul()函数怎么使用

一、函数介绍

pytorch中两个张量的乘法可以分为两种:

  • 两个张量对应元素相乘,在PyTorch中可以通过torch.mul函数(或*运算符)实现;

  • 两个张量矩阵相乘,在PyTorch中可以通过torch.matmul函数实现;

torch.matmul(input, other) → Tensor
计算两个张量input和other的矩阵乘积
【注意】:matmul函数没有强制规定维度和大小,可以用利用广播机制进行不同维度的相乘操作。

二、常见用法

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

2.1 两个一维向量的乘积运算

若两个tensor都是一维的,则返回两个向量的点积运算结果:

import torch
x = torch.tensor([1,2])
y = torch.tensor([3,4])
print(x,y)
print(torch.matmul(x,y),torch.matmul(x,y).size())

运行结果:

tensor([1, 2]) tensor([3, 4])
tensor(11) torch.Size([])

PyTorch中torch.matmul()函数怎么使用

2.2 两个二维矩阵的乘积运算

若两个tensor都是二维的,则返回两个矩阵的矩阵相乘结果:

import torch
x = torch.tensor([[1,2],[3,4]])
y = torch.tensor([[5,6,7],[8,9,10]])
print(torch.matmul(x,y),torch.matmul(x,y).size())

运行结果:

tensor([[21, 24, 27],[47, 54, 61]]) torch.Size([2, 3])

PyTorch中torch.matmul()函数怎么使用

2.3 一个一维向量和一个二维矩阵的乘积运算

若input为一维,other为二维,则先将input的一维向量扩充到二维(维数前面插入长度为1的新维度),然后进行矩阵乘积,得到结果后再将此维度去掉,得到的与input的维度相同。

import torch
x = torch.tensor([1,2])
y = torch.tensor([[5,6,7],[8,9,10]])
print(torch.matmul(x,y),torch.matmul(x,y).size())

运行结果:

tensor([21, 24, 27]) torch.Size([3])

【分析】:首先将x维度从(2)扩充为(,2),然后将x(,2) 与y(2,3)进行相乘,得到(,3),最后去掉一维部分,得到(3)

PyTorch中torch.matmul()函数怎么使用

2.4 一个二维矩阵和一个一维向量的乘积运算

若input为二维,other为一维,则先将other的一维向量扩充到二维(维数后面插入长度为1的新维度),然后进行矩阵乘积,得到结果后再将此维度去掉,得到的与other的维度相同。

import torch
x = torch.tensor([[1,2,3],[4,5,6]])
y = torch.tensor([7,8,9])
print(torch.matmul(x,y),'n',torch.matmul(x,y).size())

运行结果:

tensor([ 50, 122])
torch.Size([2])

【分析】:首先y维度从(3)扩充为(3,),然后将x(2,3)与x(2,)进行相乘,得到(2,),最后去掉一维部分,得到(2)

【总结】:2.3和2.4基本类似,唯一不同的是2.3中一维向量和二维矩阵的乘积运算需要在一维向量前面插入长度为1的新维度(x为一维向量,y为二维矩阵);2.4中二维矩阵和一维向量的乘积运算需要在一维向量后面插入长度为1的新维度(x为二维矩阵,y为一维向量)。

分享到:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>