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 需要熟悉爱因斯坦求和约定
性能 高度优化(推荐用于标准矩阵乘法) 灵活但可能稍慢
广播支持
批量处理 自动支持 需显式指定批量维度
相关推荐
EkihzniY9 分钟前
AI+OCR:解锁数字化新视界
人工智能·ocr
东哥说-MES|从入门到精通14 分钟前
GenAI-生成式人工智能在工业制造中的应用
大数据·人工智能·智能制造·数字化·数字化转型·mes
铅笔侠_小龙虾1 小时前
深度学习理论推导--梯度下降法
人工智能·深度学习
kaikaile19951 小时前
基于遗传算法的车辆路径问题(VRP)解决方案MATLAB实现
开发语言·人工智能·matlab
lpfasd1231 小时前
第1章_LangGraph的背景与设计哲学
人工智能
Aevget2 小时前
界面组件Kendo UI for React 2025 Q3亮点 - AI功能全面提升
人工智能·react.js·ui·界面控件·kendo ui·ui开发
桜吹雪2 小时前
LangChain.js/DeepAgents可观测性
javascript·人工智能
&&Citrus2 小时前
【杂谈】SNNU公共计算平台:深度学习服务器配置与远程开发指北
服务器·人工智能·vscode·深度学习·snnu
乌恩大侠2 小时前
Spark 机器上修改缓冲区大小
人工智能·usrp
STLearner2 小时前
AI论文速读 | U-Cast:学习高维时间序列预测的层次结构
大数据·论文阅读·人工智能·深度学习·学习·机器学习·数据挖掘