[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]
相关推荐
盼小辉丶2 小时前
PyTorch强化学习实战(18)——基于DQN处理股票交易问题
pytorch·深度学习·强化学习
C137的本贾尼2 小时前
第8章:把向量组织起来——矩阵与线性变换
线性代数·矩阵
飞猪~21 小时前
Langchain python版本 LLM 重要函数invoke,ainvoke,stream,astream,batch,abatch
python·langchain·batch
hai31524754321 小时前
九章芯片电路集成体系:密度矩阵逆向·全域均衡网络计算总框架
网络·线性代数·矩阵
万亿少女的梦1681 天前
基于深度学习的动物图像分类系统设计与实现
pytorch·深度学习·计算机视觉·图像分类·convnext
木木子221 天前
# 星座配对深度解析:Select 长列表选择器、矩阵评分算法与数据驱动建议
java·算法·华为·矩阵·harmonyos
西西弗Sisyphus2 天前
PyTorch 数据加载:Dataset、DataLoader 与 WeightedRandomSampler 解决类别不平衡
pytorch·python
小白学大数据2 天前
无库无捷径,PyTorch 手写完整 Transformer 大语言模型 LLM
开发语言·pytorch·语言模型·transformer
承渊政道2 天前
【从零开始大模型开发与微调:基于PyTorch与ChatGLM】(基于PyTorch卷积层的MNIST分类实战:从卷积直觉到高效卷积设计)
人工智能·pytorch·神经网络·分类·chatglm·卷积·大模型学习
想会飞的蒲公英3 天前
一个 PyTorch 模型训练的完整流程
人工智能·pytorch·python