[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]
相关推荐
吴佳浩 Alben10 小时前
GPU 生产环境实践:硬件拓扑、显存管理与完整运维体系
运维·人工智能·pytorch·语言模型·transformer·vllm
爱喝纯牛奶的柠檬14 小时前
基于STM32的4*4矩阵软键盘驱动
stm32·嵌入式硬件·矩阵
Frostnova丶15 小时前
LeetCode 48 & 1886.矩阵旋转与判断
算法·leetcode·矩阵
吴佳浩 Alben16 小时前
GPU 编号错乱踩坑指南:PyTorch cuda 编号与 nvidia-smi 不一致
人工智能·pytorch·python·深度学习·神经网络·语言模型·自然语言处理
吴佳浩 Alben16 小时前
CUDA_VISIBLE_DEVICES、多进程与容器化陷阱
人工智能·pytorch·语言模型·transformer
koo36417 小时前
pytorch深度学习笔记23
pytorch·笔记·深度学习
剑穗挂着新流苏31218 小时前
109_神经网络的决策层:线性层(Linear Layer)与数据展平详解
人工智能·pytorch·深度学习
阿Y加油吧19 小时前
力扣打卡——搜索二维矩阵、相交链表
线性代数·leetcode·矩阵
qq_2837200520 小时前
WebGL基础教程(十四):投影矩阵深度解析——正交 vs 透视,从公式推导到实战
线性代数·矩阵·webgl·正交·投影
We་ct21 小时前
LeetCode 74. 搜索二维矩阵:两种高效解题思路
前端·算法·leetcode·矩阵·typescript·二分查找