torch.matmul
是 PyTorch 中用于执行张量之间的矩阵乘法的函数。它可以用于两个张量之间的矩阵乘法,也可以用于高维张量之间的批量矩阵乘法。
import torch
# 两个张量之间的矩阵乘法
A = torch.tensor([[1, 2], [3, 4]])
B = torch.tensor([[5, 6], [7, 8]])
result = torch.matmul(A, B)
print(result)
# 输出:
# tensor([[19, 22],
# [43, 50]])
# 高维张量之间的批量矩阵乘法
C = torch.randn(2, 3, 4) # shape: (2, 3, 4)
D = torch.randn(2, 4, 5) # shape: (2, 4, 5)
result_batch = torch.matmul(C, D)
print(result_batch.shape) # 输出: torch.Size([2, 3, 5])
在矩阵乘法中,torch.matmul 会根据输入张量的维度自动进行广播,以便进行有效的矩阵乘法运算。