网络编程
位置:首页>> 网络编程>> Python编程>> PyTorch中torch.matmul()函数常见用法总结

PyTorch中torch.matmul()函数常见用法总结

作者:wendy_ya  发布时间:2023-03-28 16:01:31 

标签: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为一维向量)。

2.5 其他

其他的暂时用不上,有需要的可以自行查阅相关资料~

参考:https://cloud.tencent.com/developer/article/1802317

来源:https://blog.csdn.net/didi_ya/article/details/121158666

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com