[pytorch基础操作] 矩阵batch乘法大全(dot,* 和 mm,bmm,@,matmul)

逐元素相乘

逐元素相乘是指对应位置上的元素相乘,要求张量的形状相同

torch.dot

按位相乘torch.dot:计算两个张量的点积(内积),只支持1D张量(向量),不支持broadcast。

python 复制代码
import torch

# 创建两个向量
a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])
# 计算点积
result = torch.dot(a, b)
print(result)  # 输出: tensor(32)

*

*: 逐元素相乘,适用于任何维度的张量,要求张量的形状相同。

python 复制代码
import torch

# 创建两个张量
a = torch.randn(2, 3, 4)
b = torch.randn(2, 3, 4)

# 逐元素相乘
result = a * b
print(result.shape)

矩阵乘法

矩阵乘法,执行矩阵乘法,前行乘后列,要求第一个矩阵的列数(tensor1.shape[-1])第二个矩阵的行数(tensor2.shape[-2])相等。如shape=(n,r)乘shape=(r,m)

torch.mm

torch.mm: 执行两个矩阵的乘法,适用于2D张量(矩阵)(h,w)/(seq_len,dim),不支持broadcast。

python 复制代码
import torch

# 创建两个矩阵
a = torch.rand(2,3)
b = torch.rand(3,2)

# 计算矩阵乘法
result = torch.mm(a, b)
print(result.shape)  # [2,2]

torch.bmm

torch.bmm: 执行两个批次矩阵的乘法,适用于3D张量(b,h,w)/(b,seq_len,dim),不支持broadcast。

python 复制代码
import torch

# 创建两个批次矩阵
batch1 = torch.randn(10, 3, 4)  # 10个3x4的矩阵
batch2 = torch.randn(10, 4, 5)  # 10个4x5的矩阵

# 计算批次矩阵乘法
result = torch.bmm(batch1, batch2)
print(result.shape)  # [10, 3, 5]

@ 和 torch.matmul

@torch.matmul: 两者完全等价,执行任意维度 两个张量的矩阵乘法,支持张量的broadcast广播规则。

python 复制代码
import torch

# 创建两个张量
a = torch.randn(2, 8, 128, 64)
b = torch.randn(2, 8, 64, 128)

# 使用 @ 运算符进行矩阵乘法
result = a @ b
print(result.shape)  # [2, 8, 128, 128]

# 使用 torch.matmul 进行矩阵乘法
result = torch.matmul(a, b)
print(result.shape)  # [2, 8, 128, 128]
相关推荐
硕风和炜5 小时前
【LeetCode:3033. 修改矩阵 + 模拟】
java·算法·leetcode·矩阵·模拟
WoShop商城源码5 小时前
视频号矩阵源码:构建短视频生态的基石
线性代数·矩阵
当年拼却醉颜红6 小时前
力扣爆刷第161天之TOP100五连刷71-75(搜索二叉树、二维矩阵、路径总和)
算法·leetcode·矩阵
只是有点小怂7 小时前
【chatgpt】pytorch打印模型model参数,使用parameters()方法和named_parameters()方法
人工智能·pytorch
迅狐源码工厂10 小时前
如何选择快手矩阵系统:打造高效短视频营销的指南
大数据·人工智能·矩阵
hlyling10 小时前
一键高效处理,批量缩放PNG图片,按比例轻松调整,高效工作从此开始!
javascript·python·c#·objective-c·batch·symfony
只是有点小怂12 小时前
【PYG】 PyTorch中size方法和属性
人工智能·pytorch·python
每天努力进步!16 小时前
LeetCode热题100刷题8:54. 螺旋矩阵、73. 矩阵置零、48. 旋转图像
c++·算法·leetcode·矩阵
迅狐源码工厂18 小时前
如何选择视频号矩阵系统:打造高效短视频内容生态的指南
人工智能·线性代数·矩阵
可惜我是水瓶座__1 天前
【LeetCode】螺旋矩阵
算法·leetcode·矩阵