torch.matmul() VS torch.einsum()

torch.matmul():标准的矩阵乘法

  • 向量-向量(点积)

    python 复制代码
    a = torch.randn(3)  # [3]
    b = torch.randn(3)  # [3]
    c = torch.matmul(a, b)  # 点积,标量输出
  • 矩阵-向量

    python 复制代码
    A = torch.randn(3, 4)  # [3, 4]
    x = torch.randn(4)     # [4]
    y = torch.matmul(A, x) # [3]
  • 矩阵-矩阵

    python 复制代码
    A = torch.randn(3, 4)  # [3, 4]
    B = torch.randn(4, 5)  # [4, 5]
    C = torch.matmul(A, B) # [3, 5]
  • 批量矩阵乘法(更高维张量)

    python 复制代码
    A = torch.randn(2, 3, 4)  # [B, M, K]
    B = torch.randn(2, 4, 5)  # [B, K, N]
    C = torch.matmul(A, B)     # [B, M, N]

    torch.einsum:爱因斯坦求和约定(更通用的张量运算工具)

  • 矩阵乘法

    python 复制代码
    A = torch.randn(3, 4)
    B = torch.randn(4, 5)
    C = torch.einsum("ik,kj->ij", A, B)  # 等价于 A @ B
    
    A = torch.randn(2, 3, 4)  # [B, M, K]
    B = torch.randn(2, 4, 5)  # [B, K, N]
    C = torch.einsum("bik,bkj->bij", A, B)  # [B, M, N]
    
    a = torch.randn(3)
    b = torch.randn(3)
    c = torch.einsum("i,i->", a, b)  # 点积,标量输出
  • 转置

    python 复制代码
    A = torch.randn(3, 4)
    B = torch.einsum("ij->ji", A)  # 等价于 A.T
  • 对角线提取

  • 张量收缩(Tensor Contraction)(高阶张量乘法)

    python 复制代码
    A = torch.randn(2, 3, 4, 5)
    B = torch.randn(2, 4, 5, 6)
    C = torch.einsum("abcd,abde->abce", A, B)  # 对 d 维度收缩
  • 广播运算

torch.matmul torch.einsum
灵活性 仅支持矩阵乘法类操作 支持任意张量运算(转置、收缩等)
可读性 直观(A @ B 需要熟悉爱因斯坦求和约定
性能 高度优化(推荐用于标准矩阵乘法) 灵活但可能稍慢
广播支持
批量处理 自动支持 需显式指定批量维度
相关推荐
GIS数据转换器3 分钟前
基于低空巡检的空地一体智慧治理平台
大数据·人工智能·数据挖掘·数据分析·无人机
ar01234 分钟前
深度解析AR远程专家协助系统在工业4.0时代的变革力量
人工智能·ar
名不经传的养虾人6 分钟前
从0到1:企业级AI项目迭代日记 Vol.31|可视化、可编辑、可脱敏、可隔离——企业系统接管的四个“可”
人工智能·ai编程·ai工作流·企业ai
是梦终空6 分钟前
计算机源码274—基于深度学习的中医舌象智能识别与健康管理系统(源代码+数据库+12000字论文)
人工智能·python·深度学习·opencv·django·vue·springboot
城事漫游Molly7 分钟前
AI 快速生成标准化问卷分析报告:从 SUS 到 UMUX-LITE,如何把“分数”写成“结论”
人工智能·算法·机器学习·论文笔记·科研统计·问卷设计
程序猿阿伟11 分钟前
《OpenClaw Active Memory的智能遗忘与抽象机制》
人工智能
YANQ66211 分钟前
6. Gemini相机+yoloseg+foundationpose环境搭建及应用
人工智能·数码相机
Soari13 分钟前
【紧急发布】Claude Code v2.1.148 :修复 Bash 127 瘫痪 Bug,/simplify 升级为 AI 代码评审
人工智能·bug·bash·claudecode
微祎_13 分钟前
写给新手的 triton-inference-server-ge-backend:昇腾Triton推理服务后端到底是啥?
前端·人工智能·cann