这里总结一下pytorch常用的乘法运算以及相关的运算符(@、*)。
总结放前面:
torch.mm : 用于两个矩阵(不包括向量)的乘法。如维度为(l,m)和(m,n)相乘
torch.bmm : 用于带batch的三维向量的乘法。如维度为(b,l,m)和(b,m,n)相乘
torch.mul : 用于两个同维度矩阵的逐像素点相乘(点乘)。如维度为(l,m)和(l,m)相乘
torch.mv : 用于矩阵和向量之间的乘法(矩阵在前,向量在后)。如维度为(l,m)和(m)相乘,结果的维度为(l)。
torch.matmul : 用于两个张量(后两维满足矩阵乘法的维度)相乘或者是矩阵与向量间的乘法,因为其具有广播机制(broadcasting,自动补充维度)。如维度为(b,l,m)和(b,m,n);(l,m)和(b,m,n);(b,c,l,m)和(b,c,m,n);(l,m)和(m)相乘等。【其作用包含torch.mm、torch.bmm和torch.mv】
@运算符 : 其作用类似于torch.matmul。
*运算符 : 其作用类似于torch.mul。
1、torch.mm
import torch
a = torch.ones(1, 2)
print(a)
b = torch.ones(2, 3)
print(b)
output = torch.mm(a, b)
print(output)
print(output.size())
"""
tensor([[1., 1.]])
tensor([[1., 1., 1.],
[1., 1., 1.]])
tensor([[2., 2., 2.]])
torch.Size([1, 3])
"""
2、torch.bmm
a = torch.randn(2, 1, 2)
print(a)
b = torch.randn(2, 2, 3)
print(b)
output = torch.bmm(a, b)
print(output)
print(output.size())
"""
tensor([[[-0.1187, 0.2110]],
[[ 0.7463, -0.6136]]])
tensor([[[-0.1186, 1.5565, 1.3662],
[ 1.0199, 2.4644, 1.1630]],
[[-1.9483, -1.6258, -0.4654],
[-0.1424, 1.3892, 0.7559]]])
tensor([[[ 0.2293, 0.3352, 0.0832]],
[[-1.3666, -2.0657, -0.8111]]])
torch.Size([2, 1, 3])
"""
3、torch.mul
a = torch.ones(