[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]
相关推荐
mailangduoduo20 分钟前
pytorch入门级项目--基于卷积神经网络的数字识别
人工智能·pytorch·cnn
Daitu_Adam5 小时前
Windows11安装GPU版本Pytorch2.6教程
人工智能·pytorch·python·深度学习
阿正的梦工坊5 小时前
Grouped-Query Attention(GQA)详解: Pytorch实现
人工智能·pytorch·python
next_travel6 小时前
图像分割UNet、生成模型SD及IP-Adapter
pytorch·深度学习·计算机视觉
东木月6 小时前
windows安装pytorch
人工智能·pytorch·windows
阿正的梦工坊7 小时前
Sliding Window Attention(滑动窗口注意力)解析: Pytorch实现并结合全局注意力(Global Attention )
人工智能·pytorch·python
阿正的梦工坊8 小时前
PyTorch下三角矩阵生成函数torch.tril的深度解析
人工智能·pytorch·矩阵
大数据追光猿10 小时前
【深度学习】Pytorch项目实战-基于协同过滤实现物品推荐系统
人工智能·pytorch·python·深度学习·ai编程·推荐算法
啊哈哈哈哈哈啊哈哈14 小时前
J4打卡—— ResNet 和 DenseNet结合实现鸟类分类
人工智能·pytorch·分类
余~~185381628001 天前
矩阵碰一碰发视频的后端源码技术,支持OEM
线性代数·矩阵·音视频