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 需要熟悉爱因斯坦求和约定
性能 高度优化(推荐用于标准矩阵乘法) 灵活但可能稍慢
广播支持
批量处理 自动支持 需显式指定批量维度
相关推荐
dajun18112345619 分钟前
反 AI 生成技术兴起:如何识别与过滤海量的 AI 伪造内容?
人工智能
人邮异步社区41 分钟前
PRML为何是机器学习的经典书籍中的经典?
人工智能·机器学习
paceboy1 小时前
Claude和Cursor之间的切换
人工智能·程序人生
GISer_Jing1 小时前
AI营销增长:4大核心能力+前端落地指南
前端·javascript·人工智能
驴友花雕1 小时前
【花雕动手做】CanMV K230 AI视觉识别模块之使用CanMV IDE调试运行人脸代码
ide·人工智能·单片机·嵌入式硬件·canmv k230 ai视觉·canmv ide 人脸代码
猫头虎1 小时前
又又又双叒叕一款AI IDE发布,国内第五款国产AI IDE Qoder来了
ide·人工智能·langchain·prompt·aigc·intellij-idea·ai编程
weixin_387545641 小时前
Antigravity 上手指南:打造 VS Code 风格的 AI IDE
ide·人工智能
程序届的伪精英1 小时前
IDE TRAE介绍与使用
ide·人工智能
资深程序员 哈克(21年开发经验)1 小时前
2025 年 AI编程软件 IDE 的深入对比与推荐排行:从好用到生成效果的转变
人工智能·ai编程
奇树谦1 小时前
2025 嵌入式 AI IDE 全面对比:Trae、Copilot、Windsurf、Cursor 谁最值得个人开发者入手?
ide·人工智能·copilot