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 需要熟悉爱因斯坦求和约定
性能 高度优化(推荐用于标准矩阵乘法) 灵活但可能稍慢
广播支持
批量处理 自动支持 需显式指定批量维度
相关推荐
智能砖头12 分钟前
本地文档AI助手:基于LangChain和Qwen2.5的智能问答系统
人工智能·python
聚客AI2 小时前
🛫AI大模型训练到发布一条龙:Hugging Face终极工作流
人工智能·llm·掘金·日新计划
新智元4 小时前
刚刚,谷歌 AI 路线图曝光:竟要抛弃注意力机制?Transformer 有致命缺陷!
人工智能·openai
Maynor9964 小时前
我是如何使用Claude Code
人工智能
知舟不叙4 小时前
基于OpenCV的图像增强技术:直方图均衡化与自适应直方图均衡化
人工智能·opencv·计算机视觉·图像增强
speop4 小时前
【datawhale组队学习】共读AI新圣经
人工智能·学习
Blossom.1184 小时前
基于深度学习的智能图像增强技术:原理、实现与应用
人工智能·python·深度学习·神经网络·机器学习·tensorflow·sklearn
moonsims5 小时前
高开放性具身智能AIBOX平台—专为高校实验室与科研项目打造的边缘计算基座(让高校和科研院所聚焦核心算法)
人工智能
nbsaas-boot5 小时前
技术选型指南:如何选择更适合项目的开源语言及其生态系统
人工智能·架构
AI-星辰5 小时前
始理解NLP:我的第一章学习心得
人工智能·大模型·llm·nlp