torch.einsum 是 PyTorch 提供的一个高效的张量运算函数,能够用紧凑的 Einstein Summation 约定(Einstein Summation Convention, Einsum)描述复杂的张量操作,例如矩阵乘法、转置、内积、外积、批量矩阵乘法等。
1. 基本语法
torch.einsum(equation, *operands)
• equation:爱因斯坦求和表示法的字符串,例如 “ij,jk->ik”
• operands:参与计算的张量,可以是多个
2. 基本概念
Einsum 使用 -> 将输入与输出模式分开:
• 左侧:表示输入张量的索引
• 右侧:表示输出张量的索引
• 省略求和索引:会自动对省略的索引进行求和(即 Einstein Summation 规则)
3. torch.einsum 的 10 个常见用法
(1) 矩阵乘法 (torch.mm)
import torch
A = torch.randn(2, 3)
B = torch.randn(3, 4)
C = torch.einsum("ij,jk->ik", A, B) # 矩阵乘法
print(C.shape) # torch.Size([2, 4])
解析:
• ij 表示 A 的形状 (2,3)
• jk 表示 B 的形状 (3,4)
• 由于 j 在 -> 右侧没有出现,因此对其求和,最终得到形状 (2,4)
(2) 向量点积 (torch.dot)
a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])
dot_product = torch.einsum("i,i->", a, b) # 向量点积
print(dot_product) # 输出: 32
解析:
• i,i-> 代表对应位置相乘并求和,等价于 torch.dot(a, b)
(3) 矩阵转置 (torch.transpose)
A = torch.randn(2, 3)
A_T = torch.einsum("ij->ji", A) # 矩阵转置
print(A_T.shape) # torch.Size([3, 2])
解析:
• ij->ji 交换 i 和 j 维度,相当于 A.T
(4) 矩阵外积 (torch.outer)
a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])
outer_product = torch.einsum("i,j->ij", a, b) # 外积
print(outer_product)
# tensor([[ 4, 5, 6],
# [ 8, 10, 12],
# [12, 15, 18]])
解析:
• i,j->ij 生成形状 (3,3) 的矩阵
(5) 批量矩阵乘法 (torch.bmm)
A = torch.randn(5, 2, 3)
B = torch.randn(5, 3, 4)
C = torch.einsum("bij,bjk->bik", A,
105




被折叠的 条评论
为什么被折叠?



