在 PyTorch 中,有多种方法可以执行张量之间的乘法。这里列出了一些常见的乘法操作:
总结:
- 逐元素乘法:
*
ortorch.mul()
- 矩阵乘法:
@
ortorch.mm()
ortorch.matmul()
- 点积:
torch.Tensor.dot()
- 批量矩阵乘法:
torch.bmm()
或torch.matmul()
- 矩阵与向量相乘:
torch.mv(X, w0)
-
逐元素乘法(Element-wise multiplication):
*
ortorch.mul()
()`对应位置的元素相乘,输入张量形状必须相同或可广播。import torchA = torch.tensor([[1, 2], [3, 4]]) B = torch.tensor([[2, 3], [4, 5]])result = A * B print(result)
输出:
tensor([[ 2, 6],[12, 20]])
-
矩阵乘法:
@
ortorch.mm()
ortorch.matmul()
两个矩阵相乘,第一个矩阵的列数必须等于第二个矩阵的行数。import torchA = torch.tensor([[1, 2], [3, 4]]) B = torch.tensor([[2, 3], [4, 5]])result = torch.matmul(A, B) print(result)
输出:
tensor([[10, 13],[22, 29]])
或者使用
@
运算符执行矩阵乘法:result = A @ B print(result)
-
点积(Dot product):
torch.Tensor.dot()
两个一维张量的点积。import torchA = torch.tensor([1, 2, 3]) B = torch.tensor([4, 5, 6])result = torch.dot(A, B) print(result)
输出:
tensor(32)
-
批量矩阵乘法:对于具有更高维度的张量(点积),可以使用
torch.bmm()
或torch.matmul()
进行批量矩阵乘法。import torchA = torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) B = torch.tensor([[[2, 3], [4, 5]], [[6, 7], [8, 9]]])result = torch.bmm(A, B) print(result)
输出:
tensor([[[ 10, 13],[ 22, 29]],[[ 76, 91],[112, 133]]])
两个输入张量的 batch_size
必须相同。此外,第一个输入张量的 num_columns
必须与第二个输入张量的 num_rows
相同。换句话说,输入张量的形状应为 (batch_size, num_rows_A, num_columns_A)
和 (batch_size, num_columns_A, num_columns_B)
。
- 矩阵与向量相乘:
torch.mv(X, w0)
第一个参数是矩阵,第二个参数只能是一维向量,等价于X乘以w0的转置