[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]
相关推荐
JJJJ_iii1 小时前
【机器学习05】神经网络、模型表示、前向传播、TensorFlow实现
人工智能·pytorch·python·深度学习·神经网络·机器学习·tensorflow
William.csj1 小时前
服务器/Pytorch——对于只调用一次的函数初始化,放在for训练外面和里面的差异
人工智能·pytorch·python
Ingsuifon1 小时前
pytorch踩坑记录
人工智能·pytorch·python
CLubiy1 小时前
【研究生随笔】PyTorch中的概率论
人工智能·pytorch·深度学习·概率论
盼小辉丶2 小时前
PyTorch实战(9)——从零开始实现Transformer
pytorch·深度学习·transformer
张晓~183399481214 小时前
碰一碰发抖音源码技术搭建部署方案
线性代数·算法·microsoft·矩阵·html5
Francek Chen5 小时前
【深度学习计算机视觉】14:实战Kaggle比赛:狗的品种识别(ImageNet Dogs)
人工智能·pytorch·深度学习·计算机视觉·kaggle·imagenet dogs
woshihonghonga6 小时前
PyTorch矩阵乘法函数区别解析与矩阵高级索引说明——《动手学深度学习》3.6.3、3.6.4和3.6.5 (P79)
人工智能·pytorch·python·深度学习·jupyter·矩阵
CLubiy6 小时前
【研究生随笔】Pytorch中的线性代数(微分)
人工智能·pytorch·深度学习·线性代数·梯度·微分
郝学胜-神的一滴7 小时前
矩阵的奇异值分解(SVD)及其在计算机图形学中的应用
程序人生·线性代数·算法·矩阵·图形渲染